As requested -- // CalculateMovingAverageLooping.afl // // Calculate a simple moving average using looping code // // Howard Bandy // June 2010 //
// In Formula Editor, click Apply Indicator. // Note that all three moving averages are the same // Plot the price series Plot( C, "C", colorBlack, styleLine ); MALen = 10; // Assume the afl statement to be replicated is: MAAFL = MA( C, MALen ); // Plot the builtin simple moving average Plot( MAAFL, "MAAFL", colorBlue, styleLine ); // A couple of ways to compute the simple moving // average using looping code follow. // This example is coded for clarity, rather than for efficiency // // Initialize the bars for which there are insufficient // bars for a full moving average to be the closing price // for each of those bars. for ( i = 0; i < MALen; i++ ) { MALoop1[i] = C[i]; } // TempSum holds the sum of the values being averaged // TempSum is a scalar. for ( i = MALen; i < BarCount; i++ ) { TempSum = 0; for ( j = 0; j < MALen; j++ ) { TempSum = TempSum + C[i-j]; } MALoop1[i] = TempSum / MALen; } Plot( MALoop1, "MALoop1", colorGreen, styleLine ); // This example is a little more efficient // for ( i = 0; i < MALen; i++ ) { MALoop2[i] = C[i]; } TempSum = 0; for ( j = 0; j < MALen; j++ ) { TempSum = TempSum + C[MALen-1-j]; } for ( i = MALen; i < BarCount; i++ ) { // Drop off the oldest value and add the newest TempSum = TempSum - C[i-MALen] + C[i]; MALoop2[i] = TempSum / MALen; } Plot( MALoop2, "MALoop2", colorRed, styleLine ); /////////////// end ////////////////////