The Moving-Average Filter
The simplest filter averages the last samples. It is everywhere, from stock charts to sensor smoothing, and it is the best filter for one job: reducing white noise while keeping a sharp step response. Its frequency response, however, is a poor low-pass, and understanding why is a good first exercise in reading filters in the frequency domain.
Definition and frequency response
The magnitude is a periodic sinc (Dirichlet kernel) with zeros at : a moving average of length completely removes frequencies . The phase is linear, a delay of samples.
import numpy as np
M, fs = 5, 100.0
h = np.ones(M) / M
for f in (0, 5, 10, 20, 30, 40, 50):
w = 2 * np.pi * f / fs
H = np.sum(h * np.exp(-1j * w * np.arange(M)))
db = 20 * np.log10(abs(H)) if abs(H) > 1e-9 else float("-inf")
print(f"{f:2d} Hz: gain {abs(H):.4f} ({db:6.1f} dB)") 0 Hz: gain 1.0000 ( 0.0 dB)
5 Hz: gain 0.9040 ( -0.9 dB)
10 Hz: gain 0.6472 ( -3.8 dB)
20 Hz: gain 0.0000 ( -inf dB)
30 Hz: gain 0.2472 ( -12.1 dB)
40 Hz: gain 0.0000 ( -inf dB)
50 Hz: gain 0.2000 ( -14.0 dB)
The gain is exactly 0 at 20 and 40 Hz () but rises again to about 0.25 at 30 Hz and 0.2 at 50 Hz: large sidelobes, only about dB below the passband. Frequency selectivity is poor.
What it is good at
For white noise of variance , the average of samples has variance , the best possible reduction among filters with a step response as fast (it reaches the new level in exactly samples). That makes it optimal for time-domain smoothing:
import numpy as np
rng = np.random.default_rng(6)
n = 20000
signal = np.where(np.arange(n) < n // 2, 0.0, 1.0) # a step in the middle
x = signal + 0.3 * rng.normal(size=n)
for M in (1, 4, 16, 64):
y = np.convolve(x, np.ones(M) / M)[:n]
noise_std = np.std(y[100:n // 2]) # long flat region before the step
clean_step = np.convolve(signal, np.ones(M) / M)[:n]
settle = int(np.argmax(clean_step[n // 2:] > 0.999)) + 1 # noise-free: samples to reach the new level
print(f"M={M:3d}: noise std {noise_std:.3f} (0.3/sqrt(M) = {0.3 / np.sqrt(M):.3f}) step settles after {settle} samples")M= 1: noise std 0.302 (0.3/sqrt(M) = 0.300) step settles after 1 samples
M= 4: noise std 0.153 (0.3/sqrt(M) = 0.150) step settles after 4 samples
M= 16: noise std 0.077 (0.3/sqrt(M) = 0.075) step settles after 16 samples
M= 64: noise std 0.039 (0.3/sqrt(M) = 0.037) step settles after 64 samples
Cascades and fast computation
Running the moving average twice gives a triangular kernel, three times a smooth bell (this is how fast Gaussian blur approximations work). A moving average also has an recursive form, , the cumulative-sum trick:
import numpy as np
rng = np.random.default_rng(7)
x = rng.normal(size=20)
M = 4
c = np.concatenate([[0.0], np.cumsum(x)])
fast = (c[M:] - c[:-M]) / M # averages of each full window
direct = np.convolve(x, np.ones(M) / M, mode="valid")
print("cumulative-sum version matches:", np.allclose(fast, direct))
print("kernel after 3 passes:", np.round(np.convolve(np.convolve(np.ones(4), np.ones(4)), np.ones(4)) / 64, 4).tolist())cumulative-sum version matches: True
kernel after 3 passes: [0.0156, 0.0469, 0.0938, 0.1562, 0.1875, 0.1875, 0.1562, 0.0938, 0.0469, 0.0156]
In software
pandas.Series.rolling(M).mean(),np.convolve(x, np.ones(M)/M),scipy.ndimage.uniform_filter.- Trading "SMA" indicators are moving averages; their lag of samples is the linear phase above.
Exercises
Exercise 1: Remove a hum
With Hz, what moving-average length completely removes 50 Hz hum and all its harmonics?
Answer
(or any multiple of 20).
Solution
Zeros sit at ; we need , so . Averaging over exactly one hum period cancels it.
Exercise 2: Delay
What delay does a 31-point moving average introduce?
Answer
15 samples.
Solution
The linear phase corresponds to a delay of samples. A centered (non-causal) average avoids the delay in offline processing.
Exercise 3: Hum removal check (code)
Apply a 20-point moving average to sampled at 1000 Hz. What is left after the start-up?
Answer
Essentially zero (about ).
Solution
import numpy as np
fs = 1000
t = np.arange(0, 1, 1 / fs)
y = np.convolve(np.sin(2 * np.pi * 50 * t), np.ones(20) / 20, mode="valid")
print(float(np.max(np.abs(y))) < 1e-12)True
Test yourself
An -point moving average completely removes the frequencies…
- above
- for
- below
- none
Averaging samples of white noise reduces its standard deviation by…
- 2
The moving average is a poor low-pass filter because…
- it is nonlinear
- its sidelobes are high, only about dB
- it is unstable
- it has no delay