Sub topic 6
Rolling-window statistics as features
This chapter assumes you know pandas rolling, shift, and a DatetimeIndex with a regular frequency. It also assumes you have read the lag features chapter.
Why add window statistics
A single lag tells the model one past value. A rolling-window statistic summarizes many past values in one column. A 7-day mean smooths daily noise and shows the recent level. A 7-day standard deviation shows how volatile the series has been. Gradient boosting can split on these values directly, and they add information that lag columns do not carry on their own.
Building the features
The code below creates three lags, a rolling mean and a rolling standard deviation, and a calendar column.
import pandas as pd
def make_features(s: pd.Series) -> pd.DataFrame:
# s must have a DatetimeIndex with a regular frequency
df = pd.DataFrame({'y': s})
for lag in (1, 7, 14):
df[f'lag_{lag}'] = s.shift(lag)
past = s.shift(1) # exclude the current value from the window
df['roll_mean_7'] = past.rolling(7).mean()
df['roll_std_7'] = past.rolling(7).std()
df['dayofweek'] = s.index.dayofweek
return df.dropna()The important line is past = s.shift(1). It moves the series forward by one step before the window is applied. Without this shift, rolling(7) on s includes the current row's own value.
The window must exclude the current value
s.rolling(7).mean() at time t averages the values from t-6 to t. That includes y at time t, which is the value you are trying to predict. The model would learn to read the answer from a feature. Validation scores would look excellent, but the model would fail in production, where the current value does not exist yet.
With the shift, roll_mean_7 at time t is the mean of t-7 to t-1. This is the same information you will have when you forecast.
The diagram shows which rows feed each feature.
Choosing windows
Pick window sizes that match the data's rhythm. For daily data with weekly seasonality, a 7-day window averages over one full cycle, so the day-of-week pattern cancels out. Common choices are 7, 14 and 28. Short windows react quickly and are noisy. Long windows are stable and slow to respond. Adding a few sizes lets the model use both.
Common errors
- Forgetting the shift. This is the leakage described above.
- Irregular timestamps.
rolling(7)counts rows, not days. If days are missing, the window spans more than a week. Callasfreq('D')first and decide how to fill the gaps. - Dropping rows too early. The first rows have no full window and become
NaN. Rundropna()after all features are built, as the function does. - Mismatch at forecast time. When you forecast ahead, compute the features with the same definition. The recursive forecasting chapter reuses these exact formulas.
Exercise
A colleague writes df['roll_mean_7'] = s.rolling(7).mean() and gets a very low validation error. Explain why the score is misleading and give the corrected line.
Show answer
The window at time t includes y at time t, so the feature contains the target and the model partly copies the answer. The corrected line is df['roll_mean_7'] = s.shift(1).rolling(7).mean(), which uses only values up to t-1.