walk_forward#
Measures what a parameter search delivers out of sample. The best variant of a
strategy, chosen on the whole history, looks better than it is, because the
choice used the data it is scored on. walk_forward makes the choice the way
a trader would: on each training window it picks the candidate with the best
metric, and it trades that candidate on the test window that follows. The
stitched out-of-sample run is the honest estimate of the procedure "use the
variant that did best recently".
The history is split into folds. Test windows start at
t0 = train, train + test, train + 2 * test, ... while t0 < T, and each one
covers [t0, min(t0 + test, T)). Its training window is the train steps
before it, [t0 - train, t0), or all of the history before it,
[0, t0), with anchored=True.
Every candidate is backtested once over the whole history, and each training window is scored from that run as a backtest of its own: its equity starts where the run started, and a position held at its start counts as entered there. The candidate with the best score wins the fold. NaN scores lose, ties go to the lowest column, and a fold where every score is NaN (all candidates still in their warmup, for example) stays flat with choice -1.
The out-of-sample target holds the chosen candidate's target in each test window and 0 before the first one. It runs through the engine once, so a position carried from one fold into the next pays no extra cost, and a switch pays exactly the trade it causes.
With a portfolio engine, each candidate is a (T, K) target for the whole
book. Every window is scored on the book: equity, pnl and cost summed across
the assets, as position_test scores a portfolio. The
result's target is (T, K) and output (T, K, 4), a callable metric gets
one candidate's (L, K, 4) window and returns one number, and carry is a
(T, K) rate, one column per asset.
A portfolio engine reads a finite target as an order and NaN as "hold", so a
rebalancing schedule has NaN between its rebalance steps. When a test window
changes the book (the first test window, a switch to another candidate, or the
first window after a flat fold), a NaN on its first row is restated as the
new candidate's last finite target for the asset, or 0 when it has none (the
flat book its own run starts from), so the window starts from that candidate's
book. When the same candidate continues, its targets are used as given and the
held book carries over without a trade.
The function is batch-only. The backtests and the statistics run in C++; the function only slices, compares, and stitches.
Examples#
A trend rule on daily BTC with six lookback spans, a rolling one-year training window, and a three-month test window. The page Choose parameters with walk-forward testing plots the result and compares it with the span that looks best in hindsight.
import numpy as np
import pandas as pd
from screamer import EwMean, LogReturn, BacktestOHLCTarget, walk_forward
df = pd.read_csv("notebooks/data/binance_daily_20.csv")
btc = df[df.symbol == "BTC"]
o, h, l, c = (btc[k].to_numpy() for k in ["open", "high", "low", "close"])
spans = [5, 10, 20, 40, 80, 160]
ret = LogReturn()(c)
X = np.column_stack([np.sign(np.nan_to_num(EwMean(span=s)(ret))) for s in spans])
wf = walk_forward(BacktestOHLCTarget(taker_fee=5e-4), X, o, h, l, c,
train=365, test=91, periods_per_year=365)
print("span per fold:", [spans[k] for k in wf.choice])
print(f"out-of-sample Sharpe {wf.stats['sharpe']:.2f}, "
f"max drawdown {wf.stats['max_drawdown']:,.0f} USD")
span per fold: [160, 160, 5, 5, 40, 160, 80, 80, 80, 20, 20, 40, 40, 10, 10, 80]
out-of-sample Sharpe 0.42, max drawdown -30,014 USD
Signature#
walk_forward(engine, targets, *prices, train, test, metric="sharpe", anchored=False, periods_per_year=1.0, larger_is_better=None, carry=None, carry_multiplier=1.0)
engine: a target-position engine, such asBacktestOHLCTargetorBacktestPriceTarget, or a portfolio engine,BacktestPortfolioTargetorBacktestPortfolioOHLCTarget.targets: a(T, K)array with one target series per candidate, for example one column per parameter value. A(T,)series is one candidate. For a portfolio engine,(T, K, C): C candidates for K assets ((T, K)is one candidate), with(T, K)prices.prices: the engine's market inputs, as inengine(target, *prices).train: the length of each training window, at least 2 and shorter than the series.test: the length of each test window, at least 1. The last one can be shorter.metric: the selection statistic, any name from thebacktest_reportsummary, or a function that maps an engine output of shape(L, k, 4)tokvalues. The default is the Sharpe ratio.anchored: train on all history before each test window instead of the lasttrainsteps.periods_per_year: annualizes the ratios, as inbacktest_report. The default 1 gives per-step values.larger_is_better: the direction of the metric, as inposition_test. Statistics with no natural direction, such asturnover, need it.carry: a per-step carry rate (perpetual funding, borrow fee), a(T,)series ((T, K)for a portfolio engine) with the sign and timingBacktestCarrydocuments. With it, every candidate's run and the stitched run pass throughBacktestCarry(multiplier=carry_multiplier)before they are scored, marked with the market input named by the engine'smark_inputattribute:Engine
Marked with
BacktestPriceTargetthe price
BacktestOHLCTarget,BacktestOHLCVTargetthe close
BacktestTradesTargetthe trade price
BacktestL1Targetthe ask
BacktestPortfolioTargetthe price
BacktestPortfolioOHLCTargetthe close
A subclass of one of these engines inherits its mark, and an engine without
mark_inputraises withcarry.outputandstatsare after carry.carry_multiplieris the contract multiplier, as inBacktestCarry.
It returns a named tuple with these fields:
target: the stitched out-of-sample target, shape(T,), or(T, K)for a portfolio engine.choice: the candidate index (0 to C - 1) chosen in each fold, shape(n_folds,); -1 marks a fold that stays flat.fold_start: the first stept0of each test window.train_scores: every candidate's metric on every training window, shape(n_folds, C).output: the engine output ontarget, shape(T, 4)((T, K, 4)for a portfolio engine), after carry whencarryis given.stats: everybacktest_reportsummary statistic ofoutputfrom the first test window to the end, as a dict of floats.metric: the name of the metric.
Choosing the windows#
The training window has to hold enough trades for the metric to separate the candidates, and the test window sets how often the choice is revised. The two lengths are parameters of the procedure too: trying several and keeping the best brings back the selection bias that walk-forward removes. Pick them from the strategy's horizon, before looking at the result.
References#
Pardo, R. (2008). The Evaluation and Optimization of Trading Strategies, 2nd ed. Wiley.
Bailey, D. H., Borwein, J., López de Prado, M., and Zhu, Q. J. (2014). Pseudo-mathematics and financial charlatanism: the effects of backtest overfitting on out-of-sample performance. Notices of the AMS, 61(5), 458-471.