179. 生成用于回测的 walk-forward 训练和测试窗口
对于时间序列,随机的 train/test 切分会将未来信息泄露到训练中。回测(Backtesting)则是向前推进:在过去的数据上训练,在下一个数据块上测试,然后向前滑动并重复此过程。
编写 walk_forward(n, train_size, test_size, step, gap, expanding)。索引范围从 0 到 n - 1。第一个 fold 的训练窗口结束于 train_end = train_size (exclusive)。对于每个 fold:
- test_start = train_end + gap, test_end = test_start + test_size (exclusive)
- 如果 expanding 为 True,则 train_start = 0,否则 train_start = train_end - train_size (固定大小的 sliding window)
然后将 train_end 向前移动 step。仅保留其 test window 完全符合条件的 fold,即 test_end <= n。在第一个不符合条件的 fold 处停止。
返回一个包含 [train_start, train_end, test_start, test_end] 列表(ints)的列表。如果没有 fold 符合条件,则返回 []。
def walk_forward(n, train_size, test_size, step, gap, expanding)示例 1
输入: walk_forward(10, 4, 2, 2, 0, True)
输出: [[0, 4, 4, 6], [0, 6, 6, 8], [0, 8, 8, 10]]
示例 2
输入: n = 20, train_size = 5, test_size = 3, step = 4, gap = 1, expanding = False
输出: [[0, 5, 6, 9], [4, 9, 10, 13], [8, 13, 14, 17]]
示例 3
输入: n = 11, train_size = 4, test_size = 3, step = 3, gap = 0, expanding = True
输出: [[0, 4, 4, 7], [0, 7, 7, 10]]
约束条件
- Python 3 standard library. Code runs in your browser.
- Your code must pass all 4 tests to be accepted.
提示 1
Everything is driven by train_end: once you know it, the test window and the training start follow directly from the stated formulas.
提示 2
Start train_end at train_size, then repeat: compute test_start and test_end, stop if test_end goes past n, otherwise record the fold and move train_end forward by step.
提示 3
The stop check is test_end > n, since end indices are exclusive and test_end == n still fits. train_start is 0 when expanding, else train_end - train_size.
常见错误
- 像错误版本那样保留一个被截断、较短的最终 test window,会导致在不同量级的数据上对 fold 进行评分,这通常不是回测所期望的结果。
理解思路
对于时间序列,你不能进行 shuffle 和 split,因为模型会偷看未来。Walk-forward validation 就像一个天气预报员,只能使用过去的天数:在一段历史数据上训练,在下一段数据上测试,然后向前滑动并重复。
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]].
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. gap 留出了空间,使得 lag features 不会触及测试期。常用于需求、流量和成本预测的回测。