Skip to content
LeetQuant
QR06 Machine Learning and Model Validation

QR06 · Machine Learning and Model Validation · Lesson 4 of 5

Cross-Validation for Time Series

Why shuffled k-fold leaks with dependent data, walk-forward and expanding-window validation, purging and embargoes for overlapping labels, and nested cross-validation for honest hyperparameter selection.

17 min

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 kk-fold leaks with financial data, design walk-forward and purged schemes, and separate model selection from model evaluation.

Why shuffled k-fold leaks

Standard kk-fold assumes rows are independent and identically distributed. Financial data break this in two ways.

1. Overlapping labels. A typical label is the forward hh-day return, sampled daily. The labels at tt and t+kt + k share h−kh - k of their hh daily returns. With independent daily returns of equal variance,

Corr⁡(yt, yt+k)=h−kh,0≤k≤h.\operatorname{Corr}\big(y_t,\, y_{t+k}\big) = \frac{h - k}{h}, \qquad 0 \le k \le h .

For h=20h = 20, adjacent labels have correlation 0.950.95 and labels five days apart 0.750.75. Shuffled kk-fold puts day tt in the test set and days t±1t \pm 1 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 tt" 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 NN daily observations of an hh-day label, the number of non-overlapping labels is about N/hN/h. Ten years of daily data (N≈2,520N \approx 2{,}520) 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 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 R2R^2 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 [0,t)[0, t), test on [t,t+m)[t, t + m), then t←t+mt \leftarrow t + m. Uses all history; suitable when the relationship is stable.
  • Rolling (sliding) window: train on [t−w,t)[t - w, t). Adapts to regime change at the cost of noisier fits; the window length ww 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 kk-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 tt's label uses data in (t,t+h](t, t + h] and the test fold is [a,b][a, b], purge training tt with t+h>at + h > a and t<b+ht < b + h.
  • 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 t=0,…,989t = 0, \dots, 989, each labelled with the 10-day forward return (data in (t,t+10](t, t + 10]). The test fold is t=400,…,599t = 400, \dots, 599. With a 10-sample embargo after the test fold, which training samples remain?

Show solution

The test labels use data in (400,609](400, 609].

Before the fold. Training sample tt overlaps if t+10>400t + 10 > 400, i.e. t≥391t \ge 391. Purge t=391,…,399t = 391, \dots, 399 (9 samples). Training on the left is t=0,…,390t = 0, \dots, 390: 391 samples.

After the fold. Sample tt overlaps if t<609t < 609. Purge t=600,…,608t = 600, \dots, 608 (9 samples). The embargo drops a further t=609,…,618t = 609, \dots, 618. Training on the right is t=619,…,989t = 619, \dots, 989: 371 samples.

Total training set 391+371=762391 + 371 = 762 samples, versus 990−200=790990 - 200 = 790 in unpurged kk-fold: 28 samples lost (9+9+109 + 9 + 10) to make the test fold honest. The cost is small when hh 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 9+9+10=289 + 9 + 10 = 28 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 0.50.5. The best one has expected Sharpe 0.5×E[max⁡ of 20 standard normals]≈0.5×1.87≈0.930.5 \times \mathbb{E}[\max \text{ of } 20 \text{ standard normals}] \approx 0.5 \times 1.87 \approx 0.93, 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 kk-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 kk-fold assumes independent rows; overlapping labels (correlation (h−k)/h(h-k)/h) and persistent features break it badly.
  • Walk-forward with expanding or rolling windows matches deployment; TimeSeriesSplit with gap implements 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 N/hN/h than NN.

Practice problems

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).