Weighted Moving Average: Normalising Any Weights

Time SeriesEasy+10 XP+10

Weighted Moving Average: Normalising Any Weights

A simple moving average gives the oldest value in its window exactly as much say as the newest. For most series that's wrong — recent readings are more informative. A weighted moving average fixes it by letting you choose the weights.

wmat=∑iwi⋅xt+i∑iwiwma_t = \frac{\sum_i w_i \cdot x_{t+i}}{\sum_i w_i}wmat​=∑i​wi​∑i​wi​⋅xt+i​​

Task: write wma(series, weights) returning one value per window position, each rounded to 4 decimal places.

  • The window length is len(weights). Slide it along the series one step at a time, so the output has len(series) - len(weights) + 1 entries.
  • weights[0] pairs with the oldest value in the window and the last weight with the newest. So [1, 2] weights the newer value twice as heavily.
  • Divide by the sum of the weights. They don't have to add up to 1 — handling that is your job, which is what makes [1, 2] and [0.333, 0.667] behave identically.
  • Weights are positive.

That normalisation is what keeps the output on the same scale as the input. Skip it and [1, 2] would inflate every value threefold — a drift that looks like a signal.

The useful sanity check: all-equal weights must reproduce the simple moving average exactly, and a window over constant values must return that constant whatever the weights are.

Examples

series = [1, 2, 3, 4]
weights = [1, 2]
returns [1.6667, 2.6667, 3.6667]
series = [10, 20, 30]
weights = [1, 1, 1]
returns [20.0]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run