Sub topic 10
Avoiding lookahead leakage
Lookahead leakage happens when a model sees information at training time that it would not have at prediction time. In time series work, shift() is the main tool for preventing it, and a wrong sign or a missing shift() is the main way to cause it. This chapter covers where leakage comes from, how to build features that cannot leak, and how to test that claim.
It assumes you can write basic Python, create and index pandas Series and DataFrames, and work with a DatetimeIndex and pd.date_range. It also assumes you know what shift(), groupby().shift(), and asfreq() do from earlier chapters.
What leakage means for a forecast
A forecast is made at a specific moment, the forecast origin. Every input to the model must be known at that moment. A feature leaks if its value in row t depends on anything that happens after the origin.
This chapter uses one convention throughout:
- The target in row
tis the value you want to predict for datet. - You make the prediction
hdays earlier, so you only know values up to datet - h. - A feature in row
tmay use values from rowst - hand earlier, and nothing newer.
With h = 1, you predict today's sales using yesterday and earlier. With h = 7, you predict a week ahead, so yesterday's sales are not available yet.
Leakage is dangerous because it does not cause an error. The model scores well on validation data and then fails in production, where the leaked information does not exist.
Common sources of leakage
| Source | Example | Fix |
|---|---|---|
| Negative shift used as a feature | `s.shift(-1)` as an input | Use only `shift(k)` with `k >= h` for inputs |
| Same-row value in a statistic | `s.rolling(3).mean()` includes the current row | Shift first: `s.shift(h).rolling(3).mean()` |
| Lag shorter than the horizon | `shift(1)` for a 7-day forecast | Use `shift(h)` or larger |
| Backward or interpolated fill | `asfreq("D").bfill()` | Fill forward only, or leave `NaN` |
| Statistics from the full dataset | Scaling with the mean of all rows | Compute statistics on training rows only |
| Random train/test split | Shuffled cross-validation | Split by time |
| Unsorted data | `shift()` works by position | Sort by time (and group) first |
The sections below work through these in turn.
Leakage from the sign of the shift
A negative shift gives a lead, which is a future value. Leads are legitimate for building a target, but a lead used as an input leaks by construction. The leak is easy to introduce by accident, for example when you copy a target-building line and forget to remove it.
import pandas as pd
sales = pd.Series(
[10, 12, 15, 11, 14, 18],
index=pd.date_range("2024-01-01", periods=6, freq="D"),
name="sales",
)
df = pd.DataFrame({"sales": sales})
df["lag1"] = sales.shift(1) # known yesterday: safe
df["lead1"] = sales.shift(-1) # known tomorrow: leaks if used as an input
print(df)In row 2024-01-02, lag1 is 10 (the previous day) and lead1 is 15 (the next day). A model trained with lead1 as an input would learn from information that does not exist on 2024-01-02.
A simple rule: in feature code, every shift should have a positive periods argument that is at least the forecast horizon. Search your feature code for shift(- and confirm that each match builds a target, not an input.
Leakage from the horizon
Using shift(1) is only safe if you really do predict one step ahead. If your forecast is made a week in advance, yesterday's value is not known yet.
Write the feature builder so the horizon is an explicit parameter and the lag cannot be smaller than it:
import numpy as np
import pandas as pd
def build_features(s: pd.Series, horizon: int) -> pd.DataFrame:
"""Lag features usable when forecasting `horizon` days ahead."""
feats = pd.DataFrame(index=s.index)
for extra in (0, 1, 6):
lag = horizon + extra
feats[f"lag_{lag}"] = s.shift(lag)
return feats
rng = np.random.default_rng(0)
s = pd.Series(
rng.integers(50, 150, size=30),
index=pd.date_range("2024-01-01", periods=30, freq="D"),
name="sales",
)
feats = build_features(s, horizon=7)
print(feats.columns.tolist())For horizon=7, the columns are lag_7, lag_8, and lag_13. The smallest lag equals the horizon, so no feature can use a value newer than the forecast origin.
Test for leakage instead of trusting the code
Reading the code is not enough, because leaks often come from library calls you did not write. A reliable check works like this. Change every value after a cutoff date, rebuild the features, and confirm that all feature rows up to the cutoff are identical. If a feature at or before the cutoff depends on later data, it will change.
import pandas as pd
def assert_no_lookahead(make_features, s, cutoff):
"""Raise AssertionError if features up to `cutoff` depend on later values."""
original = make_features(s)
altered = s.copy()
altered.loc[altered.index > cutoff] = -999
changed = make_features(altered)
pd.testing.assert_frame_equal(original.loc[:cutoff], changed.loc[:cutoff])
def safe_features(s):
return pd.DataFrame({
"lag1": s.shift(1),
"roll2": s.shift(1).rolling(2).mean(),
})
def leaky_features(s):
return pd.DataFrame({
"lag1": s.shift(1),
"roll2": s.rolling(2, center=True).mean(),
})
s = pd.Series(
[10, 12, 15, 11, 14, 18, 13, 16],
index=pd.date_range("2024-01-01", periods=8, freq="D"),
)
cutoff = pd.Timestamp("2024-01-05")
assert_no_lookahead(safe_features, s, cutoff)
print("safe_features: passed")
try:
assert_no_lookahead(leaky_features, s, cutoff)
except AssertionError:
print("leaky_features: leakage detected")The centered window in leaky_features uses the next row for the row at the cutoff, so the test fails for that function and passes for the safe one. Run a test like this against your real feature pipeline, not only against toy functions.
This test only catches dependence on later rows. It does not catch a lag that is too short for your horizon, so keep the horizon explicit in the code as shown above.
Leakage from filling gaps
The earlier chapter on gaps used asfreq() to restore missing timestamps. The restored rows contain NaN, and the way you fill them can leak.
import pandas as pd
s = pd.Series(
[10, 12, 15, 11],
index=pd.date_range("2024-01-01", periods=4, freq="D"),
name="sales",
)
gappy = s.drop(pd.Timestamp("2024-01-03"))
regular = gappy.asfreq("D")
print(pd.DataFrame({
"raw": regular,
"ffill": regular.ffill(), # uses the past: safe
"bfill": regular.bfill(), # uses the future: leaks
}))On 2024-01-03, ffill gives 12 (yesterday's value). bfill gives 11, which is the value from 2024-01-04. The same applies to interpolate(), which blends the values on both sides of a gap. Prefer leaving NaN in place for models that accept it, or fill forward only. If you add an indicator column that marks which rows were filled, the model can learn to discount them.
Leakage across groups and unsorted data
shift() moves values by row position, not by date. Two situations break that assumption.
If the rows are not sorted by time, a shift pulls values from arbitrary dates, and some of them can be in the future. Sort before you shift, and assert it:
assert s.index.is_monotonic_increasing, "sort by time before shifting"With a panel of several entities, an ungrouped shift() lets the first row of one store take the last value of the previous store. That is a different kind of error, but it also puts information in the wrong place. Sort by ["store", "date"], then use df.groupby("store")["sales"].shift(h), as in the chapter on grouped lags.
Leakage from splitting and scaling
Even with correct features, the way you split the data can leak.
Random or shuffled splits put later rows in the training set and earlier rows in the test set. The model then "predicts" the past from the future, and scores much higher than it will in production. Split by time instead: train on rows up to a cutoff date, test on rows after it.
Preprocessing statistics leak in the same way. If you compute a mean and standard deviation over the full dataset, the training rows carry information about the test period. Compute the statistics on the training rows and apply them to both parts:
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
s = pd.Series(
rng.integers(50, 150, size=30),
index=pd.date_range("2024-01-01", periods=30, freq="D"),
name="sales",
)
horizon = 7
feats = pd.DataFrame({f"lag_{k}": s.shift(k) for k in (horizon, horizon + 1, horizon + 6)})
data = feats.assign(target=s).dropna()
cutoff = pd.Timestamp("2024-01-20")
train = data.loc[data.index <= cutoff]
test = data.loc[data.index > cutoff]
print(train.shape, test.shape)
feature_cols = [c for c in data.columns if c != "target"]
mu = train[feature_cols].mean()
sd = train[feature_cols].std()
train_z = (train[feature_cols] - mu) / sd
test_z = (test[feature_cols] - mu) / sd
print(test_z.head(3))This prints (7, 4) (10, 4). The first 13 rows are dropped because lag_13 is NaN there. The mean and standard deviation come only from the 7 training rows, and the test rows are scaled with those same numbers.
Targets that look ahead across the split
If the target is a lead, such as s.shift(-7), then the last training rows have targets that fall inside the test period. The model has then seen test-period outcomes during training. Leave a gap of at least the horizon between the last training row and the first test row, or drop training rows whose target date is after the cutoff. With the convention used in this chapter (target is the value at row t, features lagged), this problem does not arise, which is one reason to prefer it.
A checklist for each feature
The flowchart below summarizes the questions to ask about every feature before it enters a model.
Rolling statistics
A rolling window includes the current row by default. For a feature at row t, that means the target's own period leaks into the feature whenever the window is not shifted. The fix is to shift before rolling, as in s.shift(h).rolling(window).mean(). The next chapter covers this in detail, including how the window size and the shift interact.
Gotchas
shift()withfreq=moves labels, not values. If you use it to build a feature, check which direction the dates move. A positivefreqshift moves values to later dates, which is the safe direction for lags.pct_change()anddiff()look back by default, so they are safe. Passing a negativeperiodsmakes them look ahead.- Joining another table on date can leak if that table's values are published late. A value dated
tthat only became known att + 2must be shifted by two days before the join. dropna()after feature building is safe, but filling the leadingNaNvalues with the column mean uses data from the whole series. Fill with training statistics, or usefill_value.
Exercise
You forecast daily sales 3 days ahead. A teammate builds the feature df["roll3"] = df["sales"].rolling(3).mean() and df["lag1"] = df["sales"].shift(1). Which of these leak, and how would you rewrite them?
Show answer
Both leak. roll3 includes the current day's sales, which is the target. lag1 is yesterday's value, which is not known 3 days in advance. Rewrite them as df["sales"].shift(3).rolling(3).mean() and df["sales"].shift(3). Every lag must be at least the horizon (3), and the window should be built after shifting.
Exercise
A series has a gap on 2024-03-05. You call s.asfreq("D").interpolate() and use shift(1) to build a lag feature. The model scores well. Why is the lag feature on 2024-03-06 still a problem, and what is a safer option?
Show answer
Interpolation fills 2024-03-05 using the values on both sides of the gap, so it uses data from 2024-03-06. The lag feature for 2024-03-06 then contains a value that depends on the 2024-03-06 data itself. A safer option is s.asfreq("D").ffill(), which uses only earlier values, or leaving the gap as NaN and letting the model or a later step handle it.
Exercise
You standardize all columns using df.mean() and df.std() over the whole dataset, then split by date into train and test. The split is correct. Is there still leakage? How do you fix it?
Show answer
Yes. The mean and standard deviation include test-period values, so the training data carries information about the test period. Compute the mean and standard deviation from the training rows only, then apply those same numbers to both the training and test rows.