This method gives you an approximation of the moving average by basically assuming that the value of the sample window_size
samples ago is equal to the previous moving average, which is updated every window_size
samples.
It works well if your values are randomly distributed, but outliers will skew it more than the exact moving average.
previous_average = 0
total = 0
for count, sample in enumerate(samples):
if count % window_size == 0: # Update previous_average every window_size samples
previous_average = total/window_size
total += sample
if count > window_size:
total -= previous_average
current_average = total/window_size
With the 4 point example we can estimate the error:
$\begin{align}
y_n = \frac{(a + b + c + d)}{4} &, y_{n+1} = \frac{(a+b+c+d)}{4} + \frac{e}{4} - \frac{a}{4} \\
y*_{n+1} &= \frac{(a + b + c + d) - y_{n} + e}{4} \\
&= \frac{(a+b+c+d)}{4} - \frac{(a+b+c+d)}{16} + \frac{e}{4} \\
&= \frac{3(a+b+c+d)}{16} + \frac{e}{4} \\
\end{align}$
$\begin{align}
E &= y*_{n+1} - y_{n+1} \\
&= \frac{3a}{16} - \frac{a+b+c+d}{16}
\end{align}$
I am lazily going to assume that with an arbitrary window size $W$
$\begin{align}
E &= \frac{(W-1)a}{W^2} - \frac{y_n}{W} \\
\end{align}$
If $W$ is large enough, then:
$\begin{align}
E &\approx \frac{a - y_n}{W}
\end{align}$
Which is the residual of point $a$ divided by the total number of residuals...
This is just an approximation of the error for the first count % window_size == 0
iteration, and I'm already trying to go further than my maths abilities, but since we can start at any $x_n = a$ it suggests that as long as $W$ is sufficiently large or each $x_{n} - y_{n}$ is sufficiently small then this average will produce the same average residual as a fit with the exact formula.
I've attached an image from my test script showing the exact 100 point moving average compared to this method:
