# What is an Efficient way to calculate Simple moving average without saving previous N period values?

I want to calculate the Simple Moving Average (SMA) for Stock Prices with for period 'N'.

Normal Formula for 4 Period Moving Average is

MA = (a + b + c + d) / 4

for new entry e we do as following:

MA(new) = (b + c + d + e) / 4

Problem here is that I need to store for the N period's prices. I have tried for multiple things like

New Average = {(Old_Average x N) + (New_Data_Point - Old_Average)}/N

but I am loosing on precision.

This is impossible. You need to remember the tail.

I'd suggest using exponential smoothing in this case. Otherwise, for a simple moving average you'd have to apply some kind of an approximation. There's no point in doing so in my opinion.

• You can easily store the tail in, for example, a circular buffer en.wikipedia.org/wiki/Circular_buffer . It is very easy to program. Apr 29 '17 at 20:39
• @AlexC Hi Alex, the reason behind not maintaining the tail is that the trading strategy is a positional one and not an intraday. And the system doesn't allows multiple values from a previous day to be carried for the next day (due to some system shortcomings). Hence if I am checking if carrying just a Single last SMA value of day 1 to the day 2 is enough or not! Apr 30 '17 at 16:57

Have you tried a moving average utilising exponential-decays? It is calculated via an updating rule as you desire, I guess the downside is that it isn't of finite 'memory' like the moving averages that you mention.

It would be defined as x(t) = x(t-1)*L + (1-L)*y(t) where x(t) is the value of the moving average, y(t) is the new value of the series you are calculating the moving average of and 0 < L < 1 is a fixed parameter that control the 'length' of the moving average window (as L moves down from 1 to 0, the window reduces in length)

You need the tail for precision, but you can estimate as follows:

The mean, $\mu$, as set of integers $[X_i, X_{i+1},\ldots, X_N ]$ is defined thus:

$\Large{\mu_{X} = \frac{\sum_n^N X_i}{N}}$

To estimate the mean at $n$, you could simply do the following:

$\Large{\mu_{X,n} \approx \frac{1}{N}X_n + \frac{N-1}{N}\mu_{X,n-1} }$

See the following thread for a related question on using exponential weighting: Is there a non-recursive way of calculating the exponential moving average?

• Thanks for the way out. I'll try out something of this sort! Apr 30 '17 at 16:55