← All posts

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.

A noisy seasonal series from step 600 to 1,900 with dashed vertical lines at step 1,000 and 1,500; the level and swings are larger after step 1,000 Lab: one synthetic series (seed 0), development part and the start of the held-out future -4 0 4 8 regime change at t = 1,000 series ends at t = 1,500 held-out future 600 1,000 1,500 1,900 The seasonal period is 24 steps. Regime 2 has a higher level, a persistent and noisier error term, and runs on into the future. The true error is measured on 4,000 future points; a backtest only ever sees the left of the second dashed line.
Figure 1. The lab's series: the backtest sees steps up to 1,500; the true error is measured on the part after step 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.

Seven diagrams of five folds each on a 60-step sample. Top four: random, blocked, purged and embargoed, and hv-block K-fold. Bottom three: expanding window with no buffer, expanding window with a buffer, and a sliding window with a buffer Fold diagrams (toy values, not the lab's): 60 steps, 5 folds, time runs left to right Random K-fold Blocked K-fold Purged + embargoed K-fold (purge 2, embargo 3) hv-block-style buffer (3 steps each side) Rolling origin, expanding, no buffer Rolling origin, expanding, buffer of 2 Rolling origin, sliding window of 20, buffer of 2 train test dropped (purge, embargo or buffer) blank: not used in that fold Random folds scatter test steps among their neighbours. Blocked folds touch the test block at both edges; purging, the embargo or the buffer leave a margin. Rolling origin trains only on the past, and the first 40% is the initial training set.
Figure 2. Fold diagrams on a toy sample (toy values, not the lab's): where the test steps sit and what is dropped around them.

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.

Three bars each six steps long, shifted by one step, showing that labels at t = 6, 7 and 8 share most of their window; below, a timeline with train, purge, test block, embargo and train Why neighbouring samples leak: the label at t is the mean of the next 6 values label at t = 6 label at t = 7 label at t = 8 Labels at t = 6 and t = 7 share 5 of their 6 values. Labels H = 6 steps apart share none. Purge and embargo around a test block (a fold of a blocked K-fold) train purge test block embargo train Purge: a training label that ends inside the test block is dropped (H samples before it). In the lab H = 6. Embargo: a training sample after the block whose look-back reaches into it is dropped. In the lab the look-back is 24.
Figure 3. Overlapping labels, and the purge and embargo that remove their leak.

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.

tWindowLabelRandom splitShares with testBlocked splitAfter purge, embargo
0x1 to x3: 5, 4, 716train1 with t=2traintrain
1x2 to x4: 4, 7, 617train2 with t=2trainpurged
2x3 to x5: 7, 6, 922testnonetrain, overlapspurged
3x4 to x6: 6, 9, 823train2 with t=2, 1 with t=5train, overlapspurged
4x5 to x7: 9, 8, 1027train1 with t=2, 2 with t=5testtest
5x6 to x8: 8, 10, 1230testnonetesttest
6x7 to x9: 10, 12, 1133train2 with t=5, 1 with t=8testtest
7x8 to x10: 12, 11, 1336train1 with t=5, 2 with t=8train, overlapsembargoed
8x9 to x11: 11, 13, 1539testnonetrain, overlapsembargoed

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, gap is 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:

FoldTest samplesPurged (before)Embargoed (after)Training samplesTraining count
10 to 4none5 to 67 to 1913
25 to 92 to 410 to 110 to 1, 12 to 1910
310 to 147 to 915 to 160 to 6, 17 to 1910
415 to 1912 to 14none0 to 1112

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

MethodFixesCostsGap, regime changeGap, control
Random K-foldUses every sampleTrains on the future; leaks neighbours-0.390-0.023
Blocked K-foldKeeps blocks togetherLeaks at edges; trains on the future-0.313+0.000
Purged + embargoedRemoves overlap leaksDrops H + L a fold; trains on the future-0.311+0.001
hv-block bufferNo label bookkeepingDrops extra; trains on the future-0.307+0.001
Rolling, expandingTrains on the past onlyLast H − 1 labels unfinished-0.089+0.002
Rolling, expanding, bufferComplete labels onlySmall early folds, wide spread-0.086+0.002
Rolling, sliding, bufferForgets old regimesDiscards data-0.098+0.016
Nested tuningRemoves selection biasK × (K × m + 1) fits, not K × msee belowsee 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.

SchemeEstimateGap (true 0.935)
Random K-fold0.545-0.390 ± 0.072
Blocked K-fold0.622-0.313 ± 0.079
Purged + embargoed0.624-0.311 ± 0.079
hv-block buffer0.628-0.307 ± 0.081
Rolling, expanding0.846-0.089 ± 0.123
Rolling, expanding, buffer0.849-0.086 ± 0.123
Rolling, sliding, buffer0.837-0.098 ± 0.117
SchemeEstimateGap (true 0.423)Ridge gap
Random K-fold0.399-0.023 ± 0.020-0.006 ± 0.016
Blocked K-fold0.423+0.000 ± 0.020-0.001 ± 0.017
Purged + embargoed0.423+0.001 ± 0.021-0.001 ± 0.017
hv-block buffer0.423+0.001 ± 0.021-0.001 ± 0.017
Rolling, expanding0.425+0.002 ± 0.027+0.001 ± 0.025
Rolling, expanding, buffer0.425+0.002 ± 0.027+0.001 ± 0.025
Rolling, sliding, buffer0.439+0.016 ± 0.027+0.005 ± 0.025
Horizontal bars of estimated minus true error for seven schemes in two groups. With a regime change the random K-fold bar is longest, about 0.39 to the left of zero, blocked and purged about 0.31, rolling origin about 0.09. In the control all bars are near zero except random K-fold at about 0.02 Estimated minus true error (MAE), k-nearest-neighbours with k = 12, mean and spread over 20 seeds Series with a regime change at t = 1,000 Random K-fold -0.390 Blocked K-fold -0.313 Purged + embargoed K-fold -0.311 hv-block (buffer each side) -0.307 Rolling origin, expanding, no buffer -0.089 Rolling origin, expanding, buffer -0.086 Rolling origin, sliding, buffer -0.098 Control: the same series with no regime change Random K-fold -0.023 Blocked K-fold +0.000 Purged + embargoed K-fold +0.001 hv-block (buffer each side) +0.001 Rolling origin, expanding, no buffer +0.002 Rolling origin, expanding, buffer +0.002 Rolling origin, sliding, buffer +0.016 -0.4 -0.3 -0.2 -0.1 0 Bars left of zero mean the estimate flatters the model. Whiskers: one standard deviation over seeds.
Figure 4. Gap of each scheme with and without a regime change.

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.

Five bars of error per rolling-origin test block for seed 0 against time, with a dashed line for the true error on the future and a dashed vertical line at the regime change; the first two bars are low, the third is highest Lab: rolling-origin error in each test block, seed 0 (k = 12, expanding window with a buffer) 0.5 1.0 1.5 0.44 611 to 786 0.42 787 to 963 1.74 964 to 1139 1.15 1140 to 1316 0.81 1317 to 1493 true error on the future: 0.92 regime change at t = 1,000 Mean of the five blocks: 0.910. The two blocks before the change score 0.44 and 0.42, well under the future's 0.92. Mean over 20 seeds, block by block: 0.42, 0.44, 1.38, 1.05, 0.96.
Figure 5. Rolling-origin error per test block for seed 0: the early blocks sit well under the error on the future.

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.

Scatter of estimated against true error per seed for random K-fold, purged K-fold and rolling origin with a gap, with a dashed diagonal; random K-fold points lie lowest, purged points above them, rolling-origin points nearest the diagonal but widely spread Lab: estimated against true error, one point per seed (k = 12, regime change) 0.4 0.4 0.6 0.6 0.8 0.8 1.0 1.0 1.2 1.2 true error on the 4,000-point future estimated error random K-fold purged + embargoed K-fold rolling origin with buffer Dashed line: estimate equals truth. Random and purged points sit far below it: both often train on regime 2 data to test regime 1. Random sits lowest. Rolling origin is closer but scatters widely.
Figure 6. Estimated against true error for each seed, with a regime change.

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.

SchemeTunedNestedMean kTrue error
Random K-fold-0.400 ± 0.072-0.396 ± 0.07111.60.942
Blocked K-fold-0.324 ± 0.079-0.300 ± 0.08624.30.933
Purged + embargoed-0.322 ± 0.080-0.294 ± 0.09223.20.933
hv-block buffer-0.318 ± 0.083-0.291 ± 0.09523.60.934
Rolling, expanding-0.122 ± 0.107-0.106 ± 0.10913.20.930
Rolling, expanding, buffer-0.122 ± 0.108-0.103 ± 0.10913.70.931
Rolling, sliding, buffer-0.129 ± 0.110-0.111 ± 0.11614.80.924
Paired horizontal bars for seven schemes: the tuned-on-reported-folds bar is longer than the nested bar for every scheme, by about 0.025 for blocked and purged and 0.016 to 0.019 for rolling origin, and by 0.004 for random K-fold Estimated minus true error of the tuned model, 20 kNN variants, mean over 20 seeds Random K-fold -0.400 -0.396 Blocked K-fold -0.324 -0.300 Purged + embargoed K-fold -0.322 -0.294 hv-block (buffer each side) -0.318 -0.291 Rolling origin, expanding, no buffer -0.122 -0.106 Rolling origin, expanding, buffer -0.122 -0.103 Rolling origin, sliding, buffer -0.129 -0.111 tuned on the reported folds nested: tuned inside the training part only The nested bar is the honest one. The difference between the two bars is what tuning on the reported folds adds.
Figure 7. Tuning on the reported folds against nesting, with a regime change.

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.

SchemeRegimeLeakageSelectionSumObserved (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

A flow chart: is the process stationary with uncorrelated residuals? No or unsure leads to rolling origin with a buffer. Yes leads to an overlap question that ends in purged and embargoed K-fold or blocked K-fold. A final box says to nest the chosen scheme when choosing among models Which scheme for which situation 1. Is the process stationary, with uncorrelated model residuals? Rolling origin buffer of H - 1 or more if labels overlap sliding window if the process drifts 2. Do labels or features overlap in time? Purged + embargoed K-fold Blocked K-fold 3. Are you choosing among models or settings? Then nest the same scheme: choose on inner folds, score on outer folds no, or unsure yes yes no Rolling origin is the safe default. The K-fold branch only holds where Bergmeir, Hyndman and Koo say K-fold is valid.
Figure 8. A decision flow from the situation to the 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

  1. 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.
  2. 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.
  3. The error per test block, not only the mean, and a stationary control to separate leakage from regime effects.
  4. The model's residuals. Serial correlation (a Ljung-Box test) warns that K-fold estimates will be low.
  5. Everything chosen on a fold: hyperparameters, stopping rounds, weights, thresholds. Nest it, or keep a final block untouched.
  6. 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