TExcelTAD
Home › Fourier Analysis & Signals › The Moving-Average Filter

The Moving-Average Filter

The simplest filter averages the last MM 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

y[n]=1M∑k=0M−1x[n−k],H(eiω)=1M sin⁡(Mω/2)sin⁡(ω/2) e−iω(M−1)/2y[n] = \frac{1}{M}\sum_{k=0}^{M-1} x[n - k], \qquad H(e^{i\omega}) = \frac{1}{M}\,\frac{\sin(M\omega/2)}{\sin(\omega/2)}\, e^{-i\omega(M-1)/2}

The magnitude is a periodic sinc (Dirichlet kernel) with zeros at ω=2πk/M\omega = 2\pi k/M: a moving average of length MM completely removes frequencies kfs/Mk f_s / M. The phase is linear, a delay of (M−1)/2(M - 1)/2 samples.

python · try it yourself
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 (=k⋅100/5= k \cdot 100/5) but rises again to about 0.25 at 30 Hz and 0.2 at 50 Hz: large sidelobes, only about −12-12 dB below the passband. Frequency selectivity is poor.

What it is good at

For white noise of variance σ2\sigma^2, the average of MM samples has variance σ2/M\sigma^2/M, the best possible reduction among filters with a step response as fast (it reaches the new level in exactly MM samples). That makes it optimal for time-domain smoothing:

python · try it yourself
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 O(1)O(1) recursive form, y[n]=y[n−1]+(x[n]−x[n−M])/My[n] = y[n-1] + (x[n] - x[n - M])/M, the cumulative-sum trick:

python · try it yourself
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 (M−1)/2(M-1)/2 samples is the linear phase above.

Exercises

Exercise 1: Remove a hum

With fs=1000f_s = 1000 Hz, what moving-average length completely removes 50 Hz hum and all its harmonics?

Answer

M=20M = 20 (or any multiple of 20).

Solution

Zeros sit at kfs/Mk f_s/M; we need fs/M=50f_s/M = 50, so M=20M = 20. 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 (M−1)/2=15(M - 1)/2 = 15 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 sin⁡(2π⋅50t)\sin(2\pi \cdot 50 t) sampled at 1000 Hz. What is left after the start-up?

Answer

Essentially zero (about 10−1610^{-16}).

Solution
python · try it yourself
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 MM-point moving average completely removes the frequencies…

  1. above fs/Mf_s/M
  2. kfs/Mk f_s / M for k=1,2,…k = 1, 2, \ldots
  3. below fs/Mf_s/M
  4. none

Averaging MM samples of white noise reduces its standard deviation by…

  1. MM
  2. M\sqrt{M}
  3. M2M^2
  4. 2

The moving average is a poor low-pass filter because…

  1. it is nonlinear
  2. its sidelobes are high, only about −13-13 dB
  3. it is unstable
  4. it has no delay