WRITE · TRACE · UNDERSTAND

Purge a gap before a temporal validation window

Implement temporal_split(times,start,end,gap) returning (train_indices,validation_indices), preserving row order.

Read lesson: Purge a gap before a temporal validation window →

Your experiment

Implement temporal_split(times,start,end,gap) returning (train_indices,validation_indices), preserving row order. Train if t<start-gap; validate if start<=t<=end. Require start<=end and gap>=0.

Python runs in your browser. Your draft stays on this device.

What to look for

A temporal split must be combined with point-in-time feature joins and train-only preprocessing. Time order alone does not prevent using a feature published after the prediction timestamp.

Watch your code work

Ready to experiment

Write a solution or load the worked answer, then choose Trace & check.

Step through arrays, variables and training curves produced by your own Python.

About this algorithm

How Purge a gap before a temporal validation window works

The idea

When a model predicts the future, validation has to imitate that: train on rows before a cutoff and validate on rows after it. A plain cutoff can still leak, because rows close to the boundary often share information with the validation window. A label computed over the next few days, or a feature built from a rolling window, overlaps the period being validated.

temporal_split(times, start, end, gap) removes that overlap by purging. Rows with t < start - gap train, rows with start <= t <= end validate, and rows inside the gap or after end are used for neither. Both lists hold indices, not timestamps, and keep the original row order.

How it works

  1. Raise ValueError when start > end or gap < 0.
  2. Scan the rows with enumerate, so each timestamp keeps its original index.
  3. Put index i in the training list when t < start - gap.
  4. Put index i in the validation list when start <= t <= end.
  5. Leave out every other row: those inside the gap before start and those after end.
  6. Return the pair (train_indices, validation_indices).

What it costs

Time
O(n)
Space
O(n)

Each list is built with one pass over the timestamps, and no sorting is needed because every row is tested on its own.

Where it is used

  • scikit-learn's TimeSeriesSplit has a gap parameter that excludes samples between each training set and its test set.
  • Marcos López de Prado's book Advances in Financial Machine Learning describes purged cross-validation with an embargo for overlapping financial labels.
  • The M5 forecasting competition scored entries on a final 28-day period that came after all the training data.

Watch out for

  • Using t <= start - gap for training, which lets a row exactly on the purge boundary back in.
  • Sorting the rows or returning timestamps: the Lab expects indices into the original list, in their original order.
  • Shuffling time-ordered data into random folds, which trains on rows that come after the ones being validated.