Systematic Trading Field Guide
2.4 · Not fooling yourself

Purged and embargoed cross-validation

~13 min read
Mechanism

Ordinary K-fold cross-validation assumes observations are independent. Financial labels overlap in time and features remember the recent past, so random folds put pieces of the same event in both train and test — the model is graded partly on information it already saw. Purge the overlapping observations, embargo the aftermath, and when you need a distribution of outcomes rather than one number, use combinatorial purged CV.

The idea

A story you may recognise from your data science life, transplanted to markets. You build a classifier: features from recent price action and volume, label = "does this stock beat the market over the next five days?". You do everything the ML playbook says: shuffle, five-fold cross-validate, tune hyperparameters on the folds. The cross-validated AUC comes back 0.58 — genuinely good for daily equity prediction. You paper-trade it. It's a coin flip. What happened?

Nothing exotic — you imported an assumption along with the tooling. K-fold CV is a machine for estimating out-of-sample error when observations are exchangeable: cat photos don't leak information about other cat photos. Financial time series violate exchangeability in two specific, mechanical ways, and each one turns random folds into a leak.

Leak one: overlapping labels. Your label for Monday is the return from Monday to next Monday. Your label for Tuesday is the return from Tuesday to the Tuesday after. Those two windows share four days — they are substantially the same return, wearing different dates. Shuffle the data and Monday lands in the training set while Tuesday lands in the test set: the model trains on most of the answer to a test question. With a five-day horizon, every test observation has up to eight neighbours (four on each side) that carry pieces of its label. The model doesn't need to find real structure to score well; memorising the training folds' labelled moves reconstructs much of the test folds' labels. Your 0.58 AUC was the echo of this overlap, not prediction.

Leak two: features remember. Even with non-overlapping labels, your features are rolling computations — a 20-day volatility, a 10-day return, an RSI. Observations a few days apart have nearly identical feature vectors and correlated outcomes. A test observation sitting a day after a train observation is close to a duplicate of it. The model is being tested on near-copies of its training data, which is the definition of an optimistic error estimate.

Notice something important before we fix it: the walk-forward backtests you already run don't have this problem (train strictly on the past, trade strictly on the future — the arrow of time does the hygiene). The reason to bother with cross-validation at all is efficiency and robustness: walk-forward gives you one path through history, with early periods never tested and late periods never trained on, and its verdict can hinge on luck of the particular path (a point the PBO authors develop (Bailey, Borwein, López de Prado & Zhu 2016)). CV promises to use all the data for both training and testing. The López de Prado programme (López de Prado 2018) is about keeping that promise without the leaks, and it has three moving parts.

Purging. Keep the folds contiguous in time (no shuffling — blocks, not confetti). Then, for each test block, delete from the training set every observation whose label window overlaps the test block's label windows. If the test block covers June and labels span five days, the last training observation before the block must have its label fully resolved before June begins — so the final days of May get purged. The overlap is computable exactly (you know each label's start and end), so purging is a mechanical mask, not a judgment call.

Embargo. Purging handles label overlap; it doesn't handle features that remember. An observation just after the test block trains a model on features contaminated by test-period events (its 20-day volatility includes the test month), and serial correlation lets that leak flow backward from the test set into training. The fix is blunt: after each test block, additionally drop a short buffer of training observations — an embargo — sized to the memory of your features. A common choice is a small percentage of the sample or, more principledly, the longest feature lookback beyond the label horizon.

Combinatorial purged CV (CPCV). The final piece answers a different complaint: any single backtest — walk-forward or CV — is one draw from the space of paths your strategy could have taken through history. CPCV manufactures many paths: split history into NN contiguous groups, and run every combination of kk groups as the test set (purging and embargoing around each), training on the rest. Each group gets tested many times, under many different training histories, and the test predictions can be stitched into multiple complete backtest paths. Instead of "the Sharpe was 0.9" you get "across 45 reconstructed paths, the Sharpe ranged from 0.2 to 1.3 with a median of 0.7" — which is a far more honest shape for the truth to take, and feeds directly into the overfitting diagnostics of lesson 2.5.

The maths

Formalise the purge so you can implement it as a mask. Observation ii has a label computed over the interval [ti, ti+h][t_i,\, t_i + h], where tit_i is its decision time and hh the label horizon. Let the test block occupy [τ0, τ1][\tau_0,\, \tau_1]. Then training observation ii must be purged if its label interval intersects the test block's information span:

[ti,  ti+h]  ∩  [τ0,  τ1+h]  ≠  ∅plus embargo: ti∈(τ1+h,  τ1+h+e][t_i,\; t_i + h] \;\cap\; [\tau_0,\; \tau_1 + h] \;\neq\; \varnothing \qquad \text{plus embargo: } t_i \in (\tau_1 + h,\; \tau_1 + h + e]
An observation is purged from training if its label window touches the test window; the embargo extends the exclusion for e further observations after the test block to absorb feature memory.

For CPCV with NN groups and kk test groups per split, the number of splits is (Nk)\binom{N}{k}, and since each split contributes kk tested groups, each group is tested (N−1k−1)\binom{N-1}{k-1} times; the tested groups reassemble into

