Sub topic 11
Exponentially weighted windows
This chapter assumes you know rolling(window).mean(), how min_periods handles leading NaN values, and how expanding() accumulates from the first row. You should also be comfortable reading a Series printed in the console.
Why weight observations differently
A rolling window treats every row inside it equally. A row has full weight while it is in the window and zero weight once it leaves. This causes two problems:
- A single spike raises the rolling mean for exactly
windowrows, then the mean drops abruptly when the spike leaves. - You must pick a hard cutoff. A row 29 days old counts fully, and a row 31 days old counts for nothing.
An expanding window has the opposite problem. It never forgets, so old data can dominate.
An exponentially weighted (EW) window sits between the two. Every earlier row contributes, but its weight shrinks by a constant factor for each step back in time. Recent rows matter most, old rows fade, and nothing is dropped suddenly. In pandas you get this with ewm().
The basic call
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.ewm(span=3).mean())The result has no leading NaN values, unlike rolling(3).mean(). The default is min_periods=0, so the first output is simply the first value. The output is:
0 1.000000
1 1.666667
2 2.428571
3 3.266667
4 4.161290
5 5.095238
dtype: float64These values lag behind the data, as any smoothed average does. The rolling mean over the same data reaches 5.0 at the last row, while the EW mean reaches about 5.10. The EW mean is still pulled down by the old small values, though less each step.
ewm() returns an ExponentialMovingWindow object, in the same way that rolling() returns a Rolling object. You then call an aggregation on it. The supported ones include mean(), std(), var(), corr() and cov().
How the weights work
Let alpha be the smoothing factor, a number in the interval (0, 1]. A row that is i steps older than the current row gets the relative weight (1 - alpha) ** i. With alpha = 0.5, the current row has weight 1, the previous row 0.5, the one before that 0.25, and so on.
The weights never reach zero, so in theory every earlier row contributes. In practice the contribution of old rows becomes negligible quickly.
Choosing the decay: com, span, halflife, alpha
You specify the decay in exactly one of four ways. Passing more than one raises a ValueError. Passing none also raises an error, unless you use a time-based halflife with times.
| Parameter | Meaning | Relation to alpha | Valid range |
|---|---|---|---|
| `alpha` | The smoothing factor itself | `alpha` | 0 < alpha <= 1 |
| `span` | Roughly the number of recent rows that matter | `2 / (span + 1)` | span >= 1 |
| `com` | Center of mass | `1 / (1 + com)` | com >= 0 |
| `halflife` | Steps for a weight to fall to one half | `1 - 0.5 ** (1 / halflife)` | halflife > 0 |
For alpha = 0.5, the equivalent settings are span=3, com=1 and halflife=1. The following code confirms that all four produce identical results:
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
a = s.ewm(alpha=0.5).mean()
b = s.ewm(span=3).mean()
c = s.ewm(com=1).mean()
d = s.ewm(halflife=1).mean()
print(a.equals(b), a.equals(c), a.equals(d))equals can in principle return False because of tiny floating-point differences in how each parameter is converted to alpha. If it does on your machine, compare with np.allclose instead.
Use whichever parameter matches how you think about the problem:
- Use
spanwhen you want a drop-in comparison with an N-row rolling window. It is not the same smoothing, but it is similar in responsiveness. - Use
halflifewhen you can say how long information stays relevant, such as "a reading loses half its influence after 7 days". - Use
alphawhen a formula or paper gives you the smoothing factor directly. - Use
comwhen you are following a source that defines it, as many finance texts do.
A larger span, com or halflife means slower decay and a smoother, laggier result. A larger alpha means faster decay and a more responsive result.
Comparing with a rolling mean
The next example uses a single spike to show how the two kinds of window behave.
import pandas as pd
x = pd.Series([10, 10, 10, 50, 10, 10, 10])
out = pd.DataFrame({
"x": x,
"rolling3": x.rolling(3).mean(),
"ewm": x.ewm(span=3, adjust=False).mean(),
}).round(2)
print(out)The output is:
x rolling3 ewm
0 10 NaN 10.00
1 10 NaN 10.00
2 10 10.00 10.00
3 50 23.33 30.00
4 10 23.33 20.00
5 10 23.33 15.00
6 10 10.00 12.50The rolling mean jumps to 23.33 and stays flat for three rows. It then falls back to exactly 10 when the spike leaves the window. The EW mean reacts more strongly on the spike row (30.00), then decays smoothly (20.00, 15.00, 12.50). It never forgets the spike completely, but the spike's influence keeps shrinking.
The adjust option
The earlier example with span=3 printed 1.666667 for the second row, but this one gives 1.5 for the same setup. The difference is the adjust parameter, which defaults to True.
- With
adjust=True, each output is a weighted average over all rows so far. The weights are(1 - alpha) ** i, and they are divided by their sum. Early outputs therefore use the weights that actually exist, and the result is not biased toward the start. - With
adjust=False, pandas uses the recursive formulay[t] = (1 - alpha) * y[t-1] + alpha * x[t], withy[0] = x[0]. This is the classic exponential moving average found in many trading platforms and signal-processing texts.
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.ewm(span=3, adjust=False).mean())The output is:
0 1.00000
1 1.50000
2 2.25000
3 3.12500
4 4.06250
5 5.03125
dtype: float64For the first row both settings give 1.0. After many rows the two versions converge, because the weights of very old rows sum to almost nothing. The difference matters mainly in the first few dozen rows of a series. If you need to match another system's numbers, check which formula it uses before choosing adjust.
Edge behavior and missing values
Because min_periods defaults to 0 in ewm, you get a value from the very first row. That first value rests on a single observation, so it is a weak estimate. If you want NaN until enough data has accumulated, set min_periods explicitly:
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.ewm(span=3, min_periods=3).mean().isna().tolist())
# [True, True, False, False, False, False]Two other points about edges and gaps:
ewm().std()andewm().var()returnNaNfor the first row even with the defaultmin_periods, because a variance cannot be estimated from one value.- When the data contains
NaN, theignore_naoption decides how gaps affect the weights. Withignore_na=False(the default), a missing row still counts as a step, so older values decay across the gap. Withignore_na=True, the missing row is skipped and weights are based only on positions of non-missing values.
Irregular time series
By default ewm counts steps by row position. If your rows are unevenly spaced in time, two rows one second apart and two rows one month apart decay the same amount. To decay by elapsed time, pass a datetime-like times argument and give halflife as a time span:
import pandas as pd
idx = pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-04", "2024-01-07"])
df = pd.DataFrame({"sales": [10.0, 20.0, 30.0, 40.0]}, index=idx)
df["ewm_2d"] = df["sales"].ewm(halflife="2D", times=df.index).mean()
print(df)Here a reading loses half of its weight for every two days that pass, whatever the number of rows in between. This option works with mean(), but you cannot combine it with span, com or alpha. It also does not use adjust=False the way row-based decay does, so check the pandas documentation for your version if you rely on exact values.
Relation to rolling and expanding windows
The three kinds of window differ only in how they assign weights:
| Window | Weight of a past row | Memory |
|---|---|---|
| `rolling(n)` | 1 inside the window, 0 outside | Exactly `n` rows |
| `expanding()` | 1 for every earlier row | Everything |
| `ewm(...)` | Shrinks geometrically with age | Everything, with fading influence |
As alpha approaches 0, the weights flatten and ewm(...).mean() with adjust=True approaches the expanding mean. As alpha approaches 1, only the current row matters.
Common errors
- Treating
spanas a window size.ewm(span=3)does not use only three rows. It uses all earlier rows, with a decay tuned so that the center of mass is comparable to a short window. - Expecting leading
NaNvalues.ewmgives a value from row 0 unless you setmin_periods. - Mixing up
adjust. The defaultadjust=Truedoes not match the recursive formula in many textbooks. Setadjust=Falsewhen you need that formula. - Passing several decay parameters. Give exactly one of
com,span,halflifeandalpha. - Ignoring uneven spacing. For irregular timestamps, use
timeswith a time-basedhalflife. - Forgetting look-ahead leakage. An EW mean at row
tincludes rowt. If you use it as a feature to predict rowt, shift it by one row, as you did with rolling features:s.ewm(span=3).mean().shift(1).
Limits
ewm supports a smaller set of aggregations than rolling. There is no ewm().apply(), median(), min() or max(), because those statistics have no natural weighted form that pandas can update row by row. If you need an arbitrary statistic, use a rolling window with apply. EW calculations run in compiled code, so they are fast on large inputs.
Exercise
Given s = pd.Series([10.0, 20.0, 40.0]), what does s.ewm(alpha=0.5, adjust=False).mean() return for the three rows?
Show answer
The first value is 10.0. The second is 0.5 10.0 + 0.5 20.0 = 15.0. The third is 0.5 15.0 + 0.5 40.0 = 27.5. The result is 10.0, 15.0, 27.5.
Exercise
You want an exponentially weighted mean of daily readings in which a reading loses half of its influence after 7 days, and you want no value until at least 5 rows have been seen. The data has a DatetimeIndex with gaps. Write the call, and explain why you would also shift the result if you use it to predict the next reading.
Show answer
df["reading"].ewm(halflife="7D", times=df.index, min_periods=5).mean(). The times argument makes the decay depend on elapsed days instead of row count, which suits gaps. The value at row t includes the reading at row t, so shifting it by one row (.shift(1)) keeps the current value from leaking into the feature used to predict it.