Sub topic 8
Avoiding target leakage and look-ahead bias
Leakage happens when a model sees information at training or evaluation time that it would not have at forecast time. The result is a validation score that looks excellent and a production model that does not. This chapter assumes you can build lag and rolling features with pandas and run a chronological split with scikit-learn. It also assumes you know what a one-step forecast target is.
What leakage is
Two terms describe related problems.
- Target leakage means a feature contains the value you are trying to predict, or something computed from it.
- Look-ahead bias means a feature or a data-preparation step uses observations that lie after the forecast origin. The forecast origin is the moment when you issue the forecast.
Both break the same rule. For a row that predicts time t, every input must be computable using only data available just before t.
Tree models make this failure easy to miss. A gradient boosting model will find a leaked column quickly and rely on it heavily. A leaked pipeline often shows an MAE that is suspiciously far below the seasonal-naive baseline.
Where leakage enters
| Source | What goes wrong | Fix |
|---|---|---|
| Rolling window without a shift | The window for row `t` includes `y[t]` | Shift by one step, then roll |
| Centered window (`center=True`) | The window includes future values | Use a trailing window |
| Backward fill or interpolation | Missing values are filled from later observations | Forward fill only, or fill after splitting |
| Global statistics | A mean, standard deviation or target encoding is computed on the whole series | Compute on the training portion only |
| Random split | Training rows come from after the test rows | Split chronologically |
| Tuning on the test set | Hyperparameters or early-stopping rounds are chosen using test scores | Tune on validation blocks that precede the test set |
| Late-arriving data | A feature is published after the forecast time, such as yesterday's figure that is only final two days later | Lag the feature by its publication delay |
The most common bug: windows that include the present
A rolling mean over 7 rows ending at row t contains y[t]. If y[t] is the target, the feature contains one seventh of the answer.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
idx = pd.date_range('2024-01-01', periods=200, freq='D')
s = pd.Series(
50 + 10 * np.sin(np.arange(200) * 2 * np.pi / 7) + rng.normal(0, 3, 200),
index=idx,
)
def make_X_leaky(s: pd.Series) -> pd.DataFrame:
return pd.DataFrame({
'lag_1': s.shift(1),
'roll_mean_7': s.rolling(7).mean(), # includes y[t]
})
def make_X_safe(s: pd.Series) -> pd.DataFrame:
return pd.DataFrame({
'lag_1': s.shift(1),
'roll_mean_7': s.shift(1).rolling(7).mean(), # ends at y[t-1]
})The shift(1) goes before rolling. Rolling first and shifting afterwards gives the same numbers, but shifting first makes the intent clear when you read the code.
A test that catches look-ahead
Reading code finds some bugs and misses others. A perturbation test checks the behavior directly. If features for row t really depend only on the past, then changing every value from t onward must leave that row's features unchanged.
def has_lookahead(make_X, s: pd.Series, t: int) -> bool:
base = make_X(s)
s2 = s.copy()
s2.iloc[t:] = s2.iloc[t:] + 1000.0 # corrupt the present and the future
altered = make_X(s2)
return not np.allclose(base.iloc[t], altered.iloc[t], equal_nan=True)
print('leaky:', has_lookahead(make_X_leaky, s, t=100)) # True
print('safe: ', has_lookahead(make_X_safe, s, t=100)) # FalseThe leaky version prints True because roll_mean_7 at row 100 changes when y[100] changes. The safe version prints False. Add a check like this to your test suite for every feature function. It also catches centered windows, bfill, and any other transformation that reaches forward.
Preprocessing that learns from data
Any step that learns a number from the data can leak. Examples are scaling, imputing with a mean, target encoding a category, and clipping outliers at percentiles. Compute those numbers on the training rows and apply them unchanged to later rows.
cut = int(len(s) * 0.8)
train_s, test_s = s.iloc[:cut], s.iloc[cut:]
train_mean = train_s.mean() # learned from training only
train_s = train_s.fillna(train_mean)
test_s = test_s.fillna(train_mean) # same constant, no test statisticsDuring walk-forward validation, repeat this inside every fold. A preprocessing step fitted once on the full dataset leaks into every fold, even if the model itself is refit correctly.
Missing values deserve extra care. interpolate() and bfill() pull in later observations. Forward fill uses only the past, so it is the safe default for features.
Splits, gaps and what a gap actually does
A chronological split puts all validation rows after all training rows. A random split does not. A random split lets the model learn from tomorrow to predict yesterday, which is impossible in production.
With a one-step target, features for the first validation row are built from earlier values. Those values sit in the training period, and that is legitimate, because they would be known at forecast time. So a gap is not needed to stop feature leakage in this case.
A gap matters when training targets overlap the validation period. If you predict y[t+h] from features at t, the last training rows have targets inside the validation window. In that setting, a gap of at least h rows keeps training labels out of the validation period. A gap equal to the longest lag or window is also a common, conservative choice, and it costs only a few rows. The TimeSeriesSplit(gap=7) call used in the validation chapter does this.
Availability in production
A feature can be computed without look-ahead in your notebook and still be unavailable when the forecast runs. Ask this for each column: if the forecast runs at 06:00 on the day being predicted, what is the latest value of this feature that exists?
- Yesterday's sales total may not be final until noon today. Lag it by two days instead of one.
- Weather observations for the target day are unknown. Weather forecasts are known, but they carry their own error and must be the forecasts issued before the origin, not the later actuals.
- A promotion calendar and public holidays are known in advance. They are safe because the future value really is available at forecast time.
The rule is not "never use future-dated values". It is "only use what you would actually have".
Putting it together
- Define every feature as a function of values strictly before the forecast origin.
- Shift before you roll, and use trailing windows only.
- Learn any statistic from the training portion, inside each fold.
- Split chronologically, and add a gap when targets or windows overlap the validation period.
- Check publication delays for every external input.
- Run the perturbation test on the feature function.
Exercise
A colleague builds the feature df['roll_mean_7'] = s.rolling(7, center=True).mean() and reports that gradient boosting beats the seasonal-naive baseline by 60%. Explain why the result is unreliable, rewrite the feature, and describe how you would confirm the fix.
Show answer
With center=True, the window for row t spans three rows before and three rows after t, and it includes y[t] itself. The model sees the target and future values, so the score is inflated and will not hold in production. The fix is df['roll_mean_7'] = s.shift(1).rolling(7).mean(), which uses a trailing window ending at y[t-1]. To confirm it, run the perturbation test: add 1000 to s from row t onward and check that the feature values at row t are identical before and after. Then re-evaluate the model. The improvement over the baseline should shrink to a realistic size.