What is the fastest library/algorithm for calculating simple moving average? I wrote my own, but it takes too long on 330 000 items decimal dataset.
- period / time(ms)
- 20 / 300;
- 60 / 1500;
- 120 / 3500.
Here is the code of my method:
public decimal MA_Simple(int period, int ii) {
if (period != 0 && ii > period) {
//stp.Start();
decimal summ = 0;
for (int i = ii; i > ii - period; i--) {
summ = summ + Data.Close[i];
}
summ = summ / period;
//stp.Stop();
//if (ii == 1500) System.Windows.Forms.MessageBox.Show((stp.ElapsedTicks * 1000.0) / Stopwatch.Frequency + " ms");
return summ;
} else return -1;
}
The Data.Close[]
is a fixed size(1 000 000) decimal array.
This is MA I'm using in my app.
Once you have it calculated for the whole data series, you can grab a particular value instantly.
Your main problem is that you throw away too much information for each iteration. If you want to run this fast, you need to keep a buffer of the same size as the frame length.
This code will run moving averages for your whole dataset:
(Not real C# but you should get the idea)
Please note that it may be tempting to keep a running cumsum instead of keeping the whole buffer and calculating the value for each iteration, but this does not work for very long data lengths as your cumulative sum will grow so big that adding small additional values will result in rounding errors.
How about
Queue
?Usage:
The current (accepted) solution contains an inner loop. It would be more efficient to remove this as well. You can see how this is achieved here:
How to efficiently calculate a moving Standard Deviation
You don't need to keep a running queue. Just pick the latest new entry to the window and drop off the older entry. Notice that this only uses one loop and no extra storage other than a sum.
One C function, 13 lines of codes, simple moving average. Example of usage: