Module contents
Stage 7 of 9Advanced 100 min

Walk-forward and purged cross-validation

Implement the engine's validation protocol with walk-forward retraining and nested parameter selection, purged cross-validation with embargo for overlapping labels, and its combinatorial version for multiple backtest paths. Measure the performance inflation caused by standard cross-validation in a controlled experiment.

After this lesson you can

  • Implement walk-forward validation with expanding and rolling windows and nested hyperparameter selection.
  • Implement purging and embargo and explain the leakage each addresses.
  • Generate backtest paths using combinatorial purged cross-validation.
  • Measure overestimation from standard k-fold in a synthetic experiment.

Before you start

Training on the past

A financial label can depend on several future periods. If a training row and a test row share part of that interval, the model can learn information from the same episode it is later asked to predict. Splitting by rows does not guarantee independence or that training data existed before the decision.

Walk-forward validation fixes a cutoff, trains on earlier observations, and predicts the next block. It then moves the cutoff forward and repeats. An expanding window retains all available history; a rolling window discards the oldest history and can adapt sooner to regime changes at the cost of estimating from less data. Retraining frequency, dates, and computational cost are part of the protocol.

Hyperparameters are chosen within the outer training set. In the lab, the last segment before the outer cutoff serves as internal validation; three ridge penalties are compared and the model is refitted on purged outer training data. The outer block is used only for evaluation. Labels used for internal fitting must end before internal validation begins, and outer training labels before the outer block. Changing the model after viewing outer results turns that evaluation into another selection stage.

For example, a sequence can train through the end of January, select parameters using an earlier segment, and produce predictions for February. In March, it repeats with new training and selection. Each month’s decision uses only labels completed before the evaluated period. If a label began in January but its outcome becomes known in February, it cannot be used to decide at the start of February. The cutoff must apply to the date the outcome is known, not just its start date.

A single internal validation segment is inexpensive and easy to audit, but the result can depend on that segment. Several temporal internal splits reduce dependence on one cutoff at the cost of computation and additional decisions. In either case, fix the candidate set before observing the outer block. The example’s MSE evaluates a numerical prediction; an investment strategy would also need to convert predictions into positions and deduct costs.

Intervals, purging, and embargo

Purging with embargo uses the start sis_i and end eie_i of each label. With closed intervals, training observation ii is removed if there is a test observation jj such that

si≤ejyei≥sj.s_i\le e_j\quad\text{y}\quad e_i\ge s_j.

Touching at an endpoint counts as overlap. Training starts falling in (ej,ej+h](e_j,e_j+h] are then embargoed, where hh uses the same time units. The code applies this rule to each test interval. Purging protects against declared label overlap; embargo adds a subsequent margin. Neither alone guarantees that a revised feature, global normalization, or a late publication date is causal.

InteractivePurging and embargo

Each event i covers the closed interval [i, i+3]. The test contains three consecutive indices and their combined intervals run from 5 to 10. A training label that touches that interval is purged.

■ test · ■ purged · ■ embargo · ■ training

Lines are ordered top to bottom by index 0 through 13. The embargo removes nearby later starts; by itself it does not guarantee that all features are causal.

5
2
Test5, 6, 7
Purged2, 3, 4, 8, 9, 10
Embargo11, 12
Training0, 1, 13
Indices and colors show exactly which rows remain in each category.

For example, test [9,12] and training [6,9] touch at 9, so the latter is purged. A label [15,18] does not overlap, but with an embargo of three units its start, 15, lies in (12,15] and is also removed. If test intervals are separated, each must be checked; a single envelope can purge more rows than necessary. Dates, market closes, and embargo units must agree.

This lesson’s PurgedKFold class uses consecutive blocks and may train on blocks both before and after the test, following purging and embargo. It is useful for studying stability under its assumptions, but does not reproduce a strictly prospective historical decision. Walk-forward trains only on the past. Temporal validation does not imply a universal rule that every k-fold is invalid: Bergmeir, Hyndman and Koo study specific conditions where k-fold can work for autoregressive models.

An embargo needs a rationale tied to features and the calendar. For example, if a later feature summarizes a window containing observations from the test period, removing some immediately subsequent starts can prevent that window from contaminating training. The necessary gap depends on the actual window: choosing an arbitrary two-day embargo for a twenty-day feature does not establish separation. It may also be necessary to model feature availability intervals, not only label intervals.

