Sub topic 9
Avoiding Look-Ahead Leakage with shift
This chapter assumes you can build rolling windows with rolling(window), know what min_periods does, and have used groupby and a DatetimeIndex. It covers one problem: a rolling feature that accidentally includes information the model would not have had at prediction time. The fix is usually one call to shift.
What look-ahead leakage is
Look-ahead leakage happens when a feature for row t is computed from data that was not yet known at time t. A model trained on such a feature looks excellent in testing. In production the future values are missing, so the same feature is weaker and the results fall apart.
Rolling windows leak easily because of their default alignment. A window of size 3 at row t covers rows t-2, t-1 and t. It always includes the current row. That is fine for describing history, such as "the 3-day average ending today". It is a problem when the current value is also what you want to predict, or when it would not be known yet at prediction time.
The default window includes the current row
Compare a plain rolling mean with the same mean shifted down one row.
import pandas as pd
df = pd.DataFrame({"sales": [10, 20, 30, 40, 50, 60]})
df["leaky"] = df["sales"].rolling(3).mean()
df["safe"] = df["sales"].rolling(3).mean().shift(1)
print(df)
# sales leaky safe
# 0 10 NaN NaN
# 1 20 NaN NaN
# 2 30 20.0 NaN
# 3 40 30.0 20.0
# 4 50 40.0 30.0
# 5 60 50.0 40.0At row 3, leaky is 30.0, the mean of 20, 30 and 40. It contains the sales value 40 for the same row. If row 3's sales is the target, the feature already holds a third of the answer.
At row 3, safe is 20.0, the mean of 10, 20 and 30. It uses only rows 0 to 2. shift(1) moves every value down one row, so each row receives the result computed at the row above. The first valid safe value appears one row later than the first valid leaky value, because the shift adds one more NaN at the top.
Two equivalent ways to shift
You can shift the result of the rolling calculation, or shift the input before rolling.
import pandas as pd
s = pd.Series([10, 20, 30, 40, 50, 60])
after = s.rolling(3).mean().shift(1)
before = s.shift(1).rolling(3).mean()
print(after.equals(before)) # TrueBoth give the same values here. Shifting the result reads naturally as "compute the statistic, then delay it". Shifting the input is useful when you want the window itself to be built from lagged data, for example when you also need s.shift(1) as a separate lag feature.
Another option: closed="left" on time windows
On a time-based window you can leave the current row out of the window itself, using closed="left". The interval then runs from t - 3 days up to, but not including, t.
import pandas as pd
idx = pd.to_datetime(["2024-01-01", "2024-01-02", "2024-01-04", "2024-01-07"])
df = pd.DataFrame({"sales": [10, 20, 30, 40]}, index=idx)
df["prior_3d"] = df["sales"].rolling("3D", closed="left").sum()
print(df)
# sales prior_3d
# 2024-01-01 10 NaN
# 2024-01-02 20 10.0
# 2024-01-04 30 30.0
# 2024-01-07 40 30.0On 2024-01-04 the window is [2024-01-01, 2024-01-04). It contains the sales from January 1 and 2, which add up to 30. On 2024-01-07 the window is [2024-01-04, 2024-01-07), which holds only the January 4 value.
This is often better than shift(1) on irregular data, because the window is defined by time and not by row count. Compare it with a row shift on the same data: shift(1) at 2024-01-07 would hand over the result computed at 2024-01-04, which is a different window.
| Technique | What it excludes | Works on | Watch out for |
|---|---|---|---|
| `.rolling(n).stat().shift(1)` | The current row | Regular, sorted rows | Shifts by rows, not by time |
| `.shift(1).rolling(n).stat()` | The current row | Regular, sorted rows | Same values as above for full windows |
| `.rolling("3D", closed="left")` | The current timestamp | A sorted `DatetimeIndex` | Empty windows give `NaN` |
Two ways to frame the same problem
There are two conventions, and mixing them is a common source of leakage.
- Convention A: row
tpredictssales[t]. Every feature must be shifted so that it uses only rows beforet. - Convention B: row
tpredictssales[t+1]. Features may usesales[t], so they are unshifted, and the target issales.shift(-1).
Both build the same pairs of feature and target. Only the row labels differ.
import pandas as pd
s = pd.Series([10, 20, 30, 40, 50, 60], name="sales")
a = pd.DataFrame({"feature": s.rolling(3).mean().shift(1), "target": s})
b = pd.DataFrame({"feature": s.rolling(3).mean(), "target": s.shift(-1)})
print(a.dropna().reset_index(drop=True).equals(
b.dropna().reset_index(drop=True)
)) # TrueMixing the conventions is the mistake. If you use shift(-1) for the target (convention B) and also shift the features (convention A), your features are one step staler than they need to be. If you use unshifted features with an unshifted target (convention A without the shift), you leak.
Leakage through groups
A bare shift ignores groups. After groupby("store") and a rolling mean, you must shift inside each group too. Otherwise the first row of store B receives the last rolling value of store A.
import pandas as pd
df = pd.DataFrame({
"store": ["A", "A", "A", "B", "B", "B"],
"sales": [1, 2, 3, 10, 20, 30],
})
df["feature"] = df.groupby("store")["sales"].transform(
lambda s: s.rolling(2).mean().shift(1)
)
print(df)
# store sales feature
# 0 A 1 NaN
# 1 A 2 NaN
# 2 A 3 1.5
# 3 B 10 NaN
# 4 B 20 NaN
# 5 B 30 15.0The transform call returns a result aligned to the original rows, so no reset_index step is needed. Each group is rolled and shifted on its own, so store B starts with NaN, not with a value from store A.
An alternative that avoids the lambda is to shift within the group first and then roll. You can compute df.groupby("store")["sales"].shift(1) and then roll on that result, but the rolling step again needs a group-aware call. The transform version keeps both steps together.
Expanding features need the shift too
An expanding mean at row t averages rows 0 through t, so it also includes the current row. The same fix applies.
import pandas as pd
s = pd.Series([10, 20, 30, 40, 50, 60])
print(s.expanding().mean().shift(1))
# 0 NaN
# 1 10.0
# 2 15.0
# 3 20.0
# 4 25.0
# 5 30.0A related trap is normalizing a column with its mean and standard deviation over the whole dataset. That uses future rows to scale past rows. An expanding mean and standard deviation, shifted by one row, gives a normalization that only uses earlier data.
Test for leakage directly
Reading code for leakage is error-prone, so test it. A feature at rows up to t must not change if you alter the value at row t. The helper below changes one value and compares the feature before and after.
import pandas as pd
def uses_value_at(feature_fn, s, t):
"""Return True if any feature up to row t depends on s[t]."""
changed = s.copy()
changed.iloc[t] = s.iloc[t] + 1000
before = feature_fn(s).iloc[: t + 1]
after = feature_fn(changed).iloc[: t + 1]
return not before.equals(after)
s = pd.Series([float(i) for i in range(1, 11)])
print(uses_value_at(lambda x: x.rolling(3).mean(), s, 7)) # True
print(uses_value_at(lambda x: x.rolling(3).mean().shift(1), s, 7)) # False
print(uses_value_at(lambda x: x.rolling(3).mean().shift(-1), s, 7)) # TrueThe unshifted feature fails because row 7's window includes the value at row 7. The shift(-1) version fails because row 6 now receives the window that ends at row 7. The shift(1) version passes. You can run a check like this in a unit test for any feature function.
Gotchas
- Sort first.
shiftandrollingwork by row position. If the rows are not in time order, a shift moves values to the wrong times. Callsort_index()on aDatetimeIndex, or sort by the time column, before building features. - Missing rows. If a daily series has gaps,
shift(1)still moves by one row, which may be several days. Useclosed="left"on a time window, or reindex to a complete date range first. - Publication lag. A value stamped with a date is not always known on that date. Monthly figures are often published weeks later. Shift by the real delay, such as
shift(3)for three rows, not by one row. center=True. A centered window uses rows aftert. Do not use it for features that feed a prediction. Use it only for smoothing in analysis.- Shifting leaves
NaNrows. The firstshiftrows of the feature are missing. Drop them withdropna()before training, or let your model handle missing values explicitly. - Do not shift the target. Only features are delayed. If you shift both the feature and the target by the same amount, the leak is still there.
Exercises
Exercise
A DataFrame has a daily sales column. You want a feature for predicting sales on each row that is the mean of the previous 7 days, not including the current day. Write one expression that creates it, assuming one row per day with no gaps.
Show answer
df["feat"] = df["sales"].rolling(7).mean().shift(1). The rolling mean at row t covers rows t-6 to t, and shift(1) moves it down so row t receives the mean of rows t-7 to t-1. The first 7 rows are NaN.
Exercise
Why does df.groupby("store")["sales"].rolling(3).mean().shift(1) fail to prevent leakage between stores, and what is a safer form?
Show answer
The groupby-rolling result is one long Series ordered by group. A plain shift(1) on it moves the last value of one store onto the first row of the next store. The safer form is df.groupby("store")["sales"].transform(lambda s: s.rolling(3).mean().shift(1)), which rolls and shifts inside each group.
Exercise
A time-indexed series has irregular gaps. Why can rolling("7D", closed="left") be safer than rolling("7D").sum().shift(1)?
Show answer
With closed="left" the window for each timestamp is [t - 7 days, t), so the current observation is excluded and the window is still defined by time. The shift(1) version moves the result by one row, so a row after a gap receives the value computed at an earlier timestamp with a different window.