Howwise RSS
Trading Software8 min read

Walk Forward Validation in Python: Rolling and Anchored

Short answer

Walk forward validation in Python means repeatedly optimizing parameters on a training window, testing them on the next unseen block, advancing the window, and judging only the stitched out-of-sample returns.

Key takeaways
  • Set test length equal to step so out-of-sample blocks tile the history without overlap, and assert it in code.
  • Choose parameters on the train slice only, and prefer the median of the top-k parameter sets over the single max-Sharpe pick.
  • Concatenate per-fold OOS returns and compound once; never stitch equity levels or reset equity per fold.
  • Judge stability with chosen-parameter drift, walk-forward efficiency, the share of profitable folds and the spread of fold Sharpe.
  • Run the same loop on random-walk data: stitched OOS Sharpe near zero or negative after costs shows the harness is not leaking.

What is walk forward validation and why use it?

Walk-forward validation is a loop: optimize parameters on an in-sample (train) window, run them on the next unseen out-of-sample (test) block, then advance the window and repeat. Every test block is scored by parameters that never saw it.

A single full-history optimization reports the best result among many tried, which is a biased number. Walk-forward asks a different question: if this selection procedure had been run live at each date, what would it have earned? The unit being validated is the procedure (grid, objective, window sizes), not one parameter set.

It is also the trading version of time series cross validation. Ordinary shuffled k-fold lets the model train on the future, so it is unusable for backtests.

Anchored vs rolling walk forward: which should you use?

Anchored (expanding) windows always start at bar 0, so train grows each fold. Rolling windows keep a fixed train length and drop the oldest data. The trade is sample size against adaptation to regime change.

AspectAnchored (expanding)Rolling (fixed length)
Train sizeGrows every foldConstant
Parameter noiseFalls over time as data accumulatesStays similar across folds
Regime adaptationSlow; old regimes keep full weightFaster; old data ages out
Fold comparabilityLater folds have more data, so IS scores are not comparableFolds are statistically similar
Good fitRare-signal or low-frequency strategies needing many tradesIntraday or fast strategies, or markets whose behavior drifts
ComputeGrows with historyFlat per fold
Tip: Run both with the same test blocks. If anchored and rolling give very different stitched results, the edge depends on how much history you feed it, which is a finding in itself.

How do I choose train, test and step lengths?

Set the step equal to the test length. Then test blocks sit end to end, every bar after the first train window is out-of-sample exactly once, and the stitched series has no overlap.

Typical train:test ratios run from 3:1 to 5:1. Example: 20 years of daily bars (about 5040) with a 756-bar train (3 years) and 252-bar test gives (5040 - 756) / 252 = 17 folds.

Two constraints matter more than the ratio. Each train window needs enough trades for the objective to mean something (tens, not single digits), and you need enough folds that the fold statistics are not anecdotes. Under about 8 to 10 folds, treat the diagnostics as weak.

ChoiceToo smallToo large
Train lengthFew trades, noisy argmax, chasing noiseStale regimes, fewer folds
Test lengthFold Sharpe is mostly noise; costs from the switch dominateParameters go stale inside the block
Gap (purge/embargo)Labels or holds leak across the boundaryWasted data
Fold countDiagnostics are anecdotesOnly possible with short blocks, so see test length
Warning: Fix window sizes before looking at any out-of-sample result. Tuning train and test lengths until the stitched curve looks good turns the walk-forward itself into an overfit. If you must compare configurations, count them as extra trials.

Window generator and the leakage checklist

The generator yields integer index arrays and works for rolling or anchored mode. The gap argument is an embargo: bars skipped between the end of train and the start of test. Set it to at least the longest holding period or label horizon, otherwise a position or label opened in train resolves inside test.

The checks below fail loudly if you edit the generator badly.

import numpy as np, pandas as pd

def wf_windows(n, train, test, gap=0, anchored=False):
    k = 0
    while True:
        ts = train + gap + k * test      # step == test length
        te = ts + test
        if te > n:
            return
        a = 0 if anchored else ts - gap - train
        yield np.arange(a, ts - gap), np.arange(ts, te)
        k += 1

def check(folds):
    for i, (tr, te) in enumerate(folds):
        assert tr[-1] < te[0], 'train must end before test starts'
        if i:
            assert folds[i - 1][1][-1] < te[0], 'test blocks overlap'
            assert te[0] == folds[i - 1][1][-1] + 1, 'hole between test blocks'

