Walk Forward Optimization in Python: Leak-Safe Harness
Walk forward optimization python code repeats one loop: fit parameters on an in-sample window, freeze them, trade the next unseen window, roll forward, and judge only the stitched out-of-sample returns, purged at the boundaries.
- Only the concatenated out-of-sample returns count as the result; in-sample numbers are diagnostics, never performance.
- Purge at least as many bars as your label horizon or maximum holding period between train end and test start.
- Give each test window a warm-up prefix for indicators, but never fit parameters or book trades on it.
- Choose parameters from a neighbourhood-smoothed score, not the single best grid cell, and fix the objective before running.
- Once you change the search space after seeing OOS results, that OOS is burned; keep a final untouched holdout and log the number of trials.
What does walk forward optimization in Python actually do?
Walk forward analysis is a repeated cycle. Optimize parameters on an in-sample (IS) window, freeze them, trade the next unseen out-of-sample (OOS) window, then roll forward and repeat. The parameters chosen at each fold are never scored on the data that selected them.
The result is not the best IS parameters and not an average of parameters. It is the single return series made by gluing every OOS segment together. A single train/test split gives one noisy sample of that; a full-sample grid search gives none, because every bar influenced the choice.
- Split the time index into consecutive folds: train, purge gap, test.
- Search the parameter grid using the train segment only.
- Select parameters with a pre-declared, stability-aware objective.
- Run the test segment with those frozen parameters, including costs.
- Store the OOS returns and the fold's IS score, then advance by one test length.
- After the last fold, concatenate OOS returns and compute all metrics on the stitched series.
Rolling or anchored walk forward: which should I use?
A rolling window keeps a fixed train length and drops old data. An anchored (expanding) window keeps the start fixed so the train set grows. The choice is a bet about whether old data is still representative.
Anchored folds share most of their data, so their parameters change slowly and each fold's fit is more stable. The cost is that early regimes keep weighing on the fit and later folds are slower to adapt. Rolling does the opposite: it adapts, but each fit sees fewer trades and is noisier. Running both and seeing whether conclusions agree is a useful robustness check.
| Property | Rolling | Anchored (expanding) |
|---|---|---|
| Train length | Fixed | Grows each fold |
| Old regimes | Dropped | Always included |
| Parameter stability | Lower, more fold-to-fold jumps | Higher |
| Adapts to drift | Faster | Slower |
| Compute per fold | Constant | Grows |
| Good fit when | Behaviour is non-stationary and data is plentiful | Trades are scarce and the edge is assumed persistent |
How do I size the train and test windows?
Start from trade count, not calendar time. Each parameter set should be judged on at least 30 trades in the train window, and hundreds is better. If a candidate trades twice a month, a one-year train window is far too short.
The train window should also span several regimes (trend, chop, high and low volatility). A common IS:OOS ratio is 3:1 to 5:1, and you want at least 8 to 10 folds so that fold dispersion means something. Too-short windows give noisy parameters; too-long windows average over drift and hide it.
Worked example with 2,520 daily bars (about 10 years): train 504, test 126 (4:1), purge 10. The first test starts at bar 514 and the loop yields 15 folds, which is enough to see dispersion. With train 756 and test 252 you would get only 6 folds, too few to judge. Decide these numbers from trade counts and the fold target before looking at any OOS output, then do not tune them to flatter the result.
A leak-safe walk forward harness in about 40 lines
The sketch below uses a moving-average crossover as a stand-in strategy. The pieces that matter are generic: an index generator with a purge gap, indicators computed on a warm-up prefix then cut to the test range, costs charged on position changes, and a smoothed score for selection.
Position at bar t uses signals shifted by one bar, so a signal never trades on its own close. Because the warm-up prefix is run through the same position logic, the position already open at the fold boundary is carried in, and the first test bar pays no spurious entry cost.
import numpy as np, pandas as pd
from itertools import product
from scipy.ndimage import uniform_filter
def wf_splits(n, train, test, purge=0, anchored=False):
t0 = train + purge
while t0 + test <= n:
tr_end = t0 - purge # train stops 'purge' bars before test
tr_start = 0 if anchored else tr_end - train
yield np.arange(tr_start, tr_end), np.arange(t0, t0 + test)
t0 += test
def sharpe(r):
return np.sqrt(252) * r.mean() / (r.std() + 1e-12)
def run(px, p, lo, hi, warm, cost=0.0005):
seg = px.iloc[max(0, lo - warm):hi] # warm-up prefix, prior data only
f, s = p
pos = (seg.rolling(f).mean() > seg.rolling(s).mean()).astype(float).shift(1).fillna(0)
r = seg.pct_change().fillna(0) * pos - pos.diff().abs().fillna(0) * cost
return r.iloc[-(hi - lo):] # keep only the real window
def walk_forward(px, fasts, slows, train, test, purge, warm, anchored=False):
oos, rows = [], []
for tr, te in wf_splits(len(px), train, test, purge, anchored):
grid = product(fasts, slows)
# swap for joblib.Parallel(n_jobs=-1) when the grid is large
s = np.array([sharpe(run(px, p, tr[0], tr[-1] + 1, warm)) for p in grid])
s = s.reshape(len(fasts), len(slows))
sm = uniform_filter(s, size=3, mode='nearest') # neighbourhood-averaged score
i, j = np.unravel_index(sm.argmax(), sm.shape)
p = (fasts[i], slows[j])
r = run(px, p, te[0], te[-1] + 1, warm) # frozen params on unseen data
oos.append(r)
rows.append(dict(start=px.index[te[0]], fast=p[0], slow=p[1],
is_sharpe=s[i, j], oos_sharpe=sharpe(r)))
return pd.concat(oos), pd.DataFrame(rows)
# px: pd.Series of adjusted closes with a sorted DatetimeIndex
# oos, folds = walk_forward(px, [5,10,20,30], [50,100,150,200], 504, 126, 10, warm=250)Where does leakage hide? Purge, embargo and warm-up
Purging matters when a label or trade looks forward. If a train sample at bar t uses the return from t to t+5, then the last 5 train bars contain information from the test period. Dropping at least H bars before the test start removes that overlap. For rule-based strategies, set the purge to the longest holding period or forward horizon, so no train trade is still open when the test begins.
An embargo skips bars after a test segment. In walk forward, training data never comes after the test, and the next fold's purge already covers the boundary, so the embargo mainly matters in purged k-fold (López de Prado), where train data sits on both sides of the test block. Plain k-fold shuffles time and leaks future information into training; avoid it for serial data.
Layout for rolling, train 504, purge 10, test 126, anchored shown for fold 2:
| Leakage point | Symptom | Fix |
|---|---|---|
| Overlapping labels or holding periods | IS and OOS scores suspiciously close | Purge at least H bars before test |
| No indicator warm-up | First bars of each test window have no signal | Prefix of prior bars, cut after computing |
| Scaler or z-score fit on all data | OOS looks better than any live behaviour could | Fit on train only, apply frozen to test |
| Full-sample features (rank, quantile, PCA) | Implausibly smooth OOS curve | Recompute per fold from train |
| Position open at the split | Double-counted or missing trades at boundaries | Carry state via warm-up, charge cost only on changes |
| Adjusted prices that use future splits or dividends | Gaps at corporate actions | Use point-in-time adjusted data; include delisted names |
bars: 0 504 514 640 766
rolling fold1 [train 0..503][purge][ test 514..639 ]
fold2 [train 126..629][purge][ test 640..765 ]
anchored fold2 [train 0..629 ][purge][ test 640..765 ]
purge = bars 504..513 (fold1) are dropped from training.
warm-up for test 514: bars 264..513 feed indicators only; no fitting, no trades counted. How do I read walk forward results and judge robustness?
Concatenate the OOS returns and compute everything on that one series: equity curve, Sharpe, maximum drawdown. Then look at the folds: dispersion of OOS Sharpe, and the share of folds with positive OOS return. A good pooled number driven by two lucky folds is fragile.
Walk-forward efficiency (WFE) is OOS performance divided by IS performance, here mean OOS Sharpe over mean IS Sharpe. Values near or above about 0.5 are usually treated as acceptable; values near zero or negative mean the IS edge did not transfer. Also watch parameter drift: if the chosen fast and slow values jump around between folds, the objective surface is flat or noisy.
Then compare against something. A walk-forward result with no baseline cannot tell skill from a favourable market. Use fixed parameters on the same OOS spans, and a null built from random parameters per fold.
eq = (1 + oos).cumprod()
max_dd = (eq / eq.cummax() - 1).min()
wfe = folds.oos_sharpe.mean() / folds.is_sharpe.mean()
print(sharpe(oos), max_dd, wfe,
folds.oos_sharpe.std(), (folds.oos_sharpe > 0).mean())
# null: random parameters in every fold, same splits, same costs
rng = np.random.default_rng(0)
fasts, slows = [5,10,20,30], [50,100,150,200]
null = []
for _ in range(200):
rs = [run(px, (rng.choice(fasts), rng.choice(slows)), te[0], te[-1] + 1, 250)
for _, te in wf_splits(len(px), 504, 126, 10)]
null.append(sharpe(pd.concat(rs)))
pct = (np.array(null) < sharpe(oos)).mean() # share of random runs beaten Common mistakes, burned OOS and tooling
The most damaging mistake is peeking. If you see poor OOS results, widen the grid and rerun, that OOS segment has now influenced the design and is burned. Keep a final holdout beyond the last fold, touch it once, and log every configuration, window size and objective tried. The trial count matters because the best of many tries looks good by chance; the deflated Sharpe ratio and White's Reality Check exist to adjust for this.
Other frequent bugs: too few trades per fold, so Sharpe is noise; ignoring costs and slippage in the search (the optimizer then favours high turnover); and fitting parameters on the warm-up prefix. Re-optimization is compute-heavy, since folds times grid size backtests must run, so parallelize over grid cells with joblib and cache indicator arrays per lookback instead of recomputing them per cell.
Pick tooling by how much control you need.
| Tool | Good for | Limitation |
|---|---|---|
| Hand-rolled loop | Full control of purge, state, costs | You own every bug |
| sklearn TimeSeriesSplit (gap, max_train_size, test_size) | Quick rolling or expanding splits with a fixed test length and a gap | Forward-only splits with `gap` as a purge; no embargo and no label-aware purging; warm-up and per-fold stitching still need handling yourself |
| vectorbt splitters and rolling ranges | Fast vectorized grids across many windows | Warm-up and state handling need care |
| skfolio or mlfinlab purged CV | Purged and embargoed k-fold with label overlap | k-fold folds are not a forward-only path |
| Backtesting.py optimize | Convenient single-window optimizer | You still write the outer walk-forward loop |
Common questions
Can I use Optuna instead of a grid in walk forward optimization?
Yes, run a fresh study per fold on the train segment only and never share trials across folds. Seed it, fix the trial budget in advance, and count total trials, since a larger budget increases selection bias. Smoothing is harder than with a grid, so consider averaging the top few trials' parameters or re-scoring the best ones on perturbed settings.
Is sklearn TimeSeriesSplit enough for walk forward analysis?
It gives forward-only splits, `test_size` fixes the test length, `max_train_size` switches it from anchored to rolling, and `gap` acts as a purge. It has no embargo and no awareness of overlapping labels or open positions, so you still need warm-up handling and per-fold stitching yourself. It is fine for a model's feature matrix, less so for a trade-level backtest.
What does a low walk forward efficiency ratio mean?
A WFE near zero or negative means the in-sample edge did not carry to unseen data, which is the usual signature of overfitting or a regime change. First check for too few trades per fold, high turnover with underestimated costs, and an over-large grid. If the strategy has few parameters and still shows low WFE, the idea itself probably lacks a stable edge.
How many folds do I need?
Aim for at least 8 to 10 so you can see dispersion and the share of profitable folds. Fewer folds make the stitched result depend on one or two regimes. If that forces test windows too short to hold a meaningful trade count, you need more data or a faster-trading strategy, not smaller windows.
Should I re-optimize on every bar?
Not usually. Re-optimizing more often than your test window multiplies compute and adds parameter churn without more evidence. Shorter test windows adapt faster but produce noisier fold metrics and more boundary effects, so choose the cadence by trade count first.