Objective
Cross-validation estimates how a model will perform on data it has not seen. It is valid only if the test folds are as unseen as future data will be. By the end you should be able to explain exactly how standard -fold leaks with financial data, design walk-forward and purged schemes, and separate model selection from model evaluation.
Why shuffled k-fold leaks
Standard -fold assumes rows are independent and identically distributed. Financial data break this in two ways.
1. Overlapping labels. A typical label is the forward -day return, sampled daily. The labels at and share of their daily returns. With independent daily returns of equal variance,
For , adjacent labels have correlation and labels five days apart . Shuffled -fold puts day in the test set and days in the training set: the model has effectively seen 95% of the test label.
2. Persistent features. Features such as moving averages, volatility estimates and valuation ratios change slowly. A flexible model can recognise "this is the period around day " from the features alone and look up the neighbouring training labels. The combination of persistent features and overlapping labels is the leakage engine.
Leakage is worst for the models people most want to use: nearest neighbours, deep trees and forests can memorise neighbourhoods; a linear model with a few features leaks less but still overstates performance.
A useful companion fact: with daily observations of an -day label, the number of non-overlapping labels is about . Ten years of daily data () with 20-day labels gives roughly 126 independent observations, not 2,520.
Worked example
a forest that predicts pure noise
Daily returns are independent standard normals, so the 20-day forward return is unpredictable. The features are a time index and a column of noise. What does random-forest cross-validation report with shuffled folds and with contiguous folds?
Show solutionHide solution
import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import KFold, cross_val_score
rng = np.random.default_rng(0)
n, h = 2000, 20
r = rng.normal(size=n + h) # pure-noise daily returns
y = np.array([r[t + 1 : t + 1 + h].sum() for t in range(n)]) # 20-day forward return
X = np.column_stack([np.arange(n), rng.normal(size=n)]) # a time index and a noise feature
model = RandomForestRegressor(n_estimators=200, min_samples_leaf=5, random_state=0)
shuffled = cross_val_score(model, X, y, cv=KFold(5, shuffle=True, random_state=0), scoring="r2")
ordered = cross_val_score(model, X, y, cv=KFold(5, shuffle=False), scoring="r2")
print(f"shuffled 5-fold R^2: {shuffled.mean():.2f}")
print(f"contiguous 5-fold R^2: {ordered.mean():.2f}")
Output:
shuffled 5-fold R^2: 0.87
contiguous 5-fold R^2: -0.66
Shuffled folds report an of 0.87 on a target with no predictability: the forest finds each test day's neighbours through the time index and reads off their nearly identical labels. Contiguous folds remove most of the leak and show the truth, a model worse than predicting the mean. In real data the time index is replaced by any slow-moving feature, and the inflation is smaller but has the same cause.
Walk-forward validation
The cleanest scheme mimics deployment: train only on the past, test on the next block, roll forward.
- Expanding window: train on , test on , then . Uses all history; suitable when the relationship is stable.
- Rolling (sliding) window: train on . Adapts to regime change at the cost of noisier fits; the window length is itself a hyperparameter.
scikit-learn's TimeSeriesSplit implements the expanding version, and its gap argument drops rows between train and test:
from sklearn.model_selection import TimeSeriesSplit
import numpy as np
X = np.zeros((12, 1))
for train, test in TimeSeriesSplit(n_splits=3, test_size=2, gap=2).split(X):
print(train, test)
[0 1 2 3] [6 7]
[0 1 2 3 4 5] [8 9]
[0 1 2 3 4 5 6 7] [10 11]
Weaknesses: each test block is used once, so the estimate rests on one path of history; early folds train on little data; and the result is dominated by whichever regimes the test blocks happen to cover. Report the per-fold scores, not only the mean.
Purging and embargo
Walk-forward wastes the data before each test block's end. Purged -fold (López de Prado) keeps contiguous test folds anywhere in the sample, including the middle, and repairs the leak at the boundaries:
- Purge: remove every training sample whose label window overlaps any test sample's label window. If sample 's label uses data in and the test fold is , purge training with and .
- Embargo: additionally drop a block of training samples immediately after the test fold, because features computed after the test period (rolling statistics, serially correlated variables) still carry information about it.
Training on data after the test fold is acceptable for estimating a model's error when the relationship is stationary, but it is never acceptable for backtesting a strategy's P&L: use walk-forward for that.
Worked example
counting purged samples
You have 990 labelled samples , each labelled with the 10-day forward return (data in ). The test fold is . With a 10-sample embargo after the test fold, which training samples remain?
Show solutionHide solution
The test labels use data in .
Before the fold. Training sample overlaps if , i.e. . Purge (9 samples). Training on the left is : 391 samples.
After the fold. Sample overlaps if . Purge (9 samples). The embargo drops a further . Training on the right is : 371 samples.
Total training set samples, versus in unpurged -fold: 28 samples lost () to make the test fold honest. The cost is small when is small relative to the fold length, and grows with the horizon.
A direct implementation:
import numpy as np
def purged_kfold(n, k, horizon, embargo):
"""Yield (train, test) index arrays. Sample t's label uses data in (t, t + horizon]."""
t = np.arange(n)
for test in np.array_split(t, k):
a, b = test[0], test[-1]
overlaps = (t + horizon > a) & (t < b + horizon) # label windows intersect the test's
embargoed = (t >= b + horizon) & (t < b + horizon + embargo)
train = t[~overlaps & ~embargoed]
yield train, test
for train, test in purged_kfold(n=990, k=5, horizon=10, embargo=10):
left, right = train[train < test[0]], train[train > test[-1]]
print(f"test {test[0]}-{test[-1]}: train {len(train)}"
f" (left ends {left.max() if len(left) else '-'},"
f" right starts {right.min() if len(right) else '-'})")
test 0-197: train 773 (left ends -, right starts 217)
test 198-395: train 764 (left ends 188, right starts 415)
test 396-593: train 764 (left ends 386, right starts 613)
test 594-791: train 764 (left ends 584, right starts 811)
test 792-989: train 783 (left ends 782, right starts -)
Each interior fold loses exactly training samples, matching the hand count.
Nested cross-validation for hyperparameters
If you choose hyperparameters by cross-validated score and then report that same score, the report is biased upwards: you have taken the maximum of several noisy estimates. Nested CV separates the two jobs:
- Outer loop (evaluation): split time into walk-forward or purged folds.
- Inner loop (selection): inside each outer training set only, run another time-respecting CV to pick hyperparameters; refit on the whole outer training set and score once on the outer test fold.
The outer scores estimate the performance of the whole procedure, "tune then fit", which is what you will actually deploy. The hyperparameters may differ across outer folds; that is expected, and their stability is itself diagnostic.
How large is the bias? Suppose 20 configurations all have zero true skill and each cross-validated Sharpe estimate has standard error . The best one has expected Sharpe , from selection alone. Nested CV would report about zero.
Also keep a final hold-out period that is touched once, after all research decisions are made, because every look at the data during research is an informal inner loop.
Knowledge check
Labels are 10-day forward returns sampled daily, with independent daily returns. What is the correlation between the labels at t and t + 4?
Knowledge check
A colleague tunes 50 hyperparameter settings with walk-forward CV and reports the best setting's CV Sharpe of 1.4 as the expected live Sharpe. What is the main problem?
Knowledge check
What does the embargo in purged k-fold protect against that purging alone does not?
How to answer "how would you validate this model?" out loud
State the label horizon and whether labels overlap; choose walk-forward (for anything P&L-related) or purged -fold with an embargo of at least the label horizon; keep all preprocessing inside the folds; tune in an inner loop; keep a final hold-out; report per-fold results and the number of configurations tried.
Key takeaways
- Shuffled -fold assumes independent rows; overlapping labels (correlation ) and persistent features break it badly.
- Walk-forward with expanding or rolling windows matches deployment;
TimeSeriesSplitwithgapimplements it. - Purging removes training samples whose label windows overlap the test fold; the embargo removes samples just after it.
- Selecting hyperparameters and reporting the same CV score is biased upwards; nested CV or a single-use hold-out fixes it.
- The effective sample size is closer to than .
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).