Leak-safe rules to enforce in the loop

Most walk-forward leaks are not in the splitter. They are in what happens inside each fold. Work through this checklist:

  1. Select parameters using the train slice only, including any threshold, volatility target or ranking cutoff.
  2. Fit scalers, z-score statistics and model weights on train only, then apply them unchanged to test. A normalization fitted on the full sample leaks the future mean and variance.
  3. Warm up indicators for the test block with history from before it, but take no signals or fills from that history. Run the strategy on train plus test and slice out the test returns.
  4. Shift signals by one bar: a signal computed on bar t's close can only earn from bar t+1. A shift-less signal is the most common source of absurd Sharpe ratios.
  5. Apply a gap when labels or holding periods span the boundary.
  6. Charge costs on every position change, including the one at a fold boundary.
  7. Never reset equity per fold; carry returns, not balances.

Full minimal harness: grid search, folds and stitched OOS

The strategy here is a long/flat moving-average crossover, chosen only because it is short. Replace run_strategy with your own, keeping the contract: prices and params in, returns and positions out, with a one-bar shift and a cost.

Position carry-over is handled by running the strategy across train plus test. The open position at the boundary carries into test, and its cost is charged when it changes. To force flat at each boundary instead, multiply the first test bar's position by zero and charge the exit and re-entry cost.

Selection takes the median of the top-k parameter sets, not the single best, and scores -inf for train windows with too few trades. That damps the choice of a noisy peak.

from itertools import product
from joblib import Parallel, delayed

def run_strategy(prices, params, cost=0.0005):
    fast, slow = params
    sig = (prices.rolling(fast).mean() > prices.rolling(slow).mean()).astype(float)
    pos = sig.shift(1).fillna(0.0)                     # no same-bar fills
    ret = prices.pct_change().fillna(0.0) * pos - cost * pos.diff().abs().fillna(0.0)
    return ret, pos

def sharpe(r, ppy=252):
    s = r.std()
    return 0.0 if s == 0 or np.isnan(s) else r.mean() / s * np.sqrt(ppy)

def score(prices, params, min_trades=10):
    ret, pos = run_strategy(prices, params)
    trades = int((pos.diff().abs() > 0).sum())
    return (sharpe(ret) if trades >= min_trades else -np.inf), trades

GRID = [(f, s) for f, s in product([5, 10, 20, 30], [40, 60, 100, 150])]

def run_fold(prices, tr, te, grid=GRID, topk=3):
    trn = prices.iloc[tr]
    ranked = sorted(((score(trn, p)[0], p) for p in grid), key=lambda x: x[0], reverse=True)
    top = [p for s, p in ranked[:topk] if np.isfinite(s)]
    if not top:
        return None
    params = tuple(int(round(np.median([p[i] for p in top]))) for i in (0, 1))
    full = prices.iloc[tr[0]: te[-1] + 1]              # warm-up comes from train history
    ret, pos = run_strategy(full, params)
    oos = ret.loc[prices.index[te]]
    row = dict(test_start=prices.index[te[0]], fast=params[0], slow=params[1],
               is_sharpe=score(trn, params)[0], oos_sharpe=sharpe(oos),
               oos_ret=(1 + oos).prod() - 1,
               trades=int((pos.loc[oos.index].diff().abs() > 0).sum()))
    return row, oos

def walk_forward(prices, train=756, test=252, gap=0, anchored=False, n_jobs=-1):
    folds = list(wf_windows(len(prices), train, test, gap, anchored))
    check(folds)
    out = Parallel(n_jobs=n_jobs)(delayed(run_fold)(prices, tr, te) for tr, te in folds)
    out = [o for o in out if o is not None]
    report = pd.DataFrame([o[0] for o in out])
    oos = pd.concat([o[1] for o in out])               # returns, not equity levels
    assert oos.index.is_unique and oos.index.is_monotonic_increasing
    return report, oos

report, oos = walk_forward(prices)                     # prices: pd.Series, DatetimeIndex
equity = (1 + oos).cumprod()                           # compound once
print('stitched OOS Sharpe', round(sharpe(oos), 2), 'final equity', round(equity.iloc[-1], 3))
Warning: Compute metrics only on the stitched series. Averaging per-fold CAGR or drawdown hides the drawdown that spans a fold boundary. Concatenating equity levels instead of returns also creates false jumps, because each fold's curve restarts at 1.

