Lesson 14 of 15

Walk-Forward Validation

Walk-Forward Validation

Walk-forward validation is a more rigorous backtesting technique that prevents overfitting. Instead of optimizing and testing on the same data, you repeatedly train on a historical window and test on the immediately following period.

Algorithm

Given n total data points, a training window of size n_train, and a test window of size n_test:

start = 0
while start + n_train + n_test <= n:
    train: [start, start + n_train)
    test:  [start + n_train, start + n_train + n_test)
    start += n_test   # walk forward by one test period

Each split is represented as (train_start, train_end, test_start, test_end).

Example

walk_forward_splits(20, 10, 5) produces:

  • (0, 10, 10, 15) — train on 0–9, test on 10–14
  • (5, 15, 15, 20) — train on 5–14, test on 15–19

Task

Implement walk_forward_splits(n, n_train, n_test) that returns a list of tuples.

Python runtime loading...
Loading...
Click "Run" to execute your code.