Sub topic 7
Expanding windows for running statistics
This chapter assumes you know how to build a pandas Series, have read the earlier chapters on rolling() and min_periods, and are comfortable with basic statistics such as mean and standard deviation.
How an expanding window works
A rolling window has a fixed size and slides forward, so old rows drop out as new rows arrive. An expanding window never drops rows. It always starts at the first row and grows by one row at each step. The result at row i is the statistic computed over rows 0 through i.
You create one with expanding(), then call an aggregation on it, just as with rolling().
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.expanding().mean())
# 0 1.0
# 1 1.5
# 2 2.0
# 3 2.5
# 4 3.0
# 5 3.5
print(s.expanding().max())
# 0 1.0
# 1 2.0
# 2 3.0
# 3 4.0
# 4 5.0
# 5 6.0The mean at row 3 is 2.5 because it averages 1, 2, 3 and 4. The maximum is a running maximum: it only changes when a new highest value appears.
Edges and min_periods
Unlike rolling(), expanding() has min_periods=1 by default. A result appears from the first row, with no leading NaN values. That is why the output above starts at 1.0.
Early results rest on very few observations, so they can be noisy. A mean of one value is just that value. Raise min_periods to hold back results until enough data has arrived:
import pandas as pd
s = pd.Series([1, 2, 3, 4, 5, 6])
print(s.expanding(min_periods=3).mean())
# 0 NaN
# 1 NaN
# 2 2.0
# 3 2.5
# 4 3.0
# 5 3.5Only the first two rows change. The window itself still starts at row 0, so later values are identical.
Which statistics to use
Any built-in aggregation from the rolling chapter works here: sum, mean, std, min, max, median and others. Some of them overlap with the cumulative methods cumsum() and cummax(). expanding().sum() gives the same running total as cumsum(). But expanding() also covers statistics that have no cum version, such as running standard deviation and running median. It also accepts min_periods.
Example: drawdown from a running peak
A common use is measuring how far a price has fallen from its highest value so far. The running maximum is the highest price seen up to each day. Dividing the price by it and subtracting 1 gives the drawdown.
import pandas as pd
prices = pd.Series([100, 104, 101, 110, 105, 99])
running_max = prices.expanding().max()
drawdown = prices / running_max - 1
print(drawdown.round(4))
# 0 0.0000
# 1 0.0000
# 2 -0.0288
# 3 0.0000
# 4 -0.0455
# 5 -0.1000On day 5 the price is 99 and the best price so far is 110, so the drawdown is 99/110 − 1 = −10%. A value of 0 means the price is at a new high.
Common errors
- Reading early values as reliable. With the default
min_periods=1, the first few results use only a handful of rows. A running standard deviation also needs at least two values. With one value,std()returnsNaNbecause the sample standard deviation is undefined for a single observation. - Expecting old data to fade. An expanding window weights every row equally, so the statistic reacts more slowly as the series grows. If you want recent rows to count more, use a rolling window or the exponentially weighted windows covered later.
- Look-ahead leakage. The result at row i includes row i itself. If you use it as a feature to predict row i, shift it by one row, as covered in the chapter on leakage.
- Mixing groups. On a DataFrame with several entities, a plain
expanding()runs straight across group boundaries. Apply it aftergroupby, the same way you did withrolling().
Exercise
A Series is pd.Series([4, 8, 6, 10]). What does s.expanding(min_periods=2).max() return, and why is the first value NaN?
Show answer
It returns NaN, 8.0, 8.0, 10.0. The first window holds only one value, which is fewer than min_periods=2, so the result is NaN. From the second row on, each result is the maximum of all rows so far: 8, then 8 (since 6 is lower), then 10.
Exercise
Why might s.expanding().mean() be a poor choice for a series whose level shifts permanently halfway through, and what would you try instead?
Show answer
Every past value keeps the same weight, so the running mean adjusts slowly after the shift and stays pulled toward the old level. A fixed-size rolling window forgets old rows, and an exponentially weighted mean gives recent rows more weight, so either adapts faster.