Backtesting Forecasts Without Leakage
A backtest estimates how large a forecaster's error will be on data it has not seen, and it is only as honest as the split behind it. In the lab, a random K-fold put a nearest-neighbour forecaster's error at 0.545 against a true 0.935 on a long held-out future. Rolling-origin and purged schemes came out closer. Most of the shortfall came from the series changing regime, which no split can see coming. The rest was leakage between neighbouring samples, which a split can remove.
Related posts: Forecasting Many Related Time Series with Quantiles, where the booster trains only on days before the forecast origin, using many earlier origins; Card Fraud on Kaggle, which picks both final files by nested five-fold cross-validation; and Why Random Train-Test Splits Flatter Flood Models, which shows the same effect in space. I competed in M5 Forecasting - Uncertainty with a team and we finished 34th of 907 with a silver medal. The numbers below come from a synthetic lab, not from M5, and are means over 20 seeds, quoted as mean ± standard deviation.
In short
- Call estimated minus true error the gap. A negative gap means the estimate flatters the model, and its size is the optimism. Three things produce it: leakage between train and test, a test period unlike the future, and tuning on the folds you report.
- With a regime change in the lab's series, the gap was −0.390 ± 0.072 for a random K-fold, −0.313 ± 0.079 for blocked folds, −0.311 ± 0.079 for purged folds and −0.086 ± 0.123 for rolling origin with a buffer. Rolling origin was closer to the truth than the purged folds in all 20 seeds.
- With no regime change, a random K-fold was still low by 0.023 ± 0.020 (5.5%). Blocked, purged and hv-block folds were within 0.001 of the truth.
- With a label that averages the next 6 values, neighbouring labels of independent values correlate at 5/6. A buffer, purge and embargo remove that leak at the cost of some training data.
- Tuning on the reported folds added 0.016 to 0.028 to the gap for blocked, purged and rolling schemes. Nesting avoids it, because the choice is scored on data that took no part in it, at the cost of one fit per inner fold and candidate.
What a backtest should estimate
Fit a model on the data you have, deploy it, and call its average error on later data E. A backtest splits the data into K folds and gives the estimate Ê. The difference is the gap:
gap = Ê − E, Ê = (1/K) Σk=1..K error(model fitted on traink, scored on testk)
- Leakage. The training part holds information that also appears in the test part: a neighbouring sample, a label built from the same values, a feature that looks into the test period. A split can remove this.
- A test period unlike the future. If the process changes, old test blocks measure the old process. A split can weight recent blocks but cannot see a change that has not happened.
- Selection. Pick the best of many models on the folds you report, and the reported number is the minimum of noisy estimates. Nesting removes this.
Leakage is well documented in ML-based science: a survey found "17 fields where errors have been found, collectively affecting 329 papers" and a taxonomy of 8 types of leakage (Kapoor and Narayanan, see Sources).
The lab's series and task
The series xt has a seasonal period of 24 steps, an autoregressive error term and a regime change at step 1,000 of a 1,500-step development series. In regime 2 the level rises by 1.5, the error becomes more persistent (coefficient 0.85 instead of 0.6) and its innovations larger (standard deviation 0.8 instead of 0.6). Regime 2 runs on into a held-out future of 4,000 steps. The backtest sees only the first 1,500.
The task is to predict, at step t, the mean of the next H = 6 values. Features at t: the current value and two lags, the means of the last 6 and last 24 values (overlapping windows, so the longest look-back is L = 24), and the sine and cosine of the seasonal phase. The main model is a k-nearest-neighbours regressor with k = 12, which can memorise neighbours. A ridge regression on the same features is the low-capacity contrast. The error is the mean absolute error (MAE). A model's true error E is its MAE on the 4,000 future steps after fitting on all 1,500 development steps.
Every scheme has five folds over the 1,471 usable samples (steps 23 to 1,493). The rolling origins use the first 40% (588 samples) as the initial training set and five test blocks of about 177 samples covering steps 611 to 1,493. The sliding window keeps the latest 500 samples. The buffer between training and test is H = 6 samples.
Rolling origin
Forecast only from the past: "This procedure is sometimes known as “evaluation on a rolling forecasting origin” because the “origin” at which the forecast is based rolls forward in time." (Hyndman and Athanasopoulos, see Sources). For origins o1 < … < oK, a buffer of g samples and a test block of B samples:
ÊRO = (1/K) Σk error(model fitted on t < ok − g, scored on [ok, ok + B))
An expanding window keeps all history. A sliding window keeps a fixed length, which suits drift and costs data. In Nixtla's statsforecast, input_size None "uses expanding windows with all available history" and otherwise "uses rolling windows of fixed size", with n_windows and step_size setting the origins. scikit-learn's TimeSeriesSplit has max_train_size and gap (the buffer); sktime's ExpandingWindowSplitter has initial_window and step_length.
Early folds train on little data, so the estimate is noisy: the standard deviation of the gap was 0.123 for rolling origin and 0.072 to 0.081 for the K-fold schemes.
Buffers, purging and embargoes
The label is yt = (1/H) Σj=1..H xt+j. Two labels s steps apart share H − s of their values, so for independent values
corr(yt, yt+s) = (H − s) / H for s < H, and 0 for s ≥ H
That is 5/6 at s = 1 (a lab test confirms it on pure noise), and autocorrelation raises it. With one such sample in training and the next in test, the model has seen most of the answer.
A twelve-value series shows the leak exactly. Let H = 3 and let the label at t be the sum of the next three values, which is H times the lab's mean. A random split puts samples t = 2, 5 and 8 in the test set. A blocked split puts t = 4, 5 and 6 there, purges H samples before the block and embargoes 2 after it.
| t | Window | Label | Random split | Shares with test | Blocked split | After purge, embargo |
|---|---|---|---|---|---|---|
| 0 | x1 to x3: 5, 4, 7 | 16 | train | 1 with t=2 | train | train |
| 1 | x2 to x4: 4, 7, 6 | 17 | train | 2 with t=2 | train | purged |
| 2 | x3 to x5: 7, 6, 9 | 22 | test | none | train, overlaps | purged |
| 3 | x4 to x6: 6, 9, 8 | 23 | train | 2 with t=2, 1 with t=5 | train, overlaps | purged |
| 4 | x5 to x7: 9, 8, 10 | 27 | train | 1 with t=2, 2 with t=5 | test | test |
| 5 | x6 to x8: 8, 10, 12 | 30 | test | none | test | test |
| 6 | x7 to x9: 10, 12, 11 | 33 | train | 2 with t=5, 1 with t=8 | test | test |
| 7 | x8 to x10: 12, 11, 13 | 36 | train | 1 with t=5, 2 with t=8 | train, overlaps | embargoed |
| 8 | x9 to x11: 11, 13, 15 | 39 | test | none | train, overlaps | embargoed |
Under the random split, all 6 training labels share a value with a test label: the label at t = 3 is 23 = 6 + 9 + 8 and the test label at t = 2 is 22 = 7 + 6 + 9, so they share 6 and 9. Under the blocked split, 4 of the 6 training labels (t = 2, 3, 7, 8) still overlap the test block. The purge and embargo remove them, and t = 1 as well, because the rule below is slightly wider than needed. Only t = 0 is left, and it shares nothing. On 9 samples a clean split costs 5 of 6 training labels; at the lab's 1,471 samples it costs at most 30 per fold.
- Buffer (rolling origin). At origin o you know values up to o, so a training label at t is complete only if t + H ≤ o. The last H − 1 samples before the origin must go; the lab removes H. In scikit-learn,
gapis the "Number of samples to exclude from the end of each train set before the test set." - Purge (test blocks in the middle). López de Prado (2018): "eliminate from the training set all observations whose labels overlapped in time with those labels included in the testing set. I call this process purging."
- Embargo. Serially correlated features just after the test block look back into it, so "eliminate from the training set observations that immediately follow an observation in the testing set. I call this process embargo." It is not needed before the block, since earlier training labels "contain information that was available at the testing time". He suggests "A small value h ≈ .01T, where T is the number of bars, often suffices to prevent all leakage."
For a test block [a, b], the labels overlap exactly when a − H + 1 ≤ i ≤ b + H − 1, and a feature look-back L reaches into the block when i ≤ b + L − 1. So the purge may stop at a − H + 1, and the embargo must reach at least b + max(H − 1, L − 1). The lab uses the simpler bounds, which are one sample wider on each side:
drop training samples i with a − H ≤ i ≤ b + L
In the lab H = 6 and L = 24. On a toy sample of 20 with H = 3 and an embargo of 2, the folds are:
| Fold | Test samples | Purged (before) | Embargoed (after) | Training samples | Training count |
|---|---|---|---|---|---|
| 1 | 0 to 4 | none | 5 to 6 | 7 to 19 | 13 |
| 2 | 5 to 9 | 2 to 4 | 10 to 11 | 0 to 1, 12 to 19 | 10 |
| 3 | 10 to 14 | 7 to 9 | 15 to 16 | 0 to 6, 17 to 19 | 10 |
| 4 | 15 to 19 | 12 to 14 | none | 0 to 11 | 12 |
An hv-block-style buffer (after Racine, 2000) removes a fixed number of samples on both sides of the test block; the lab uses 24 each side, wider than the purge needs.
Why a random K-fold flatters a forecast
A shuffled K-fold treats samples as independent. In a time series neighbours are alike and overlapping labels are near copies. In the lab about 81% of the test samples in a random fold have a training sample one step earlier, against under 1% for a blocked fold, so a nearest-neighbour model forecasts points whose neighbours it has memorised.
Bergmeir, Hyndman and Koo show that for a purely autoregressive model "the use of standard K-fold CV is possible as long as the models considered have uncorrelated errors", and that only "if the models underfit the data and lead to heavily correlated errors" are cross-validation procedures "to be avoided as in such a case they may yield a systematic underestimation of the error", a case "easily detected by checking the residuals for serial correlation, e.g., using the Ljung-Box test." So a random K-fold fails when residuals are correlated, when features or labels overlap in time, or when the process is not stationary. Cerqueira, Torgo and Mozetič report that "cross-validation approaches can be applied to stationary time series", while in real-world settings with non-stationary variation "the most accurate estimates are produced by out-of-sample methods that preserve the temporal order of observations."
The same mechanism works in space. In the flood post, a nearest-neighbour model scored a critical success index of 0.751 with random cells held out and 0.611 with whole tiles, and random cells won in all ten seeds. Roberts et al. state it for temporal, spatial and hierarchical data: "when performing cross-validation, these structures are regularly ignored, resulting in serious underestimation of predictive error", and "Block cross-validation, where data are split strategically rather than randomly, can address these issues."
Nested tuning inside the backtest
Each fold score is true skill plus noise, so the best of m candidates sits below the typical one. For independent normal noise of spread σ the shortfall is at most about σ√(2 ln m); the lab's 20 variants are correlated, so the effect there is much smaller. Nesting avoids it. Split with the scheme you will report (outer folds). Inside each outer training part, run the same scheme (inner folds) to choose the model, refit on that part, and score the outer test block. No outer score took part in a choice.
for train, test in scheme(times): # outer folds
best = argmin over configs of mean_k error(scheme(train)) # inner folds, train only
model = fit(best, train)
outer_scores.append(error(model, test))
estimate = mean(outer_scores)
The rule covers every choice made on a fold. In the fraud post the boosters first stopped on the fold they were scored on; choosing the round on a 10 per cent holdout of the training fold lowered single-model scores by 0.00004 to 0.00009, which that post calls an optimistic bias. Nesting costs about K × (K × m + 1) fits instead of K × m: 505 against 100 per scheme in the lab.
What each scheme fixes and what it costs
| Method | Fixes | Costs | Gap, regime change | Gap, control |
|---|---|---|---|---|
| Random K-fold | Uses every sample | Trains on the future; leaks neighbours | -0.390 | -0.023 |
| Blocked K-fold | Keeps blocks together | Leaks at edges; trains on the future | -0.313 | +0.000 |
| Purged + embargoed | Removes overlap leaks | Drops H + L a fold; trains on the future | -0.311 | +0.001 |
| hv-block buffer | No label bookkeeping | Drops extra; trains on the future | -0.307 | +0.001 |
| Rolling, expanding | Trains on the past only | Last H − 1 labels unfinished | -0.089 | +0.002 |
| Rolling, expanding, buffer | Complete labels only | Small early folds, wide spread | -0.086 | +0.002 |
| Rolling, sliding, buffer | Forgets old regimes | Discards data | -0.098 | +0.016 |
| Nested tuning | Removes selection bias | K × (K × m + 1) fits, not K × m | see below | see below |
For the single-path weakness of walk-forward testing ("a single scenario is tested (the historical path), which can be easily overfit"), López de Prado proposes combinatorial purged cross-validation, which generates "thousands of train/test splits, so that every part of the series is tested multiple times (not just once)". The lab does not run it.
A small lab you can run
Download the lab (zip). It needs numpy. Run nice python run_lab.py (about 45 seconds) and nice python -m pytest -q (25 tests). Each test checks one claim against the alternative it rejects, and some check the quoted numbers against the saved results.
Each seed runs seven schemes and records the estimate for the fixed model, for ridge regression, for the best of 20 neighbour variants (10 values of k from 1 to 80, with and without the 24-step mean) chosen on the same folds, and for the nested version. The control is the same series with no regime change.
| Scheme | Estimate | Gap (true 0.935) |
|---|---|---|
| Random K-fold | 0.545 | -0.390 ± 0.072 |
| Blocked K-fold | 0.622 | -0.313 ± 0.079 |
| Purged + embargoed | 0.624 | -0.311 ± 0.079 |
| hv-block buffer | 0.628 | -0.307 ± 0.081 |
| Rolling, expanding | 0.846 | -0.089 ± 0.123 |
| Rolling, expanding, buffer | 0.849 | -0.086 ± 0.123 |
| Rolling, sliding, buffer | 0.837 | -0.098 ± 0.117 |
| Scheme | Estimate | Gap (true 0.423) | Ridge gap |
|---|---|---|---|
| Random K-fold | 0.399 | -0.023 ± 0.020 | -0.006 ± 0.016 |
| Blocked K-fold | 0.423 | +0.000 ± 0.020 | -0.001 ± 0.017 |
| Purged + embargoed | 0.423 | +0.001 ± 0.021 | -0.001 ± 0.017 |
| hv-block buffer | 0.423 | +0.001 ± 0.021 | -0.001 ± 0.017 |
| Rolling, expanding | 0.425 | +0.002 ± 0.027 | +0.001 ± 0.025 |
| Rolling, expanding, buffer | 0.425 | +0.002 ± 0.027 | +0.001 ± 0.025 |
| Rolling, sliding, buffer | 0.439 | +0.016 ± 0.027 | +0.005 ± 0.025 |
With the regime change, every scheme flattered the model. Purging changed little against plain blocking (the paired difference was +0.002 ± 0.004): some of these folds train on regime 2 data to test on regime 1 blocks, and regime 1 is the easier part. A random K-fold was lower than the purged folds in all 20 seeds, by 0.079 ± 0.025, which is the leakage on top of the regime effect. The same leak was 0.023 in the control; I did not test why it is larger here, and the more persistent error term is a likely cause.
The rolling estimate is the plain mean of its five blocks. For seed 0 the first two score 0.44 and 0.42, under half of the future's 0.92; the block that holds the regime change scores 1.74, and the last two 1.15 and 0.81. Over the 20 seeds the blocks average 0.42, 0.44, 1.38, 1.05 and 0.96, a mean of 0.849 against a true 0.935. The first two blocks were under half the true error in 12 of 20 seeds.
In the control the gap was +0.000 ± 0.020 for blocked folds and +0.001 ± 0.021 for purged and hv-block folds. Random K-fold was −0.023 ± 0.020, below the truth in 17 of 20 seeds and lower than the purged folds in all 20 (by 0.024 ± 0.004). Rolling origin gave +0.002 ± 0.027 with or without a buffer, since the leak touches only the first few test steps of each block. The sliding window was 0.014 ± 0.011 above the expanding one, the price of less training data. For ridge the random K-fold gap was −0.006 ± 0.016 against −0.023 ± 0.020 for the neighbour model: a linear model cannot memorise neighbours.
The estimates also fail to rank the seeds: the correlation between purged estimate and true error was −0.42 (−0.56 for random K-fold). One driver is the noise in the development sample, measured as the standard deviation of the regime-2 residuals over steps 1,000 to 1,499. Seeds with a noisier development sample tended to give a worse backtest and a lower true error (correlations of +0.69 and −0.52 over 20 seeds).
Tuning on the folds you report
For each scheme, the tuned estimate is the best fold score among the 20 variants. Both it and the nested estimate are compared with the true error of the variant chosen on all development data.
| Scheme | Tuned | Nested | Mean k | True error |
|---|---|---|---|---|
| Random K-fold | -0.400 ± 0.072 | -0.396 ± 0.071 | 11.6 | 0.942 |
| Blocked K-fold | -0.324 ± 0.079 | -0.300 ± 0.086 | 24.3 | 0.933 |
| Purged + embargoed | -0.322 ± 0.080 | -0.294 ± 0.092 | 23.2 | 0.933 |
| hv-block buffer | -0.318 ± 0.083 | -0.291 ± 0.095 | 23.6 | 0.934 |
| Rolling, expanding | -0.122 ± 0.107 | -0.106 ± 0.109 | 13.2 | 0.930 |
| Rolling, expanding, buffer | -0.122 ± 0.108 | -0.103 ± 0.109 | 13.7 | 0.931 |
| Rolling, sliding, buffer | -0.129 ± 0.110 | -0.111 ± 0.116 | 14.8 | 0.924 |
The nested estimate was higher than the tuned one by 0.025 ± 0.020 for blocked folds, 0.028 ± 0.021 for purged folds and 0.019 ± 0.018 for rolling origin with a buffer, in at least 17 of 20 seeds each. For random K-fold it was 0.004 ± 0.003, because one variant dominated its folds. Random folds also chose a different model: k = 11.6 on average against 23.2 for purged folds, and the random pick had the higher true error, 0.942 against 0.933 (paired difference +0.010 ± 0.020, higher in 15 of 20 seeds, equal in one). In the control the difference was only 0.002 to 0.008.
Where the optimism comes from
Roughly, the three sources add:
gap ≈ regime + leakage + selection
regime ≈ gap(blocked K-fold), leakage ≈ gap(scheme) − gap(purged), selection ≈ gap(tuned) − gap(nested)
For a random K-fold with the variant tuned on its own folds: −0.313 + (−0.390 − (−0.311)) + (−0.400 − (−0.396)) = −0.313 − 0.079 − 0.004 = −0.396, against an observed −0.400. The blocked gap stands in for the regime effect because it trains on the future but has almost no leakage. The terms come from different fits, so the sum is off by up to 0.02, as the table shows.
| Scheme | Regime | Leakage | Selection | Sum | Observed (tuned) |
|---|---|---|---|---|---|
| Random K-fold | -0.313 | -0.079 | -0.004 | -0.396 | -0.400 |
| Blocked K-fold | -0.313 | -0.002 | -0.025 | -0.340 | -0.324 |
| Purged + embargoed | -0.313 | +0.000 | -0.028 | -0.341 | -0.322 |
| hv-block buffer | -0.313 | +0.004 | -0.026 | -0.336 | -0.318 |
The regime term is the largest, and no split removes it.
Choosing a scheme
In scikit-learn the rolling origin with a buffer is one call. Set gap to the label horizon minus one, so that every training label is complete at the origin:
from sklearn.model_selection import TimeSeriesSplit
H = 3 # the label is the mean of the next H values
tscv = TimeSeriesSplit(n_splits=3, test_size=2, gap=H - 1)
for fold, (train, test) in enumerate(tscv.split(X)): # X has 12 rows
print(fold, train, test)
# Documented output for 12 samples, n_splits=3, test_size=2, gap=2:
# Fold 0: Train: index=[0 1 2 3] Test: index=[6 7]
# Fold 1: Train: index=[0 1 2 3 4 5] Test: index=[8 9]
# Fold 2: Train: index=[0 1 2 3 4 5 6 7] Test: index=[10 11]
In fold 0 the last training index is 3, its label reaches 3 + 3 = 6, and the first test index is 6. One more sample would be wasteful; one fewer would leak.
What I would check first
- What the label looks at. A label spanning H steps needs a buffer, purge or embargo of at least H − 1 samples; the longest look-back sets the embargo.
- Whether the folds ever train on the future. Random and blocked K-fold do. If the forecaster only sees the past, use a rolling origin.
- The error per test block, not only the mean, and a stationary control to separate leakage from regime effects.
- The model's residuals. Serial correlation (a Ljung-Box test) warns that K-fold estimates will be low.
- Everything chosen on a fold: hyperparameters, stopping rounds, weights, thresholds. Nest it, or keep a final block untouched.
- The spread over seeds or origins. A gap of −0.09 with a standard deviation of 0.12 is not a measurement of −0.09.
Limits of this post
- The data are synthetic: one seasonal period, an autoregressive error, one regime change. The sizes depend on the settings (H = 6, L = 24, five folds, 1,500 development steps, k-nearest neighbours), and the lab has no run with others.
- The true error is for a model fitted on all development data, so part of each gap is the difference in training size: 0.014 ± 0.011 for the sliding window against the expanding one in the control, near zero for K-fold schemes.
- Twenty seeds are few. The control's nested-minus-tuned differences (0.002 to 0.008) are small against their spreads, and the decomposition is a rough sum.
- The lab scores point forecasts, and its hv-block-style buffer is not a reproduction of Racine's method.
- A backtest cannot see a change that has not happened.
Sources
- V. Cerqueira, L. Torgo, I. Mozetič, Evaluating time series forecasting models: An empirical study on performance estimation methods, arXiv:1905.11744 (2019), Machine Learning 109 (2020)
- C. Bergmeir, R. J. Hyndman, B. Koo, A note on the validity of cross-validation for evaluating autoregressive time series prediction, Computational Statistics & Data Analysis 120 (2018) 70 to 83. Quotations from the authors' preprint.
- C. Bergmeir, J. M. Benítez, On the use of cross-validation for time series predictor evaluation, Information Sciences 191 (2012) 192 to 213 (DOI)
- J. Racine, Consistent cross-validatory model-selection for dependent data: hv-block cross-validation, Journal of Econometrics 99 (2000) 39 to 61 (DOI)
- L. J. Tashman, Out-of-sample tests of forecasting accuracy: an analysis and review, International Journal of Forecasting 16 (2000) 437 to 450 (DOI)
- M. López de Prado, The 10 Reasons Most Machine Learning Funds Fail (January 2018 version). The same author's book, Advances in Financial Machine Learning (Wiley, 2018), has the chapters "Cross-Validation in Finance" and "Backtesting through Cross-Validation" (see its table of contents).
- S. Kapoor, A. Narayanan, Leakage and the Reproducibility Crisis in ML-based Science, arXiv:2207.07048 (2022).
- D. R. Roberts et al., Cross-validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure, Ecography 40 (2017) 913 to 929
- R. J. Hyndman, G. Athanasopoulos, Forecasting: Principles and Practice, 3rd ed., section on time series cross-validation
- scikit-learn, TimeSeriesSplit (version 1.9.1 documentation)
- Nixtla, statsforecast core,
cross_validation - sktime, ExpandingWindowSplitter (version 1.2.0 documentation)