Sub topic 10
Avoiding Lookahead Leakage
This chapter assumes you know basic Python, can build pandas Series and DataFrames with a DatetimeIndex, and have used shift() for lags and leads, as covered in the earlier chapters.
What lookahead leakage is
Lookahead leakage happens when a feature for a given row uses information that would not exist at the moment you make the prediction. A model trained on leaky features scores well in testing and then fails in production, because the future values it relied on are not available there.
Suppose you forecast each day's sales, and you make the forecast at the end of the previous day. Every feature in the row for day t must be computable from data up to day t-1.
Where leakage comes from
Most leakage in lag-based features comes from a few sources.
| Source | Example | Why it leaks |
|---|---|---|
| Negative shift | `s.shift(-1)` | Row `t` holds the value from day `t+1`. |
| Current value | `s.rolling(3).mean()` | The window includes day `t`, which is the target. |
| Ungrouped shift | `df["sales"].shift(1)` on stacked groups | The first row of one group gets the last value of another. |
| Random split | `train_test_split(shuffle=True)` | The model trains on days after the ones it is tested on. |
Negative shifts are fine for building a target, such as sales.shift(-1) as "tomorrow's sales". They are wrong as a feature.
A mechanical test for leakage
Reading code for leaks is error-prone. A more reliable check uses one fact: a safe feature at row t cannot depend on the value at row t or later. So change the last value of the series and rebuild the features. If any feature changes, it used the current or a future value.
import pandas as pd
idx = pd.date_range("2024-01-01", periods=10, freq="D")
sales = pd.Series([10, 12, 15, 11, 14, 16, 13, 18, 17, 20], index=idx, name="sales")
def safe_features(s):
return pd.DataFrame({"lag1": s.shift(1), "lag2": s.shift(2)})
def leaky_features(s):
return pd.DataFrame({
"lag1": s.shift(1),
"lead1": s.shift(-1),
"mean3": s.rolling(3).mean(),
})
def uses_current_or_future(make, s):
changed = s.copy()
changed.iloc[-1] += 1000
base, alt = make(s), make(changed)
return {c: not base[c].equals(alt[c]) for c in base.columns}
print(uses_current_or_future(safe_features, sales))
print(uses_current_or_future(leaky_features, sales))The output is:
{'lag1': False, 'lag2': False}
{'lag1': False, 'lead1': True, 'mean3': True}lead1 changes at the second-to-last row, so it reads from the future. mean3 changes at the last row, so its window includes the day being predicted. Series.equals treats NaN values in matching positions as equal, so the NaN rows at the edges do not cause false alarms.
Fixing a leaky feature
To fix a rolling feature, shift it so the window ends one day earlier. Use s.shift(1).rolling(3).mean() instead of s.rolling(3).mean(). The next chapter covers shifted rolling statistics in detail.
For features that mix groups, use groupby("store")["sales"].shift(1). Sort by group and date first, so the order of rows matches the order of time.
Split by time, not at random
Even with safe features, a shuffled split lets the model see later days during training. Cut at a date instead.
data = pd.concat([sales, safe_features(sales)], axis=1).dropna()
cut = pd.Timestamp("2024-01-08")
train = data.loc[data.index < cut]
test = data.loc[data.index >= cut]
print(len(train), len(test))This prints 5 3. The dropna() removes the first two rows, where lag2 is NaN. Every training row is earlier than every test row.
Check the lag against the forecast horizon
A lag must also match when the data really becomes available. If you forecast a week ahead, shift(1) is wrong. At forecast time you do not yet know the last six days. In that case use shift(7) or larger. Write down the forecast horizon and make the smallest lag at least that long.
Exercise
A colleague writes df["roll3"] = df["sales"].rolling(3).mean() and uses it to predict df["sales"] for the same day. Is this leaky, and how would you fix it?
Show answer
Yes. The window for day t includes day t's own sales, which is the target. Shift first so the window ends on day t-1: df["roll3"] = df["sales"].shift(1).rolling(3).mean(). You can confirm the fix with the perturbation test, since changing the last value no longer changes any feature.