Generate walk-forward train and test windows for backtesting

Random train/test splits leak the future into training for time series. Backtesting instead walks forward: train on the past, test on the next block, slide ahead, repeat.

Write walk_forward(n, train_size, test_size, step, gap, expanding). Indices run 0 to n - 1. The first fold's training window ends at train_end = train_size (exclusive). For each fold:
- test_start = train_end + gap, test_end = test_start + test_size (exclusive)
- train_start = 0 if expanding is True, else train_end - train_size (a sliding window of fixed size)
Then move train_end forward by step. Only keep folds whose test window fits completely, that is test_end <= n. Stop at the first fold that does not fit.

Return a list of [train_start, train_end, test_start, test_end] lists (ints). Return [] if no fold fits.

Signaturedef walk_forward(n, train_size, test_size, step, gap, expanding)

Example

walk_forward(10, 4, 2, 2, 0, True) gives [[0, 4, 4, 6], [0, 6, 6, 8], [0, 8, 8, 10]].

Understand the idea

For time series you cannot shuffle and split, because the model would peek at the future. Walk-forward validation is like a weather forecaster who is only allowed to use past days: train on a block of history, test on the next block, then slide forward and repeat. Worked example: n = 7, train_size 3, test_size 2, step 2, gap 0, sliding window. Fold 1: train_end = 3, test is [3, 5), train is [0, 3). Move train_end to 5: test [5, 7) fits, train [2, 5). Move to 7: test would end at 9 > 7, so stop. Result [[0, 3, 3, 5], [2, 5, 5, 7]]. Rule: test_start = train_end + gap, test_end = test_start + test_size; train_start is 0 when expanding, else train_end - train_size; keep a fold only if test_end <= n and stop at the first one that does not fit. The gap leaves room so lag features cannot touch the test period. Used for backtesting demand, traffic and cost forecasts.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplewalk_forward(10, 4, 2, 2, 0, True)
  • Sample 2: sliding with gapwalk_forward(20, 5, 3, 4, 1, False)
  • Test 3: partial last window droppedwalk_forward(11, 4, 3, 3, 0, True)
  • Test 4: nothing fitswalk_forward(5, 4, 2, 1, 0, True)