Folds That Only Look Back

Time SeriesMedium+20 XP+20

Folds That Only Look Back

A daily electricity-demand forecaster is tested with walk-forward validation: train on everything before a cut-off, test on the block right after it, then move the cut-off forward and do it again. The training window only ever grows.

There's one more constraint. The forecasts are needed horizon days ahead. With a horizon of hhh, the newest value you have sits hhh steps before the target, so in every fold the first test day sits hhh steps after the fold's last training day. Any days in between are left out of that fold: neither trained on nor tested.

Days are numbered 0 to n - 1.

  • Fold 1 trains on days 0 to first_cutoff - 1.
  • Each fold's test block is test_size consecutive days, starting horizon steps after that fold's last training day.
  • The next fold's cut-off is test_size days later, and it trains on every day before its cut-off.
  • Keep adding folds while the whole test block fits inside the series. A partial block is not a fold.

Task: write walk_forward_splits(n, first_cutoff, test_size, horizon=1) returning a list of tuples (train, test), where train and test are lists of day indices in increasing order. If not even one fold fits, return [].

Testing with a smaller gap than the real horizon lets each fold use fresher data than the deployed model will ever have, so the score comes out better than the model's real performance.

cups
304050
day
16121824
Fold 1
–
Fold 2
–
Fold 3
–
Average
–

24 days of a café's coffee sales, one dot per day. Fold 1 trains on days 1–12 and tests on 13–16.

Examples

n = 10
first_cutoff = 4
test_size = 2
returns [([0, 1, 2, 3], [4, 5]), ([0, 1, 2, 3, 4, 5], [6, 7]), ([0, 1, 2, 3, 4, 5, 6, 7], [8, 9])]
n = 12
first_cutoff = 5
test_size = 2
horizon = 3
returns [([0, 1, 2, 3, 4], [7, 8]), ([0, 1, 2, 3, 4, 5, 6], [9, 10])]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run