How do I judge parameter stability and prove the loop does not leak?

Print the fold report and read it as a table: fast and slow per fold, IS Sharpe, OOS Sharpe and trades. Parameters that jump between opposite corners of the grid each fold mean the surface is flat or noisy, and the walk-forward is mostly picking at random.

Walk-forward efficiency (WFE) is OOS performance divided by IS performance. A common form is mean OOS Sharpe divided by mean IS Sharpe. Values well below 1 are normal because IS is optimistically biased. Near zero or negative means the in-sample edge did not carry over. Above 1 on a few folds is usually luck.

Fold Sharpe over a 252-bar block has a standard error of roughly 1 on annual data, so judge the distribution and the median, not single folds.

DiagnosticHow to computeWorrying sign
Parameter driftreport[['fast','slow']].describe()Chosen values span most of the grid
WFEreport.oos_sharpe.mean() / report.is_sharpe.mean()Near zero or negative
% profitable folds(report.oos_ret > 0).mean()Near 50% with a few big winners driving the total
Fold Sharpe spreadreport.oos_sharpe.describe()Median near zero, wide tails
Trades per foldreport.tradesUnder about 10, so metrics are unreliable
def random_walk(seed, n=5000):
    r = np.random.default_rng(seed).normal(0, 0.01, n)
    idx = pd.bdate_range('2005-01-03', periods=n)
    return pd.Series(100 * np.exp(np.cumsum(r)), index=idx)

sharpes = [sharpe(walk_forward(random_walk(s), n_jobs=1)[1]) for s in range(30)]
print(np.mean(sharpes), np.percentile(sharpes, [5, 50, 95]))
# Expect a mean near zero or negative (costs). A clearly positive mean means a leak.
Tip: Prove the test can catch a leak: remove the shift(1) in run_strategy and rerun. On random data the null Sharpe should jump sharply upward. If your own harness stays flat after you break it on purpose, the test is not sensitive.

Common mistakes, speed and the TimeSeriesSplit alternative

The failures below account for most walk-forward results that fail to reproduce live.

MistakeWhy it hurtsFix
Tuning window sizes after seeing OOSThe walk-forward becomes the thing being overfitFreeze sizes first; log every configuration tried
Too few foldsDiagnostics are anecdotesShorter test blocks, or accept the result is weak
Overlapping test windowsBars counted twice inflate Sharpestep == test, plus the assertions
Shift-less signalsTrading on the bar that generated the signalshift(1) and the broken-shift test
Ignoring costsFast parameters win in-sample on fees you never payCharge fees and slippage on every position change
Max-Sharpe argmaxSelects a noisy peakMedian of top-k, trade-count penalty

Common questions

Can I use sklearn TimeSeriesSplit for walk forward validation?

Yes. TimeSeriesSplit(n_splits=k, test_size=252, gap=5) gives expanding train windows with fixed test blocks and an embargo gap, and passing max_train_size makes it rolling. It only produces indices, so you still write the per-fold optimization and stitching yourself. Check that the test blocks tile the data, because by default the first train window is whatever is left over.

How do I stitch out-of-sample results from a walk forward?

Concatenate the per-fold OOS return series in time order with pd.concat, assert the index is unique and increasing, then compute (1 + oos).cumprod() once. Never join per-fold equity curves, since each restarts at 1. Compute Sharpe, drawdown and CAGR on this single series.

How many folds do I need?

Aim for at least 8 to 10, and more if the strategy trades rarely. With fewer folds the percentage of profitable folds and the WFE are too coarse to separate skill from luck. If the history is short, shorten the test block rather than the train block, as long as each test block still has enough trades.

Should I carry the open position across a fold boundary or go flat?

Carrying is closer to live trading, where the parameter update does not flatten the book. Flattening is cleaner when the new parameters imply a very different position. Either way, charge the cost of any position change at the switch and keep equity continuous.

How do I speed up walk forward optimization in Python with pandas?

Folds are independent, so joblib Parallel with delayed runs them across cores. Keep the grid small, precompute rolling features once per parameter value, and use numpy arrays inside inner loops. Pass n_jobs=1 while debugging so errors show a clear traceback.

Related topics:walk-forwardbacktestingpythonpandasoverfitting