How do you split data by time so that the labels of the last train samples don’t take prices from the test period?
This post draws each fold (one split of the data) on a timeline, records when each label is complete, and purges the samples that straddle the boundary. The easy mistake: shuffling the candles at random, or leaving bad folds out of the report. Both make a walk-forward look better than reality.
Terms used below:
- Walk-forward: train on one period, test on the next, then roll both forward and repeat.
- Fold: one train/test split in that sequence.
- Purge: removing train samples whose label overlaps the boundary.
- Gap / embargo: a buffer of time between train and test. How long depends on the label and the design.
- Label end: the bar whose close completes a sample’s label.
One fold, drawn on a timeline
Draw the train, validation and test windows by date. Record each sample’s
feature time and the moment its label is complete. Remove train samples whose
label ends after the test starts, and fit scaling on train only. scikit-learn’s
TimeSeriesSplit has a gap parameter that drops a number of samples at the
end of each train set, but it doesn’t know your labels. Save the model version
of every fold, and the combined result in order, not just the good folds.
| Part | Position | What happens |
|---|---|---|
| Train | First | Fit the scaler and the model here only |
| Purge / gap | At the boundary | Remove samples whose label end is at or after the next part’s start |
| Validation | Middle | Choose within the locked range |
| Sealed test | Last | Once looked at, mark it contaminated; don’t rename it |
Each test window of a walk-forward usually has only a few trades, so the 95% interval of the mean R for a single window is very wide. Still report every window in order, but base the conclusion on the interval of the R pooled over all test windows. The number of variants you looked at, recorded in a registry, is the number of tries m used to raise the t threshold, as in the luck-or-skill post.
A 5-bar label crossing the boundary
- The test starts at bar 101; a train sample at 98 with a 5-bar label uses prices up to 103.
- Sample 98 has looked into the test period through its label.
- Remove it from train for this fold.
- Check every train sample whose label end is at or after the test start, under your boundary convention.
- After purging, train the model and scaler again before evaluating the test.
| Bar | Where | What |
|---|---|---|
| 98 | In train | The sample’s features; its label needs 5 bars |
| 101 | Start of test | The train/test boundary |
| 103 | Sample 98’s label is complete | Its label saw the test period: purge it |
The features sit in train but the label uses test prices: drop sample 98 from this fold’s train, refit the model and scaler, then evaluate the test.
Worked example: purge labels that cross the train/test boundary
A sample on 31 December has a label that needs the next three candles. If the test starts on 1 January, that label can use test data even though the features sit in train. So check the span of information behind the label, not just the date in the feature column. Remove or handle the samples that cross the boundary, as your locked design says.
In a rolling walk-forward, each step fits the scaler and model only on valid train data, chooses on validation, then predicts the next period. If you use an embargo, record its length and why; an arbitrary number doesn’t cure every leak by itself. Keep a table of folds, with train end, label end and test start, for reconciliation.
Exercise: draw ten bars, a 3-bar label, and a boundary before bar 8. Which samples have labels that reach into the test? (Samples 5, 6 and 7, whose labels end at 8, 9 and 10.) Then ask the AI to write a test for exactly that list; never shuffle at random and accidentally show the model the future.
| Wrong | Right |
|---|---|
| Shuffle the candles at random | Keep time order |
| Only look at the date in the feature column | Check the label’s span of information too |
| Fit the scaler on train and test | Fit on valid train only |
| Drop bad folds from the report | Report every fold, in order |
The code, src/walkforward.py. It runs the kNN signal from the kNN post over
rolling folds (2,000 bars of train, 1,000 of test), purging by label end. The
features are RSI 14 and the 100-bar return; the label is the sign of the
return over the next 24 bars. Then it shows two wrong reports, the best half
of the folds and a shuffled 5-fold split:
# src/walkforward.py: rolling walk-forward for a kNN signal, with label-based purging, against a shuffled split.
# Features at the close of t: RSI 14 and the 100-bar return. Label: sign of the return from t to t+H. Label end: t+H.
# .venv\Scripts\python src\walkforward.py data\xauusd_h1_utc.csv
import csv, math, sys
import numpy as np
H, K, COST, LOOK = 24, 15, 0.0002, 100
TRAIN, TEST = 2000, 1000
def rsi(c, n=14):
out, g, l = np.full(len(c), np.nan), 0.0, 0.0
for i in range(1, len(c)):
ch = c[i] - c[i - 1]
up, dn = max(ch, 0), max(-ch, 0)
g, l = ((g + up / n), (l + dn / n)) if i <= n else ((g * (n - 1) + up) / n, (l * (n - 1) + dn) / n)
if i >= n:
out[i] = 100.0 if l == 0 else 100 - 100 / (1 + g / l)
return out
def dataset(c):
X = np.column_stack([rsi(c), np.r_[np.full(LOOK, np.nan), c[LOOK:] / c[:-LOOK] - 1]])
ret = np.r_[c[H:] / c[:-H] - 1, np.full(H, np.nan)] # return from t to t+H
y = np.sign(ret)
label_end = np.arange(len(c)) + H
return X, y, ret, label_end
def folds(n, first, h=H, train=TRAIN, test=TEST):
"""Rolling folds in time order. Train samples whose label ends at or after the test start are purged."""
s = first + train
while s + test + h <= n: # every test label is complete in the file
tr = np.arange(s - train, s)
keep, purged = tr[tr + h < s], tr[tr + h >= s]
yield dict(keep=keep, purged=purged, test=np.arange(s, s + test))
s += test
def knn(X, y, train_idx, test_idx, k=K):
mean, std = X[train_idx].mean(0), X[train_idx].std(0, ddof=1) # the scaler sees train rows only
Z = (X - mean) / std
preds = np.empty(len(test_idx))
for n, t in enumerate(test_idx):
d = np.abs(Z[train_idx] - Z[t]).sum(1) # L1
near = train_idx[np.argpartition(d, k)[:k]]
preds[n] = np.sign(y[near].sum())
return preds
def stats(net):
m, s = net.mean(), net.std(ddof=1)
half = 1.96 * s / math.sqrt(len(net))
return m, m - half, m + half
def main(path):
with open(path, newline="") as f:
c = np.array([float(r["close"]) for r in csv.DictReader(f)])
X, y, ret, _ = dataset(c)
ok = ~np.isnan(X).any(1) & ~np.isnan(y) & (y != 0)
first = int(np.argmax(ok))
print(f"{len(c)} bars | horizon {H} | k {K} | train {TRAIN} | test {TEST} | cost {COST:.2%} per trade")
print("fold train purged test trades hit mean net 95% interval")
pooled = []
for i, f in enumerate(folds(len(c), first), start=1):
keep = f["keep"][ok[f["keep"]]]
test = f["test"][ok[f["test"]]]
p = knn(X, y, keep, test)
net = p * ret[test] - COST
pooled.append(net)
m, lo, hi = stats(net)
print(f"{i:>4} {f['keep'][0]:>5}-{f['purged'][-1]:<6} {len(f['purged']):>5} {test[0]:>5}-{test[-1]:<6}"
f" {len(test):>5} {np.mean(p == y[test]):5.1%} {m:+.4%} {lo:+.4%} .. {hi:+.4%}")
allnet = np.concatenate(pooled)
m, lo, hi = stats(allnet)
print(f"pooled: {len(allnet)} trades | mean net {m:+.4%} | 95% interval {lo:+.4%} .. {hi:+.4%}")
best = sorted(pooled, key=lambda a: a.mean(), reverse=True)[:len(pooled) // 2]
print(f"WRONG, best half of the folds only: mean net {np.concatenate(best).mean():+.4%}")
# WRONG: shuffle the bars into 5 random folds, no purge (neighbours from the future, overlapping labels)
idx = np.flatnonzero(ok)
rng = np.random.default_rng(0)
rng.shuffle(idx)
hits, nets = [], []
for part in np.array_split(idx, 5):
train = np.setdiff1d(idx, part)
p = knn(X, y, train, part)
hits.append(np.mean(p == y[part]))
nets.append(p * ret[part] - COST)
print(f"WRONG, shuffled 5-fold: hit {np.mean(hits):.1%} | mean net {np.concatenate(nets).mean():+.4%}")
if __name__ == "__main__":
main(sys.argv[1])On the made-up random walk from the tuning post (10,994 bars, no edge to
find), .venv\Scripts\python src\walkforward.py data\xauusd_h1_utc.csv:
10994 bars | horizon 24 | k 15 | train 2000 | test 1000 | cost 0.02% per trade
fold train purged test trades hit mean net 95% interval
1 100-2099 24 2100-3099 1000 51.0% -0.0448% -0.1016% .. +0.0121%
2 1100-3099 24 3100-4099 1000 47.8% -0.0372% -0.0884% .. +0.0141%
3 2100-4099 24 4100-5099 1000 50.9% -0.0292% -0.0868% .. +0.0284%
4 3100-5099 24 5100-6099 1000 48.2% -0.0079% -0.0655% .. +0.0498%
5 4100-6099 24 6100-7099 1000 53.2% +0.0807% +0.0280% .. +0.1335%
6 5100-7099 24 7100-8099 1000 54.6% +0.0583% +0.0041% .. +0.1125%
7 6100-8099 24 8100-9099 1000 50.5% -0.0033% -0.0598% .. +0.0531%
8 7100-9099 24 9100-10099 1000 50.6% -0.0737% -0.1356% .. -0.0118%
pooled: 8000 trades | mean net -0.0071% | 95% interval -0.0270% .. +0.0128%
WRONG, best half of the folds only: mean net +0.0320%
WRONG, shuffled 5-fold: hit 54.5% | mean net +0.0552%How to read it:
- Purged: 24 samples per fold, the train bars whose 24-bar label reaches past the test start.
- Folds 5 and 6 look good on their own; fold 6’s interval even excludes 0. On a random walk, that’s luck, which is why the conclusion uses the pooled row.
- Pooled: 8,000 predictions, mean −0.0071% per trade, interval from −0.0270% to +0.0128%. It contains 0: no evidence of an edge, as it should be.
- Best half of the folds: +0.0320%. The same predictions, minus the folds you’d rather not show.
- Shuffled 5-fold: 54.5% hit rate and +0.0552% per trade on a series with nothing to find. Random folds put bars from the future in train, and neighbouring bars share most of their 24-bar labels, so the model is graded on answers it has partly seen.
One caveat on the intervals: there’s a prediction on every bar and each is held 24 bars, so the trades overlap and the intervals are narrower than they should be. Real trades that don’t overlap, or a block bootstrap, give honest widths. The shuffled split’s inflation only showed up with slow features and a long label; with RSI and a 5-bar return it stayed under 1 point. Don’t rely on spotting it by eye; rely on the split.
The tests, tests/test_walkforward.py, including the bar-98 case and the
ten-bar exercise:
# tests/test_walkforward.py: which samples get purged, and that folds never look ahead.
import numpy as np
from src.walkforward import folds, knn
def test_sample_98_is_purged_when_test_starts_at_101():
f = next(folds(n=1200, first=1, h=5, train=100, test=50)) # train 1..100, test from 101
assert f["test"][0] == 101
assert 98 in f["purged"] and list(f["purged"]) == [96, 97, 98, 99, 100]
assert f["keep"][-1] == 95 # label ends at 100, before the test
def test_ten_bar_exercise():
# bars 1..10, horizon 3, the test starts at bar 8: labels of 5, 6, 7 reach into the test
f = next(folds(n=20, first=1, h=3, train=7, test=3))
assert f["test"][0] == 8 and list(f["purged"]) == [5, 6, 7]
def test_folds_are_in_order_and_never_overlap_the_test():
prev_end = -1
for f in folds(n=10_000, first=20, h=5):
assert f["keep"].max() + 5 < f["test"][0]
assert f["test"][0] > prev_end
prev_end = f["test"][-1]
def test_other_test_rows_never_change_a_prediction():
rng = np.random.default_rng(3)
X = rng.normal(size=(120, 2)) * [1.0, 50.0]
y = np.where(rng.random(120) > 0.5, 1.0, -1.0)
train, test = np.arange(100), np.arange(100, 120)
before = knn(X, y, train, test, k=5)
X[101:] = 1e6 # wreck every test row except the first
after = knn(X, y, train, test[:1], k=5)
assert before[0] == after[0] # the scaler only ever saw train rowsRun .venv\Scripts\python -m pytest -q tests; you should see 4 passed.
Try it: a nested walk-forward design
From this time-stamped data and rulebook, design a nested walk-forward for research; don't run an endless optimisation yet. Show the fold diagram, the scaler fitted on train only, purging of samples with label_end_at >= validation_start or test_start, and explain gap or embargo from the horizon and overlap. Build a registry of every experiment with version, parameters, seed, dataset hash, number of variants looked at, fees and slippage, and the reason for dropping it. Compare the baseline, a fixed configuration and each added filter. Use one sealed test; if it's been looked at, mark it contaminated instead of renaming it a new test. Return a leak-check table, 5 example rows at the boundary, and the asserts. Don't optimise on profit alone or publish a configuration as best for every market.Never paste passwords, API keys or tokens into a prompt, and check whatever the AI returns on the demo account before relying on it.
The order to work in:
- Draw train → validation → test; record the horizon, the feature lookback and the cut-off boundary before running.
- Lock the parameter list, the baseline and the costs; log every try, not just the leader.
- Open the test once, as planned; if you change something, make a new version and keep another unseen period.
Key takeaways
- The test starts at bar 101; a train sample at bar 98 with a 5-bar label uses prices up to 103, so it must leave that fold’s train.
- Walk-forward: each fold fits the scaler and the model on valid train only, chooses on validation, then predicts the next period.
TimeSeriesSplit’s gap or an embargo doesn’t know your label length; record the length and the reason, and keep the boundary table of every fold.
Comments