mysi Find

Calculator in Markets and quant

Walk-forward split by share

Splits daily returns into training and test windows by share and compares in-sample with out-of-sample Sharpe.

In short

Formulan = count of returns; t = floor(n÷(train_pct÷(1−train_pct)+num_windows)); s = n−num_windows×tWindow w = 0, 1, …: test rows s+w×t to s+(w+1)×t−1 (the last to n−1); training: the s rows before (rolling) or every row before (anchored)Sharpe = mean ÷ sample standard deviation × √252 (0 if no deviation); 252 trading days a year, a fixed conventionisReturn, oosReturn = sum of the block's returnsmeanIsSharpe, meanOosSharpe = average over windowsdropPct = (meanIsSharpe − meanOosSharpe) ÷ |meanIsSharpe| (0 if that is 0)totalIsObs, totalOosObs = training, test rows summed over windows
UnitsDaily returns as decimals.
Defaultsnum_windows 4 (1–50), train_pct 0.7 (0.01–0.99), mode rolling.
Worked examplereturns 0.01, −0.005, 0.012, 0.003, −0.008, 0.007, 0.004, −0.002, 0.006, −0.009, 0.011, 0.001; 2 windows; train_pct 0.5. t = floor(12÷3) = 4, s = 12−8 = 4Window 0 trains on rows 0 to 3: mean 0.005, deviation √(0.000178 ÷ 3) = 0.0077028, isSharpe = 0.005 ÷ 0.0077028 × 15.8745 = 10.304; tests on 4 to 7, oosSharpe = 0.597meanIsSharpe = 5.45, meanOosSharpe = 2.39, dropPct = 0.562

By hand: yes. A small model got these answers from the formulas above, without running code.

Say this to your agent

Use https://mysi.dev/walk-forward-validation-visualizer/ to walk-forward test my 12 daily returns in 2 windows, half training.

Nothing to install, no key, no settings. An agent that can open web pages and run Python opens the page, runs the tested code in its own sandbox and gives you the answer.

The code

Copy this into your Python tool. Run walk_forward_validation_visualizer_check() first, then call walk_forward_validation_visualizer() with your numbers. Give the answer with the cite line.

"""Walk-forward split by share: tiles a daily return series into one training block and
num_windows back-to-back test blocks, and gives each window's in-sample and out-of-sample
annualized Sharpe ratio and summed return, and the drop in Sharpe from training to test.
Inputs: returns (list of daily simple returns as decimals); num_windows (1 to 50, default 4);
train_pct (0.01 to 0.99, default 0.7: training length ÷ (training + test length));
mode ("rolling" or "anchored", default "rolling").
Returns per-window lists isStart, isEnd, oosStart, oosEnd (row indexes, end excluded),
isSharpe, oosSharpe, isReturn, oosReturn; and meanIsSharpe, meanOosSharpe, dropPct,
totalIsObs, totalOosObs.
mysi, Walk-forward split by share, mysi.dev/walk-forward-validation-visualizer, version 1,
changed 2026-12-04. MIT.
"""
import math
import statistics


def _walk_forward_validation_visualizer_sharpe(xs):
    # Sharpe 1994, no risk-free rate; annualized by sqrt(periods), Lo 2002, with the convention
    # of 252 trading days a year (daily returns)
    sd = statistics.stdev(xs)
    return 0.0 if sd == 0 else statistics.fmean(xs) / sd * math.sqrt(252)


def walk_forward_validation_visualizer(returns, num_windows=4, train_pct=0.7, mode="rolling"):
    ok = isinstance(returns, list) and all(
        isinstance(r, (int, float)) and not isinstance(r, bool) and math.isfinite(r)
        for r in returns)
    if not ok:
        raise ValueError("returns must be a list of numbers (daily returns as decimals)")
    if not isinstance(num_windows, int) or isinstance(num_windows, bool) \
            or not 1 <= num_windows <= 50:
        raise ValueError("num_windows must be a whole number from 1 to 50")
    if isinstance(train_pct, bool) or not isinstance(train_pct, (int, float)) \
            or not 0.01 <= train_pct <= 0.99:
        raise ValueError("train_pct must be a number from 0.01 to 0.99")
    if mode not in ("rolling", "anchored"):
        raise ValueError("mode must be one of: rolling, anchored")
    n = len(returns)
    test_span = math.floor(n / (train_pct / (1 - train_pct) + num_windows))
    train_span = n - num_windows * test_span
    if test_span < 2 or train_span < 2:
        raise ValueError(f"returns has {n} values: too few for {num_windows} windows "
                         "(each block needs at least 2)")
    out = {k: [] for k in ("isStart", "isEnd", "oosStart", "oosEnd",
                           "isSharpe", "oosSharpe", "isReturn", "oosReturn")}
    for w in range(num_windows):
        oos_start = train_span + w * test_span
        oos_end = n if w == num_windows - 1 else oos_start + test_span
        is_start = 0 if mode == "anchored" else oos_start - train_span
        ins, oos = returns[is_start:oos_start], returns[oos_start:oos_end]
        for key, value in (("isStart", is_start), ("isEnd", oos_start), ("oosStart", oos_start),
                           ("oosEnd", oos_end), ("isReturn", sum(ins)), ("oosReturn", sum(oos)),
                           ("isSharpe", _walk_forward_validation_visualizer_sharpe(ins)),
                           ("oosSharpe", _walk_forward_validation_visualizer_sharpe(oos))):
            out[key].append(value)
    mean_is = statistics.fmean(out["isSharpe"])
    mean_oos = statistics.fmean(out["oosSharpe"])
    out["meanIsSharpe"], out["meanOosSharpe"] = mean_is, mean_oos
    out["dropPct"] = 0.0 if mean_is == 0 else (mean_is - mean_oos) / abs(mean_is)
    out["totalIsObs"] = sum(e - s for s, e in zip(out["isStart"], out["isEnd"]))
    out["totalOosObs"] = sum(e - s for s, e in zip(out["oosStart"], out["oosEnd"]))
    return out


