Search code examples
c#algorithmfinancialmoving-average

How to calculate simple moving average faster in C#?


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.


Solution

  • 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)

    decimal buffer[] = new decimal[period];
    decimal output[] = new decimal[data.Length];
    current_index = 0;
    for (int i=0; i<data.Length; i++)
        {
            buffer[current_index] = data[i]/period;
            decimal ma = 0.0;
            for (int j=0;j<period;j++)
                {
                    ma += buffer[j];
                }
            output[i] = ma;
            current_index = (current_index + 1) % period;
        }
    return output;
    

    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.