φ(N,k)  =  (Nk) kN\varphi(N, k) \;=\; \binom{N}{k}\,\frac{k}{N}

complete backtest paths. The standard small example: N=6N = 6, k=2k = 2 gives (62)=15\binom{6}{2} = 15 splits and φ=5\varphi = 5 full paths — five different versions of history's verdict on your model, for roughly the compute of fifteen training runs.

Worked example

Worked example — purging and embargo on a 12-month timeline

Twelve months of data, three contiguous folds, label horizon one month, embargo one month. Testing fold B (May–Aug):

MonthJFMAMJJASOND
Roletraintraintrainpurgetesttesttesttestpurgeembargotraintrain

Walk the two exclusions. April is purged because an April observation's label is the April→May return — it reaches into the test block; a model trained on it has seen May's prices. September is purged for the mirror reason (its label is fully inside knowledge that only exists because the test block happened — equivalently, the test block's own labels extend into September, so September training rows overlap them). October is embargoed: its rolling features (20-day vol, monthly momentum) are still computed over test-period data, and serial correlation would let the model absorb test-set conditions from them. What survives as training data: Jan–Mar and Nov–Dec. Yes — purging costs you data. That is the honest price of the estimate; the inflated AUC was never yours.

The mask, in the shape your framework would use:

def purge_mask(t, h, test_start, test_end, embargo):
    """t: decision times (sorted array); h: label horizon; returns
    True where a row may be used for TRAINING."""
    label_end = t + h
    overlaps = (t <= test_end + h) & (label_end >= test_start)
    embargoed = (t > test_end + h) & (t <= test_end + h + embargo)
    return ~(overlaps | embargoed)

And the CPCV bookkeeping for N=6N=6, k=2k=2: fifteen splits, each fold tested five times, five stitched backtest paths. If your strategy's five path-Sharpes come back as, say, 1.2, you have learned two things a single walk-forward could not tell you: the central estimate (~0.8) and — more valuable — that one reordering of history cuts it in half. Fragility across paths is exactly the signature of an edge concentrated in one regime, which lesson 2.7 picks up.

How you'd use it

First, decide whether you need it at all. If your strategy is a fixed rule with no fitted parameters — a trend filter, a carry sort — plain walk-forward simulation is honest and simpler; CV machinery adds nothing but places to make mistakes. Purged CV earns its complexity exactly when you are fitting something: ML models, parameter grids, anything where hyperparameter choice needs an error estimate that isn't contaminated.

Set the knobs from your problem, not from defaults. Label horizon hh comes from your label definition. Embargo ee should cover your longest feature memory beyond hh — if your slowest feature is a 60-day volatility, embargo roughly that. Fold count: fewer, longer folds respect regime structure better than many small ones; with ten years of daily data, six to ten contiguous groups is a sensible shape.

Use CPCV for the decision that matters. Model selection on the distribution of path Sharpes — median minus a dispersion penalty, or simply "reject anything whose worst path is unacceptable" — is far more robust than selecting on a single number. This plugs straight into the PBO calculation of the next lesson, which needs exactly the combinatorial structure CPCV produces.

Keep one uncontaminated referee. Whatever CV you run for tuning, hold out a final contiguous span of history (the most recent year or two) that no fitting decision ever touched, and let it deliver the last verdict, once. CV estimates guide the search; the untouched holdout is the only number you quote.

What goes wrong

Leakage around the CV, not through it. Purging seals the folds; it does nothing about global preprocessing. Fit a scaler, PCA, feature selection, or class-weight scheme on the full dataset before splitting, and every fold leaks through the preprocessing regardless of purging — the exact full-sample sin of lesson 2.1 in ML clothing. Everything that learns from data must live inside the fold loop, refit on each training set. If you use sklearn, that means pipelines, religiously.

Tuning until the CV breaks. Run enough hyperparameter configurations against the same folds and the champion overfits the folds themselves — CV error is an estimate with noise, and argmax-ing over noise is lesson 2.3's selection problem all over again. Count configurations, deflate accordingly, and let the untouched holdout catch what slips through.

Embargo theatre. An embargo of a day or two chosen "because the example used that" does nothing if your features carry a quarter's memory. Size it from the actual autocorrelation length of your features — check empirically how far apart two observations must be before feature correlation decays — or accept that your CV number retains an optimistic tilt.

Non-stationarity wearing a leak's costume. Even perfectly purged CV assumes the world doesn't change between train and test; markets change regime, which produces bad live performance that no CV hygiene can predict. Don't spend all your paranoia on leakage — a clean 0.55 AUC estimated across 2012–2022 tells you nothing about whether the pattern survives 2026. That failure mode has its own lesson (2.7).

Purging away your sample. With long-horizon labels (quarterly, yearly), purging plus embargo can consume most of the data, leaving folds too small to fit on. That's not the method failing — it's the method telling you the truth that long-horizon labels on a short history contain very few independent observations (the effective-sample-size lesson of 2.6, arriving from another direction). If the honest procedure leaves too little data to learn from, the conclusion is that there wasn't enough evidence to learn from, not that the procedure should be relaxed.

Further reading