_walk_forward_validation_visualizer_r = [0.01, -0.005, 0.012, 0.003, -0.008, 0.007, 0.004,
                                         -0.002, 0.006, -0.009, 0.011, 0.001]
WALK_FORWARD_VALIDATION_VISUALIZER_CASES = [
    ({"returns": _walk_forward_validation_visualizer_r, "num_windows": 2, "train_pct": 0.5},
     {"isSharpe": [10.3044, 0.596601], "oosSharpe": [0.596601, 4.18282], "dropPct": 0.561559}),
    ({"returns": _walk_forward_validation_visualizer_r, "num_windows": 2, "train_pct": 0.5,
      "mode": "anchored"},
     {"isSharpe": [10.3044, 5.84426], "meanIsSharpe": 8.07431, "dropPct": 0.704035}),
    ({"returns": _walk_forward_validation_visualizer_r, "num_windows": 3, "train_pct": 0.25},
     {"oosStart": [3, 6, 9], "isSharpe": [9.68141, 1.36248, 10.1678], "dropPct": 0.38158}),
]


def walk_forward_validation_visualizer_check(tolerance=1e-3):
    for given, want in WALK_FORWARD_VALIDATION_VISUALIZER_CASES:
        got = walk_forward_validation_visualizer(**given)
        for name, value in want.items():
            pairs = zip(got[name], value) if isinstance(value, list) else [(got[name], value)]
            for g, v in pairs:
                assert abs(g - v) <= tolerance * max(1, abs(v)), (name, g, v)
    return "ok"


if __name__ == "__main__":
    import json, sys
    walk_forward_validation_visualizer_check()
    given = dict(a.split("=", 1) for a in sys.argv[1:] if "=" in a)
    js = lambda v: v.lstrip("-")[:1].isdigit() or v[:1] in '[{".' or v in ("true", "false", "null")
    given = {k: json.loads(v) if js(v) else v for k, v in given.items()}
    if given:
        print(json.dumps(walk_forward_validation_visualizer(**given)))
Raw file

What it takes

InputMeaningDefaultAllowed
returnsThe strategy's daily simple returns as decimals, oldest first (0.01 = 1%)requireda list
num_windowsNumber of test blocks41 to 50
train_pctTraining length ÷ (training length + test length)0.70.01 to 0.99
moderolling trains on the fixed-length block just before each test block; anchored trains on every row before itrollingrolling, anchored

What it returns

OutputMeaning
isStart, isEnd, oosStart, oosEndPer window, the first row and the row after the last of the training and test blocks, counted from 0
isSharpe, oosSharpePer window, the annualized Sharpe ratio of the training and the test block
isReturn, oosReturnPer window, the sum of the returns in the training and the test block
meanIsSharpe, meanOosSharpeThe average of the windows' training and test Sharpe ratios
dropPctFall from mean training Sharpe to mean test Sharpe, as a fraction of the training Sharpe's size
totalIsObs, totalOosObsRows used in training and in test, added over the windows

Where the method comes from

Walk-forward analysis, as Robert Pardo describes it, judges a trading strategy only on data it was not fitted to: the series is cut into a training block followed by a test block, and the pair is stepped forward through time. This function tiles the whole series with one training block and a chosen number of back-to-back test blocks, sized so that training and test lengths keep the ratio train_pct to one minus train_pct. Rolling windows keep the training length fixed; anchored windows grow it from the first row. For every block it reports the annualized Sharpe ratio (mean over sample standard deviation times the square root of 252, with no risk-free rate) and the summed return, and it measures how far the average Sharpe falls from training to test, the usual sign of an overfitted backtest. It only splits and scores the returns given; it does not refit any strategy, so the returns should already come from a strategy chosen on each training block. Short blocks give very noisy Sharpe ratios.

Sources

Tested

Tested 4 Dec 2026: claude-haiku-5-5 was right on 1 of 3 questions without this page and 3 of 3 with it; claude-fable-5-2 was right on 1 of 3 questions without this page and 3 of 3 with it.

Changes

Cite as: mysi, Walk-forward split by share, mysi.dev/walk-forward-validation-visualizer, version 1, changed 2026-12-04. Code MIT.