Sub topic 11
Exponentially weighted windows
This chapter assumes you can use rolling and expanding on a Series, understand min_periods, and know the basic statistics (mean, standard deviation). Rolling windows treat every row inside the window equally and ignore every row outside it. Exponentially weighted windows replace that hard boundary with weights that fade smoothly with age.
How the weighting works
An exponentially weighted (EW) mean uses all earlier rows. The newest row gets weight 1, the one before it gets weight (1 - alpha), the one before that (1 - alpha)**2, and so on. The smoothing factor alpha is a number between 0 and 1. A larger alpha forgets the past faster.
You call ewm on a Series or DataFrame, then choose an aggregation.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.ewm(span=3).mean())
# 0 1.000000
# 1 1.666667
# 2 2.428571
# 3 3.266667
# 4 4.161290
# 5 5.095238
# dtype: float64Unlike rolling(3).mean(), this output has no leading NaN. The first row is just its own value, because it is the only value seen so far. Each later result is a weighted average of everything up to that row, with recent rows counting most.
Choosing the decay: span, com, halflife, alpha
You specify the decay with exactly one of four parameters. They are different ways to express the same alpha.
| Parameter | Meaning | Relation to alpha |
|---|---|---|
| `span` | Roughly the number of rows that matter, like a window length | `alpha = 2 / (span + 1)` |
| `com` | Center of mass | `alpha = 1 / (1 + com)` |
| `halflife` | Rows until a weight drops to half | `alpha = 1 - exp(-ln(2) / halflife)` |
| `alpha` | The smoothing factor itself | none |
span=3 gives alpha=0.5. Use span when you think in window lengths. Use halflife when you can say "a reading should count half as much after 5 days". Passing two of these parameters raises a ValueError.
The adjust parameter
By default adjust=True. Each result divides by the sum of the weights used so far, so early rows are weighted averages with a correct denominator. This is the output you saw above.
With adjust=False, pandas uses the recursive form y[t] = (1 - alpha) * y[t-1] + alpha * x[t]. This is the textbook exponential moving average, and it starts from the first value without normalizing.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.ewm(span=3, adjust=False).mean())
# 0 1.00000
# 1 1.50000
# 2 2.25000
# 3 3.12500
# 4 4.06250
# 5 5.03125
# dtype: float64The two versions differ most near the start of the data and converge as more rows accumulate. Pick one on purpose. If you must match another tool's EMA, check which form it uses.
Comparison with rolling windows
Rolling and EW windows answer slightly different questions.
- A rolling mean forgets a value abruptly. When a spike leaves the window, the mean drops suddenly.
- An EW mean fades a spike gradually, so the output is smoother and reacts quickly to new data.
- A rolling window needs
windowrows before it reports (unless you setmin_periods). An EW window reports from the first row, though early values rest on little data. - A rolling window has a fixed memory. An EW window technically remembers everything, but old weights become negligible.
Other aggregations and missing values
ewm supports mean, sum, std, var, cov and corr. For example, s.ewm(halflife=2).std() gives a volatility estimate that emphasizes recent changes.
The min_periods parameter defaults to 0 here, which is why there are no leading NaN values. Set min_periods=3 if you want the first results hidden until enough rows exist.
Missing values are skipped by default (ignore_na=False still accounts for the gap in the weights). For irregular timestamps, pass a times argument together with halflife, and the decay is measured in elapsed time instead of row counts.
Exercise
Exercise
What does pd.Series([2, 4, 8]).ewm(alpha=0.5, adjust=False).mean() return, and why is the first value not NaN?
Show answer
It returns 2.0, 3.0, 5.5. With adjust=False the first value is the first observation (2). Then y1 = 0.54 + 0.52 = 3.0 and y2 = 0.58 + 0.53 = 5.5. There is no NaN because ewm has min_periods=0 by default, so it reports from the first row.