In a pipeline, each transformer learns its parameters within each split’s training set. If the mean, standard deviation, feature selection, or imputations are calculated across all rows before splitting, the model receives information about the test distribution even without seeing its labels directly. The splitter cannot correct a transformation already computed outside it. Record which step is fitted, on which rows, and when it is applied.

Combinations and paths

Combinatorial purged cross-validation divides the sequence into NN groups and selects kk test groups in each combination. There are (Nk)\binom Nk splits. Each group appears in (N−1k−1)\binom{N-1}{k-1} test splits; if predictions are assembled so each group appears once per path, that is the number of paths.

With six groups and two test groups there are 15 splits and five paths. The lab uses five perfect matchings: each path combines three pairs of groups and covers all six exactly once. Each pair belongs to one split. This construction is specific to this case and verified by its tests; it is not a general path generator for all N,kN,k. The paths share training data and models and are not five independent experiments.

For each split, training labels overlapping any label in the test groups are purged. Predictions are reassembled in chronological order within each path. If the estimator produces portfolio weights, initial position, costs, and transitions between blocks must also be defined; concatenating block metrics does not necessarily produce an executable backtest.

The path count follows from counting appearances of a fixed group: to form a test split including it, choose the other k−1k-1 from N−1N-1 groups. Each complete path needs one such appearance per group. In the six-two case, the 15 pairs can be explicitly partitioned into five matchings of three, as the tests verify. Averages and quantiles across those five paths describe sensitivity to the splits, but their spread is not a confidence interval based on five independent observations.

Local laboratory

Download p01validation.py, p01validation_lab.py, and test_p01validation.py. Install NumPy, scikit-learn, and pytest. The splitters accept arrays ordered by start and implement the split interface; times are numeric, with embargo in the same units. The tests check absence of overlap, path count and coverage, and walk-forward temporal separation.

The experiment is deliberately constructed to show leakage: 80 independent episodes have a random fingerprint and a random label per episode, repeated ten times with tiny noise. Random k-fold leaves replicas of the same episode in training and test, and a nearest neighbor memorizes its label. Purged blocks exclude overlapping episodes. The fingerprint contains no predictive relationship across new episodes. The two splits differ: one mixes rows and the other separates temporal blocks.

[ ]Purging, paths, and walk-forwardLocal GPU
import os,sys
from pathlib import Path
import pytest
lib=Path(os.environ.get('P01_LIB_DIR','.')).resolve()
if not (lib/'p01validation.py').exists(): raise FileNotFoundError('Descarga los módulos y pruebas en P01_LIB_DIR')
sys.path.insert(0,str(lib))
from p01validation_lab import experiment
os.environ['PYTEST_DISABLE_PLUGIN_AUTOLOAD']='1'
status=pytest.main([str(lib/'test_p01validation.py'),'-q','-p','no:cacheprovider'])
assert status==0
experiment()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

With this seed, random k-fold obtains AUC 1.000 and purged validation obtains 0.558. Resampling the 80 episodes with predictions already calculated gives an approximate interval [0.448, 0.657], including 0.5; it does not include uncertainty from retraining the models. The five CPCV paths give AUCs of 0.569, 0.584, 0.540, 0.543, and 0.641. These figures share data and should not be treated as independent replicates. Purging does not force AUC to exactly 0.5 in every sample.

The second experiment creates a weak synthetic linear signal and uses walk-forward with a 100-row window, first evaluation at 120, and blocks of 20. Across 120 predictions, MSE is 1.0674; the selected penalties are printed at each cutoff. This signal is planted to verify the pipeline, and is not market evidence.

Exercises

NumericCombinatorial paths
With 6 groups and 2 test groups per combination, how many complete paths are there if each group appears once in each path?
CodeRemove overlap and embargo
Implement purge(train,tests,starts,ends,embargo) with integer indices and closed intervals. Remove each training observation that overlaps a test or whose start lies in (fin_test, fin_test+embargo]. Return a list preserving order.
def purge(train,tests,starts,ends,embargo):
  raise NotImplementedError()
Shift+Enter to run
QuizChanging regimes
If you suspect the relationship between signal and return changes with the regime, what possible advantage does a rolling window have over an expanding window?
QuizScaling before splitting
What leakage can arise from normalizing each feature using the mean and standard deviation of the full sample before separating training and test?

What to remember

Key idea
Purging removes known overlaps; walk-forward and nested selection also address when each decision could have been made.