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.
These days, the Math DotNet library has a class called
RunningStatistics
that will do this for you. If you want to do it over the last "X" items only, useMovingStatistics
instead.Both will calculate running averages, variance, and standard deviation, on the fly with one-pass only and without storing extra copies of the data.
If the data is static, you can preprocess the array to make moving average queries very fast:
Now the moving average calculation is easy and fast:
Here's how I tried it. But warning I'm a complete amateur so this may be completely wrong.
Should return a list of decimals containing the moving averages for your data.