Sub topic 6
Rolling-window statistics as features
Lag features give the model individual past values. Rolling-window features summarize a whole stretch of the past, such as the average of the last 7 days or how volatile the last 14 days were. This chapter shows how to build them correctly, how to choose windows, and which errors are most common. It assumes you can use pandas Series and DataFrame objects with a DatetimeIndex, and that you have read the chapter on lag features.
Why windows help
A single lag such as lag_1 is noisy. If yesterday was an odd day, the model sees only that odd value. A 7-day mean smooths the noise and gives a more stable estimate of the current level. A 7-day standard deviation tells the model how much to trust that level.
Windows also compress history. Seven lags cost seven columns. One mean and one standard deviation cost two columns, and they often carry most of the useful signal. Trees split on a handful of features at a time, so fewer and more informative columns usually work better.
The one rule: the window ends at t-1
When you predict y at time t, every feature must be computable from values before t. In pandas, s.rolling(7).mean() at row t includes s[t], which is the value you are trying to predict. Shift first, then roll:
The shift is the line that most often goes missing. A model built without it looks excellent in validation and fails in production, because it was given part of the answer.
Building the features
The following code is self-contained. It creates a synthetic daily series, builds window features on the shifted series, and runs a leakage check.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
idx = pd.date_range("2024-01-01", periods=120, freq="D")
weekly = 10 * np.sin(2 * np.pi * idx.dayofweek.to_numpy() / 7)
y = pd.Series(50 + weekly + rng.normal(0, 3, len(idx)), index=idx, name="y")
def window_features(s: pd.Series, windows=(7, 14, 28)) -> pd.DataFrame:
past = s.shift(1) # the window for row t ends at t-1
out = pd.DataFrame(index=s.index)
for w in windows:
r = past.rolling(w)
out[f"mean_{w}"] = r.mean()
out[f"std_{w}"] = r.std()
out[f"min_{w}"] = r.min()
out[f"max_{w}"] = r.max()
out["ewm_7"] = past.ewm(span=7, adjust=False).mean()
out["ratio_7_28"] = out["mean_7"] / out["mean_28"]
return out
# Leakage check: changing y at position 60 must not alter any feature
# at rows 0..60, only rows after it.
y_changed = y.copy()
y_changed.iloc[60] += 1000
f_orig = window_features(y)
f_changed = window_features(y_changed)
pd.testing.assert_frame_equal(f_orig.iloc[:61], f_changed.iloc[:61])
print("rows 0-60 unchanged")
print("row 61 mean_7:", f_orig["mean_7"].iloc[61], "->", f_changed["mean_7"].iloc[61])The check passes because row 60's features depend only on rows up to 59. Row 61 changes, which is correct: at time 61, the value at 60 is already in the past. Run this kind of test on any feature function you write. It catches leakage that code review misses.
Choosing statistics
| Statistic | What it captures | Typical use |
|---|---|---|
| Mean | Current level | Almost always included |
| Standard deviation | Volatility, noise | Helps the model separate stable from erratic periods |
| Min and max | Recent range | Spikes, stock-outs, capacity limits |
| Median | Level robust to outliers | Spiky data such as promotions |
| Exponentially weighted mean | Level with more weight on recent days | Series where the level drifts |
| Ratio of short to long mean | Direction of recent change | A crude momentum signal |
Exponentially weighted means (ewm) have no fixed window. Each value is a weighted average of all past values, with weights that decay geometrically. The span argument sets how fast. Applying ewm to past keeps it leak-free in the same way.
Choosing window sizes
Pick windows that match the structure of the data.
- Include a window equal to the seasonal period. For daily data with a weekly cycle, a 7-day mean averages over exactly one cycle, so the weekday pattern cancels out. A 5-day mean would mix weekdays unevenly and leave a sawtooth in the feature.
- Add a longer window, such as 28 days, for the slow-moving level, and a shorter one for recent behavior.
- Keep the set small. Three windows with four statistics each is already 12 columns that are strongly correlated. Trees tolerate that, but it dilutes importance scores and slows tuning.
- Validate the choice with walk-forward scores, not with intuition alone.
Edge cases
Warm-up rows
A 28-day window needs 28 past values, and the shift removes one more. The first 28 rows are NaN, and dropna() removes them. You can set min_periods (for example past.rolling(28, min_periods=7)) to keep more rows, but then early rows use shorter windows than later ones. The feature then means different things in different rows. Prefer dropping rows unless data is scarce.
Missing timestamps
rolling(7) counts rows, not days. If your data skips dates, seven rows may span ten days. Call s.asfreq("D") first so that gaps become explicit NaN values, then decide how to fill them. Alternatively use a time-based window, s.rolling("7D", closed="left"). The closed="left" argument excludes the current row, which does the job of the shift. This requires a sorted DatetimeIndex.
Missing values inside a window
By default rolling(7) returns NaN if any of the seven values is NaN. Gradient boosting libraries such as HistGradientBoostingRegressor accept NaN inputs, but a gap then wipes out seven rows of features. Decide deliberately between filling the gap, using min_periods, or accepting the missing features.
Consistency at forecast time
Features at prediction time must be computed exactly as in training. The recursive_forecast function from this tutorial uses values.iloc[-7:], which are the seven values before the step being forecast. That equals past.rolling(7) in training. If you change the window definition, the forecast code needs the same change. Mismatched definitions give no error and quietly worse forecasts.
Level shifts
Rolling means follow a trending series with a delay, and tree models cannot predict values outside the range they saw in training. Window features made of raw levels inherit this problem. Features like ratio_7_28, or a window mean subtracted from the lag (lag_1 - mean_7), are scale-free and extrapolate better.
Common errors
- Rolling without the shift, so the target is inside its own window.
- Computing features on the full dataset and then splitting. Pure past-only windows are safe, but any statistic that uses the whole series (global mean, standardization,
center=Truewindows) is not. - Using
center=True. This puts the window around rowt, including future values. - Computing features on a series with gaps without calling
asfreq. - Using different window definitions in training and forecasting code.
Exercise
A colleague builds df["roll_mean_7"] = s.rolling(7).mean() and df["y"] = s. The validation MAE is far below the seasonal-naive baseline, but production forecasts are much worse. What is wrong, how do you fix it, and how can you test the fix?
Show answer
The 7-day window at row t includes s[t], the target, so the feature contains one seventh of the answer. In production that value is unknown, so accuracy collapses. Fix it with s.shift(1).rolling(7).mean(), or s.rolling("7D", closed="left").mean() on a sorted DatetimeIndex. To test, change the value of y at one position t and confirm that features at rows up to and including t are unchanged, as in the leakage check above.