Exponential Moving Average: One Running Number

Time SeriesEasy+10 XP+10

Exponential Moving Average: One Running Number

A simple moving average treats every value in its window equally and forgets everything outside it. An exponential moving average instead keeps a single running number, mixing each new value into it:

et=αxt+(1−α)et−1e_t = \alpha x_t + (1 - \alpha) e_{t-1}et​=αxt​+(1−α)et−1​

So the newest value gets weight α, the one before it α(1-α), the one before that α(1-α)², and so on — every past value still contributes, with influence fading geometrically.

Task: write ema(series, alpha) returning one smoothed value per input value, each rounded to 4 decimal places.

  • The seeding rule: the first output is simply series[0]. There's no earlier estimate to mix with, and starting from zero instead would drag the whole front of the series toward the origin.
  • alpha is between 0 and 1. At alpha = 1 the EMA has no memory and just copies the input; small values make it slow and smooth.
  • The output is the same length as the input.
  • Round each output as you emit it, but carry the unrounded running value forward. Feeding rounded values back in accumulates error down the series.

The appeal over a windowed average is that it needs no window. One number holds the entire history, so it costs the same memory whether you're smoothing ten points or ten million — which is why it's the default in streaming systems, and why the same recursion turns up inside Adam and momentum.

Examples

series = [10, 20, 30]
alpha = 0.5
returns [10.0, 15.0, 22.5]
series = [1, 2, 3, 4]
alpha = 1.0
returns [1.0, 2.0, 3.0, 4.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