Sub topic 8
Splitting by time, not at random
This chapter assumes you can build an as-of join, as covered in the earlier chapters. You should also know pandas filtering and basic supervised-learning evaluation. The training set you built is point-in-time correct, so each feature value was known at its row's prediction time. This chapter covers the next step: choosing which of those rows train the model and which evaluate it. A random split can undo the care you took in the join.
Why a random split leaks
A random split shuffles all rows and assigns, for example, 80% to training and 20% to validation. This is the default in many tools and works well for data with no time order, such as photos of cats and dogs. Production data does not behave that way. A deployed model is trained on the past and scored on the future.
A random split breaks that setup in three ways:
- Future rows train the model. A validation row from March has neighbors from April and May in the training set. The model can learn patterns that only exist later, such as a promotion, a pricing change, or a new product.
- Same-entity rows land on both sides. A customer who appears monthly will have rows in training and validation. The model can memorize customer-level quirks such as spend level, region, or plan. Validation then rewards recall of a known customer, not generalization to a new situation.
- Drift is hidden. The relationship between features and label changes over time. A random split samples every period into both sets, so the validation set looks like the training set. The score ends up measuring how well the model fits one blended period. In production the model faces a period it has never seen.
The result is the same inflated offline metric described in the first chapter, even though every feature is point-in-time correct. Temporal leakage can come from the join and from the split.
| Property | Random split | Time-based split |
|---|---|---|
| Validation data is later than training data | No | Yes |
| Matches production use | No | Yes |
| Exposes drift | No | Yes |
| Sets are the same size by construction | Yes | Depends on the cutoff |
| Entities may appear in both sets | Yes | Yes, but only with earlier history |
The last row matters. In a time-based split the same customer may still appear in both sets, and that is fine. In production you also score customers you have seen before. The training rows for that customer just have to be earlier than the validation rows.
The basic cutoff split
Pick a cutoff timestamp. Rows with a prediction time before the cutoff go to training, and rows at or after it go to validation. Split on prediction_ts, the column that defines when the model would have made the prediction. Do not split on feature_ts or on the time the label became known.
cutoff = pd.Timestamp("2026-01-01")
train_df = train[train["prediction_ts"] < cutoff]
valid_df = train[train["prediction_ts"] >= cutoff]Use one comparison for each side, < and >=, so no row is in both sets and no row is dropped. If your timestamps carry time zones, make the cutoff timezone-aware in the same zone. Comparing a naive timestamp with an aware column raises an error in pandas. Converting both to UTC first is the simplest fix.
The label horizon problem
The basic split has a subtle leak. Suppose the label is "customer churned within 30 days after the prediction time". A training row with prediction time December 20 gets its label from events up to January 19. That is after the cutoff. The training label contains information from the validation period, and a model trained on it has seen what happened in the validation window.
The fix is to drop, or leave out of training, any row whose label window crosses the cutoff. This gap is sometimes called an embargo or purge. A training row is only safe when prediction_ts + label_horizon <= cutoff.
The gap throws away some training rows, which costs data. It is still the correct trade, because those rows carry labels that were not yet known at the cutoff. In production you could not have trained on them either.
A reusable split function
Put the rules in one function so every experiment uses them. This example is self-contained and runs as shown.
import pandas as pd
def time_split(df, ts_col, cutoff, label_horizon):
"""Split rows by time, leaving a gap of one label horizon."""
cutoff = pd.Timestamp(cutoff)
train = df[df[ts_col] <= cutoff - label_horizon]
valid = df[df[ts_col] >= cutoff]
return train, valid
dates = pd.date_range("2025-01-01", periods=365, freq="D")
df = pd.DataFrame(
{
"customer_id": [i % 50 for i in range(365)],
"prediction_ts": dates,
"churned": [int(i % 7 == 0) for i in range(365)],
}
)
horizon = pd.Timedelta("30D")
train_df, valid_df = time_split(df, "prediction_ts", "2025-10-01", horizon)
# Every training label window must close before validation begins.
assert train_df["prediction_ts"].max() + horizon <= valid_df["prediction_ts"].min()
print(len(train_df), len(valid_df))
print(train_df["prediction_ts"].max(), valid_df["prediction_ts"].min())The assertion is a leakage test for the split itself. It fails if someone changes the cutoff logic and lets a label window overlap validation. The later chapter on automated leakage checks builds on this idea.
Choosing the cutoff
There is no universal cutoff. These criteria decide it:
- Make validation resemble the deployment period. If you will retrain monthly and score the next month, validate on a month-sized window, not a year.
- Cover seasonality. If behavior has a yearly cycle, a validation window of one December tells you about December only. Consider several windows.
- Keep enough positive labels. A rare event, such as 1% churn, needs a validation window with enough positives for a stable metric. Count them before you trust a score.
- Leave enough history for training. Rolling features such as a 90-day average are empty for early rows. Start training after the longest window has filled.
Three sets: train, validation, test
Tuning hyperparameters against the validation set slowly fits the model to that window. Keep a third, later block of time as a test set that you score once, after all choices are made. The order is always train, then validation, then test, with a label-horizon gap between each pair.
horizon = pd.Timedelta("30D")
valid_start = pd.Timestamp("2025-09-01")
test_start = pd.Timestamp("2025-11-01")
train_df = df[df["prediction_ts"] <= valid_start - horizon]
valid_df = df[
(df["prediction_ts"] >= valid_start)
& (df["prediction_ts"] <= test_start - horizon)
]
test_df = df[df["prediction_ts"] >= test_start]
print(len(train_df), len(valid_df), len(test_df))Walk-forward evaluation
One cutoff gives one score, and that score could be a lucky or unlucky period. Walk-forward evaluation, also called rolling-origin or expanding-window evaluation, repeats the split at several cutoffs. For each cutoff, train on everything up to the gap and validate on the next window. The spread of scores tells you how stable the model is across periods.
def expanding_folds(df, ts_col, cutoffs, valid_span, label_horizon):
"""Yield (cutoff, train, valid) for each cutoff, moving forward in time."""
for cutoff in cutoffs:
cutoff = pd.Timestamp(cutoff)
train = df[df[ts_col] <= cutoff - label_horizon]
valid = df[
(df[ts_col] >= cutoff) & (df[ts_col] < cutoff + valid_span)
]
yield cutoff, train, valid
cutoffs = ["2025-07-01", "2025-08-01", "2025-09-01", "2025-10-01"]
for cutoff, tr, va in expanding_folds(
df, "prediction_ts", cutoffs, pd.Timedelta("30D"), pd.Timedelta("30D")
):
print(cutoff.date(), len(tr), len(va), round(va["churned"].mean(), 3))Each fold's training set contains all earlier rows, so it grows. A sliding window, which drops the oldest rows, is an alternative when old behavior is no longer relevant. Compare both if you suspect drift. Never use scikit-learn's KFold with shuffling on this data. If you use scikit-learn, TimeSeriesSplit respects order and has a gap parameter, but it assumes one row per time step. With many entities per timestamp, splitting on explicit timestamps as above is clearer.
Edge cases
- Rows with identical timestamps. If many labels share one prediction time, such as a nightly batch, the cutoff keeps them together. That is correct. Splitting by row number would divide a batch across both sets.
- Entities that appear only in validation. New customers have no history, so their features are mostly empty or default. This is realistic, and it shows how the model handles cold starts. Report the score for new and known entities separately if it matters to you.
- Entities that appear only in training. Customers who churned long ago are in training only. That is normal.
- Label maturity. Rows near the end of your data may not have a complete label window. A row from the last 10 days has not had 30 days to churn, so its label is unreliable. Exclude rows whose prediction time is later than
max_label_time - horizon. - Relabeling. If labels get corrected after the fact, the bitemporal filtering from the late-data chapter applies to labels too. Use the label values known when you ran the split.
- Group-level constraints. Some data has grouped samples that must stay together, such as several rows from one order. Assign the group's time from its earliest prediction time, so the whole group lands on one side.
Checklist
- Split on
prediction_ts, with<on one side and>=on the other. - Leave a gap of at least one label horizon between training and the next set.
- Check that validation data has enough positive labels.
- Keep a final test period untouched until the end.
- Use walk-forward folds to measure stability across periods.
- Assert the ordering and gap in code so the rule cannot silently regress.
Exercise
Your label is "customer cancels within 14 days of the prediction time". Your data runs from 2025-01-01 to 2025-12-31, and you set the validation cutoff at 2025-10-01. What is the latest prediction time a training row may have, and why does the last validation row also need attention?
Show answer
A training row needs prediction_ts + 14 days <= cutoff, so its prediction time must be 2025-09-17 or earlier. A later training row has a label window that reaches into the validation period. The last validation rows, those after 2025-12-17, have not had a full 14 days to cancel before the data ends, so their labels are incomplete. Exclude them or treat their scores with caution.