Search code examples
javamoving-average

Simple Moving Average for stock prices


I was playing with ActiveQuant FinancialLibrary SimpleMovingAverage function SMA() below:

Is there an error in the algo below, where it calculates the average by looking "into the future" ( as it does i < (period + skipdays) ) ?

public static double SMA(int period, double[] vals, int skipdays) {
    double value = 0.0;
    for (int i = skipdays; i < (period + skipdays); i++) {
        value += vals[i];
    }
    value /= (double) period;
    return value;
}

The for loop can be replaced with that below, where it looks backward.

    for (int i = skipdays - period; i < skipdays; i++) {
        value += vals[i];
    }

Am I missing something?


Solution

  • I see no error. The algorithm correctly computes the mean value of the data array from index skipdays (inclusive) to index skipdays + period (exclusive) for period > 0.

    Perhaps you need to rephrase the question.