Sub topic 2
Rolling-Window Features for Gradient Boosting Forecasts
Assume you know pandas Series and scikit-learn's fit and predict methods. A rolling-window feature summarizes recent observations. It gives a regression model information about the local level and variability of a series.
Rolling-window statistics as features
For a target \(y_t\), a seven-period rolling mean estimates the recent level:
\[ \text{mean}t = \frac{y{t-1} + \cdots + y_{t-7}}{7} \]
The window must end at \(t-1\), not \(t\). Shifting before rolling prevents the feature from using the value it is supposed to predict.
| Feature | Captures | Common use |
|---|---|---|
| Rolling mean | Recent level | Smooth noisy data |
| Rolling standard deviation | Recent volatility | Detect changing variability |
| Lagged value | Recent exact value | Model autocorrelation |
import pandas as pd
from sklearn.ensemble import HistGradientBoostingRegressor
series = pd.Series(
[10, 12, 11, 14, 15, 16, 15, 17, 18, 19, 20, 21],
index=pd.date_range("2026-01-01", periods=12, freq="D")
)
df = pd.DataFrame({"y": series})
past = series.shift(1)
df["lag_1"] = series.shift(1)
df["roll_mean_3"] = past.rolling(3).mean()
df["roll_std_3"] = past.rolling(3).std()
df["dayofweek"] = series.index.dayofweek
df = df.dropna()
features = ["lag_1", "roll_mean_3", "roll_std_3", "dayofweek"]
cut = 8
model = HistGradientBoostingRegressor(max_iter=100, random_state=0)
model.fit(df.iloc[:cut][features], df.iloc[:cut]["y"])
prediction = model.predict(df.iloc[cut:][features])
print(prediction)Calendar features
Calendar features represent recurring timing effects. Use day of week for weekly patterns, month for annual patterns, and holiday indicators when demand changes on holidays. Encode cyclical features, such as day of year, with sine and cosine when December and January should be close.
Avoiding target leakage
Target leakage occurs when a feature contains information unavailable when the forecast is made. Unshifted rolling statistics are a common example. Random train/test splits also let training rows occur after validation rows, creating look-ahead bias.
Fitting gradient boosting
Gradient boosting builds many small decision trees sequentially. Each tree corrects errors from earlier trees. It handles nonlinear interactions among lags, windows, and calendar values without requiring feature scaling.
Trend limits and workarounds
A tree predicts values within patterns represented in training data. It does not naturally extrapolate a rising trend beyond the largest observed levels. Add a time index, difference the target, model growth separately, or retrain frequently after level shifts. Always compare the result with a naive baseline.
Exercise
Why should a rolling mean be computed from series.shift(1) when predicting the current value?
Show answer
The shift removes the current target from the window, preventing target leakage.