How do I test a rule year by year, choosing its settings only from the past?

Choose a moving-average rule’s window on the years before each test year, apply it to that year, and compare the walk-forward result with the best window picked in hindsight.

After this lesson, you can choose a rule’s setting on the past before each test year and measure the result on the years that follow.

How do I choose the window before each year?

A walk-forward test chooses the setting before each test year from the years before it, applies it to that year, and joins the test years. Here the setting is the window of a moving-average rule, and the choice moves between windows from year to year.

The example is ten years of a made-up stock’s daily returns, normal with a mean of 0 and a standard deviation of 1%, so no window has an edge. The rule holds the stock while its close is above the mean of the last window closes, as in the lesson on signals. .shift(2, fill_value=0) moves each signal two rows down, because a signal at one close trades at the next and earns the return after that. strategy holds one column of daily returns per window, from 10 to 200 days.

sharpe gives the yearly Sharpe ratio, as in the lesson on performance measures. best_window scores every window on the training rows and returns the best one, and .iloc[:-1] drops the last training row, because the window must be set at the close before the last one. The dictionary comprehension chooses one window per test year from 2016 to 2023 on all earlier years, and pd.concat joins each year’s returns of its chosen window.

The following box builds the returns of the 20 windows and runs the walk-forward test.

import numpy as np
import pandas as pd

dates = pd.bdate_range("2014-01-01", "2023-12-31")
rng = np.random.default_rng(19)
stock_return = pd.Series(rng.normal(0, 0.01, len(dates)), index=dates)
price = 100 * (1 + stock_return).cumprod()

windows = range(10, 201, 10)
signals = pd.DataFrame({window: (price > price.rolling(window).mean()).astype(int) for window in windows})
strategy = signals.shift(2, fill_value=0).mul(stock_return, axis=0)

def sharpe(returns):
    return np.sqrt(252) * returns.mean() / returns.std()

def best_window(past):
    return int(past.iloc[:-1].apply(sharpe).idxmax())

years = strategy.index.year
chosen = {year: best_window(strategy[years < year]) for year in range(2016, 2024)}
walk_forward = pd.concat([strategy.loc[years == year, window] for year, window in chosen.items()])
print(pd.Series(chosen, name="window"))
2016     50
2017    160
2018    140
2019    140
2020     30
2021     40
2022     50
2023    120
Name: window, dtype: int64

The window changes from 140 days in 2019 to 30 days in 2020, because a different window happened to lead in each training sample.

How does the walk-forward result compare with hindsight?

The walk-forward test earns a Sharpe ratio of −0.20 on 2016 to 2023, and the best single window chosen after seeing those years earns 0.31. The hindsight result uses the test years both to choose the window and to measure it, so it overstates what the rule could have earned.

.loc["2016":] keeps the rows from 2016, and .apply(sharpe).max() gives the best window’s Sharpe ratio on those rows.

The following box prints both Sharpe ratios.

print(round(sharpe(walk_forward), 2), round(strategy.loc["2016":].apply(sharpe).max(), 2))
-0.2 0.31

Your turn

Choose each year’s window on the two years before it only and print the walk-forward Sharpe ratio. You should see −0.36.

years >= year - 2 keeps the two years before the test year, and & combines it with years < year.

recent = {year: best_window(strategy[(years >= year - 2) & (years < year)]) for year in range(2016, 2024)}
recent_returns = pd.concat([strategy.loc[years == year, window] for year, window in recent.items()])
print(round(sharpe(recent_returns), 2))
-0.36