Sub topic 7
Temporal Leakage and Time-Aware Splits
This chapter assumes you can train and score a scikit-learn estimator, you know what a train/test split and cross-validation are, and you have read the earlier chapters on splits and pipelines. It covers what temporal leakage is, how a random split causes it, and how to build splits that respect time.
What temporal leakage is
Temporal leakage happens when a model is trained on information from a later time than the rows it is evaluated on. In production you only ever predict forward. At prediction time you know the past and the present, and you do not know the future. An evaluation that lets the model see the future answers a question you will never be asked.
Three common forms are:
- Random splitting of ordered data. Training rows come from after some of the test rows.
- Future-aware features. A feature is computed using values from after the prediction time, such as a rolling mean that is centered on the current row.
- Future-aware preprocessing. A scaler, imputer, or encoder is fit on a period that includes the test period.
The first form is the easiest to commit, because train_test_split shuffles by default.
Why a random split inflates scores
Time series rows are rarely independent. Neighboring rows share trends, seasonality, and slowly changing state. If you shuffle, a test row from Tuesday has training neighbors from Monday and Wednesday. The model can interpolate between them, which is much easier than forecasting.
The following script shows the effect. The target is a random walk, and the model predicts the next value from the current time index and a lagged value. A shuffled split looks excellent. A chronological split shows the honest error.
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_absolute_error
from sklearn.model_selection import train_test_split
rng = np.random.default_rng(0)
n = 1000
y = np.cumsum(rng.normal(size=n)) # random walk
t = np.arange(n).reshape(-1, 1) # time index as the only feature
# Random split: test points sit between training points
t_tr, t_te, y_tr, y_te = train_test_split(t, y, test_size=0.25, random_state=0)
model = RandomForestRegressor(n_estimators=100, random_state=0).fit(t_tr, y_tr)
print("shuffled MAE:", mean_absolute_error(y_te, model.predict(t_te)))
# Chronological split: test points lie after every training point
cut = int(n * 0.75)
model = RandomForestRegressor(n_estimators=100, random_state=0).fit(t[:cut], y[:cut])
print("chronological MAE:", mean_absolute_error(y[cut:], model.predict(t[cut:])))The shuffled error is small because each test point has training points a step or two away in time. The chronological error is large because a tree model cannot extrapolate beyond the last value it saw. Only the second number describes how the model will behave after deployment.
The basic fix: split by time
For a single hold-out set, sort by time, then cut. Everything before the cut is training data. Everything after is test data. If you also need a validation set, cut twice, so the order is train, then validation, then test.
Keep these rules in mind:
- Sort by the timestamp, not by the row index of a file that may have been appended out of order.
- Cut at a date, not at a fraction, when the business has a natural boundary such as "all data before the first of the month".
- Make the test period resemble deployment. If the model will predict one week ahead, the test period should be evaluated one week ahead.
Cross-validation with TimeSeriesSplit
KFold with shuffling has the same problem as train_test_split. Even without shuffling, plain KFold uses later folds as training data for earlier test folds. scikit-learn provides TimeSeriesSplit for this. It uses an expanding window: each split trains on all rows up to some point and tests on the block that follows.
import numpy as np
from sklearn.model_selection import TimeSeriesSplit
X = np.arange(12).reshape(-1, 1) # rows ordered by time
for train_idx, test_idx in TimeSeriesSplit(n_splits=3).split(X):
assert train_idx.max() < test_idx.min()
print(train_idx, test_idx)The output shows the training window growing with each split, while the test block always lies strictly after it. The first training window is the smallest, so scores from early splits are noisier than later ones.
TimeSeriesSplit has options that matter in practice:
| Parameter | Effect | When to use it |
|---|---|---|
| `n_splits` | Number of train/test pairs | More splits give more estimates but smaller early training sets |
| `test_size` | Fixed number of rows in each test block | When you want every test block to match the forecast horizon |
| `max_train_size` | Caps the training window, giving a rolling window | When old data is stale and should be forgotten |
| `gap` | Rows skipped between train and test | When features or labels overlap in time (see below) |
The data must already be sorted by time. TimeSeriesSplit splits by position and does not read a timestamp column.
The gap parameter and overlapping labels
Sometimes a label is not known at the moment of the event. A loan default label may need 90 days to observe. A "return within 7 days" label is not final until a week after the purchase. If a training row at day 100 has a label that depends on days 100 to 107, and the test block starts at day 101, then the training label contains information from the test period.
The same problem appears with rolling features. A 7-day rolling mean at day 101 includes days 95 to 101. A training row at day 100 shares six of those days. This is smaller than a direct leak, but it makes neighbors across the boundary correlated.
The fix is to leave a gap at least as long as the label horizon or the feature window. In scikit-learn, set gap:
import numpy as np
from sklearn.model_selection import TimeSeriesSplit
X = np.arange(30).reshape(-1, 1)
cv = TimeSeriesSplit(n_splits=3, test_size=5, gap=7)
for train_idx, test_idx in cv.split(X):
print("train ends at", train_idx.max(), "test starts at", test_idx.min())
assert test_idx.min() - train_idx.max() > 7Each printed pair has seven unused rows between the end of training and the start of testing. Those rows are dropped from both sides. Choose the gap from the longest of the label delay and the feature window, not by trial and error against the score.
Features that look into the future
Splitting correctly is not enough if the features were built with future values. Check each time-based feature for its direction.
- Centered windows.
rolling(window=7, center=True)uses three future rows. Use the default trailing window instead. - Backward fill.
fillna(method="bfill")orbfill()copies a later value into an earlier row. Prefer forward fill, which only carries the past forward. - Interpolation. Linear interpolation of missing values uses the next observation. Interpolate only within the training period, or use forward fill.
- Global statistics. A column holding the per-customer mean over the entire history leaks future behavior into every row. Compute such statistics using only earlier rows.
- Lag direction.
shift(1)gives yesterday's value.shift(-1)gives tomorrow's. A negative shift is nearly always a bug in a feature.
The next example builds a trailing feature in pandas, and a leaky centered one for comparison.
import numpy as np
import pandas as pd
idx = pd.date_range("2024-01-01", periods=10, freq="D")
df = pd.DataFrame({"sales": np.arange(10, 20)}, index=idx)
df["trailing_mean"] = df["sales"].shift(1).rolling(3).mean() # past only
df["centered_mean"] = df["sales"].rolling(3, center=True).mean() # uses tomorrow
print(df)In trailing_mean, the call to shift(1) first removes today's value, so the feature at row t only uses rows up to t − 1. That matters when the target is today's sales: without the shift, the rolling mean would include the target itself.
Preprocessing in time order
The preprocessing rule from earlier chapters applies with one extra constraint. Fit each transform on the training window only, and apply it to later windows. With TimeSeriesSplit, put the transform in a pipeline so it is refit for every split.
import numpy as np
from sklearn.linear_model import Ridge
from sklearn.model_selection import TimeSeriesSplit, cross_val_score
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(1)
X = rng.normal(size=(300, 4)).cumsum(axis=0) # drifting features
y = X[:, 0] * 0.5 + rng.normal(size=300)
pipe = make_pipeline(StandardScaler(), Ridge())
scores = cross_val_score(pipe, X, y, cv=TimeSeriesSplit(n_splits=5), scoring="r2")
print(scores.round(2))Because the features drift, a scaler fit on the whole series would use means and variances from a future the model has not yet seen. Inside the pipeline, each split uses the statistics from its own training window.
Drift and the limits of a single test period
A correct time split can still mislead you. If the test period is short or unusual, such as a holiday week, the score reflects that period and not the typical future. Report the score for several splits and look at how it changes. A model that scores well on early splits and poorly on later ones may be degrading as the data drifts.
Another point is the retraining policy. An expanding window assumes that old data stays useful. A rolling window assumes it does not. Pick the one that matches how you will retrain in production, then evaluate with the same policy.
Mixed structure: time and groups together
Many datasets have both a time order and repeated entities, such as many customers observed over many months. Splitting by time alone can still put the same customer on both sides, which is the group leakage covered in the next chapter. Splitting by group alone can put future customers in training. Decide which question you are answering:
- "How well will the model predict next month for the customers we already know?" Split by time only.
- "How well will it work for new customers next month?" Split by time, then remove from the test set any customer seen in training.
scikit-learn has no single splitter for both. You build the test set by filtering after a time split.
Common mistakes
- Using
train_test_spliton a time series with its defaultshuffle=True. - Using
cross_val_score(model, X, y, cv=5)on ordered data. For a regressor, an integercvmeans unshuffledKFold, which trains on the future for early folds. - Sorting after splitting, which hides a split that was never chronological.
- Tuning hyperparameters with shuffled cross-validation, then testing chronologically. The chosen parameters are already tuned to a leaky metric.
- Ignoring the label delay, so recent training labels are incomplete or leak test-period outcomes.
- Leaving the time index in as a feature and expecting it to generalize. Tree models cannot extrapolate beyond the training range.
Summary
Evaluate on data that comes after the data you trained on. Use TimeSeriesSplit instead of shuffled folds, set gap when labels or features span time, build features from trailing information only, and refit preprocessing inside each split. Compare the chronological score with the random-split score. A large difference shows how much the random split overstated performance.
Exercise
A team predicts whether a customer will cancel within 30 days of each month's end. They use TimeSeriesSplit(n_splits=5) with no gap and rows sorted by month. Their features include "number of support tickets in the next 30 days". Name two separate temporal leakage problems and how to fix each.
Show answer
First, the feature "support tickets in the next 30 days" looks into the future, so it would not be available at prediction time. Remove it, or recompute it using only the 30 days before the prediction date. Second, the label covers the 30 days after each month's end, so a training row's label overlaps the start of the following test block. Set gap to at least the label horizon (about 30 days of rows) so no training label depends on test-period events.
Exercise
You call cross_val_score(Ridge(), X, y, cv=5) on a daily series that is sorted by date. The folds are not shuffled, yet the score is still optimistic. Why, and what do you change?
Show answer
With an integer cv on a regressor, scikit-learn uses KFold without shuffling. Each test fold is a contiguous block, but the folds before and after it are all used for training, so the model trains on the future of every block except the last. Pass cv=TimeSeriesSplit(n_splits=5) so training data always precedes the test block, and add a gap if labels or rolling features span multiple days.