Simulating and optimizing an algorithmic trading strategy with VectorBT

We implement and backtest an algorithmic trading strategy using VectorBT – a vectorized quantitative analysis library. We limit overfitting via clustering and heuristics, with optional smoothing. We use walk forward optimization to determine the strategy’s robustness to evolving market conditions and evaluate it out-of-sample end-to-end. Compared to buy-and-hold, the resulting returns are smaller but more consistent.

algorithmic-trading
python
finance
Author

Victor Semionov

Published

November 12, 2026

Introduction

Algorithmic trading is the automatic execution of orders by computer programs using predefined strategies. Algorithmic trading systems consist of the following key components:

  1. A data source feeds the system prices over time.
  2. A technical analysis module aggregates prices into technical indicators.
  3. A trading strategy (algorithm) generates position entry and exit signals.
  4. A risk engine filters out orders exceeding acceptable limits.
  5. An exchange receives the orders (either directly from the system or via an intermediate broker) and executes them.

flowchart TB

data@{ shape: h-cyl, label: "Data source"}
subgraph system[Trading system]
  direction LR
  analysis[[Technical analysis]]
  strategy[Trading strategy]
  risk{Risk engine}
  analysis -- indicators --> strategy
  strategy -- signals --> risk
end
exchange([Broker / exchange])

data -- prices --> system
system -- orders --> exchange

Numerous trading strategies exist. Here, we use a simple moving average (MA) crossover as an indication of price trend (direction) reversal. That is, we enter (buy) long positions when a short-term (fast) MA crosses over a long-term (slow) MA, and we exit (sell) when the fast MA crosses below the slow MA. The strategy has two parameters – the sizes of the fast and slow MA windows. A typical example is 50 and 200 days, respectively, but the optimal values depend on market conditions and are not known in advance.

We answer the following questions:

  • How well does the strategy perform in different time periods?
  • How does it perform compared to the market, and to a random strategy?
  • How much does the performance depend on parameters near its maximum, and how much do the optimal parameters vary with time?
  • How well does the strategy perform in an unknown future with periodic optimization from recent data?

Setup

To evaluate the strategy, we backtest it, i.e. simulate its outcome using historical price data. We use VectorBT – a modern Python quantitative analysis library that enables fast simulations of thousands of parameter combinations across many assets. Compared to established alternatives such as backtrader, VectorBT offers vectorized computation, operating on pandas dataframes and NumPy arrays, and is accelerated by Numba and Rust. VectorBT implements a few technical indicators, and easily integrates with libraries such as TA-Lib, which implement many others. It supports various order options, such as short positions, (trailing) stop losses, slippage, fees, numerous portfolio metrics, visualizations, and more.

One downside of using VectorBT is that a production system needs a separate implementation of its strategy, with potential bugs that backtesting cannot reveal. Additionally, the library is considered difficult to use – the usage documentation is small compared to the API, has few examples, and the solutions of some tasks are not obvious.

In the following cells, we import the necessary libraries, configure VectorBT, and define the main configuration of the simulation.

Code
import math, os, io, warnings
from typing import Literal, Callable, overload, cast

import numpy as np
import pandas as pd
import vectorbt as vbt
import diskcache
import httpx
import plotly
from sklearn.cluster import DBSCAN
from scipy import spatial, ndimage
from IPython.display import display
from dotenv import load_dotenv

from alpaca.data import BarSet
from alpaca.data.historical.stock import StockHistoricalDataClient
from alpaca.data.requests import StockBarsRequest
from alpaca.data.timeframe import TimeFrame


load_dotenv()

layout = vbt.settings[ 'plotting' ]['layout']
layout['width'], layout['height'] = 800, 520
plotly.io.templates['vbt_dark'].layout.update(
    paper_bgcolor='#202026',
    plot_bgcolor='#282830',
    xaxis_gridcolor='#404050',
    yaxis_gridcolor='#404050',
)


def format_time(t: pd.Timestamp) -> str:
    return pd.Series([t]).astype('str')[0]


def multiplot(plotter: Callable[[str], vbt.FigureWidget], height: int = layout['height']):
    is_quarto = 'QUARTO_PROJECT_ROOT' in os.environ
    templates = ['vbt_light', 'vbt_dark'] if is_quarto else ['vbt_dark']

    old_height, layout['height'] = layout['height'], height
    try:
        for template in templates:
            fig = plotter(template)
            fig.update_layout(width=layout['width'] - 1)  # no scroll bars
            fig.show()
    finally:
        layout['height'] = old_height


@overload
def compute_stats(pf: vbt.Portfolio, group_by: list[str] | Literal[False]) -> pd.DataFrame: ...
@overload
def compute_stats(pf: vbt.Portfolio, group_by: Literal[True]) -> pd.Series: ...
DAYS_IN_MONTH = 21

vbt.settings['returns']['year_freq'] = f'{12 * DAYS_IN_MONTH} days'
# simulation scope
archive_timestamp = '20261112061436'
universe_size = 100
end_date = '2026-11-12'
max_nulls = 0.05

# data splitting
n_splits = 10
train_size = 12 * DAYS_IN_MONTH
val_size = 6 * DAYS_IN_MONTH

# optimization
is_realtime = False
main_metric = 'sortino_ratio'
windows = np.arange(5, 155, 5)
ref_params = (40, 150)

# parameter selection
conv_sigma = 0  # disabled
min_trades = 100
params_frac = 0.05
cluster_tol = 0.3
min_samples = 3
size_power = 1

Data preparation

We use data from the Alpaca API, due to its reliability compared to anonymously accessible alternatives such as Yahoo Finance. The universe, on which we perform simulations, is a random sample of US stocks from the S&P 500 index. A more careful approach would avoid survivorship bias by including stocks removed from that index, but is outside the scope of this post.

First, we compute the start date of the data to request, given its end date, duration, and other parameters. We add a small margin to compensate for stock exchange holidays.

lead_size = max(windows) - is_realtime  # leading buffer for rolling indicator windows
data_size = lead_size + train_size + n_splits * val_size
offset = pd.offsets.BDay(math.ceil(data_size * 1.05))  # margin
start_date = format_time(pd.Timestamp(end_date) - offset)

We implement price data retrieval using the Alpaca Python client library. The list of S&P 500 symbols is obtained from an archived Wikipedia page. We cache all data to speed up execution.

cache = diskcache.Cache('cache')


@cache.memoize()
def get_snp500(timestamp: str) -> list[str]:
    url = 'https://en.wikipedia.org/wiki/List_of_S&P_500_companies'

    with httpx.Client(headers={'User-Agent': 'httpx'}, timeout=30) as client:
        response = client.get(
            'https://archive.org/wayback/available',
            params={'url': url, 'timestamp': timestamp},
        )
        closest = response.raise_for_status().json()['archived_snapshots']['closest']

        response = client.get(f'https://web.archive.org/web/{closest['timestamp']}/{url}')
        html = response.raise_for_status().text
        table = pd.read_html(io.StringIO(html))[0]
        return table['Symbol'].sort_values().to_list()


@cache.memoize()
def download_data(symbols: list[str], start_date: str, end_date: str) -> pd.DataFrame:
    api_key, secret_key = os.environ['ALPACA_API_KEY'], os.environ['ALPACA_SECRET_KEY']
    client = StockHistoricalDataClient(api_key=api_key, secret_key=secret_key)
    request = StockBarsRequest(
        symbol_or_symbols=symbols,
        start=pd.Timestamp(start_date),
        end=pd.Timestamp(end_date),
        timeframe=TimeFrame.Day,
        adjustment='all',
    )

    data = cast(BarSet, client.get_stock_bars(request)).df
    data = cast(pd.DataFrame, data.unstack('symbol')).swaplevel(0, 1, axis=1).sort_index(axis=1)
    data = data.rename_axis(index={'timestamp': 'date'}, columns=['symbol', 'price'])
    data.index = cast(pd.DatetimeIndex, data.index).normalize().tz_localize(None)
    return data

We fetch the dataset, trim it to the exact required size, discard symbols with intolerable amounts of missing values, and sample the remainder. We select the closing price for use in simulations.

snp500 = get_snp500(archive_timestamp)
data = download_data(snp500, start_date, end_date)
data = data.tail(data_size)
assert len(data) == data_size

close_price = lambda df: df.xs('close', axis=1, level='price')
null_frac = close_price(data).isna().mean()
data = data[null_frac.index[null_frac <= max_nulls]]

available_symbols = sorted(data.columns.unique(0))
assert len(available_symbols) > 450
n_syms = universe_size or len(available_symbols)
universe = pd.Series(available_symbols).sample(n_syms, random_state=0).sort_values().to_list()
data = data[universe]

price = close_price(data)

The State Street SPDR S&P 500 ETF Trust (SPY) tracks the same stocks as the index we sample. For an overview of the market behavior in the selected time period, we visualize the evolution of SPY’s price and trade volume.

spy = download_data([sym := 'SPY'], format_time(data.index[0]), format_time(data.index[-1]))[sym]
multiplot(lambda t: spy.vbt.ohlc.plot(
    title=sym,
    xaxis2=dict(title=spy.index.name.capitalize()),
    yaxis1=dict(title='Price'),
    yaxis2=dict(title='Shares'),
    template=t,
))

Overall, the price increases, but it also has a prolonged period of steady decline in 2022 and sharp troughs in 2023, 2025, and 2026. This choice of time frame is deliberate and allows backtesting in both bull and bear periods.

The next cell shows a preview of individual stock prices.

price.head()
symbol AAPL ADBE ADI ADM ADSK AEP AIG ALL APO BE ... UDR UPS URI VZ WFC WST WY XEL XOM YUM
date
2020-04-02 59.03 303.96 78.47 28.53 137.05 60.48 18.06 73.49 26.46 4.96 ... 24.62 70.62 92.41 37.15 23.05 152.99 12.54 48.92 30.41 58.45
2020-04-03 58.18 293.61 77.45 28.79 139.00 57.10 17.39 73.64 27.27 4.79 ... 24.37 68.32 87.52 36.78 22.21 148.73 12.14 46.85 29.51 56.01
2020-04-06 63.26 319.13 85.72 29.73 152.32 61.90 18.29 80.11 30.68 5.24 ... 27.23 72.63 99.16 38.13 24.25 158.51 13.54 49.51 30.46 62.39
2020-04-07 62.53 308.93 86.12 29.90 148.70 62.03 19.77 79.26 29.97 5.09 ... 27.55 70.52 103.72 38.31 24.36 155.41 13.69 47.96 31.04 63.14
2020-04-08 64.13 317.18 90.73 30.31 159.21 65.61 20.51 83.31 31.84 5.86 ... 30.10 74.99 107.29 38.87 25.64 161.94 15.40 50.85 33.00 66.69

5 rows × 100 columns

Walk forward optimization

We optimize the strategy’s parameters by varying them in backtesting to maximize a predefined metric. As market conditions evolve with time, so do the strategy’s optimal parameters. Ideally, their variance should be small, and the metric should depend weakly on the parameters near its maximum (the peak should be wide). To evaluate this, we split the data into multiple time periods and backtest across them.

More importantly, we perform walk forward optimization by backtesting across sequential out-of-sample time windows. That is, we optimize the parameters across a set of training windows, and evaluate the metric on immediately following validation windows forming a contiguous span. This is analogous to cross-validation in machine learning and time series forecasting, and mimics how a real-world system operates by periodically updating parameters from recent data up to the current (cutoff) time.

split_kwargs = dict(
    n=n_splits,
    window_len=(train_size + val_size),
    set_lens=(val_size,),
    left_to_right=False,
)

multiplot(
    lambda t: price.iloc[lead_size:].vbt.rolling_split(  # exclude leading buffer
        **split_kwargs,
        plot=True,
        heatmap_kwargs=dict(
            title='Data splits',
            xaxis1=dict(title=price.index.name.capitalize()),
            yaxis1=dict(title='Split'),
            template=t,
        ),
    )
    .for_each_trace(lambda tr: tr.update(name={'0': 'Training', '1': 'Validation'}[tr.name]))
)

Strategy evaluation

Various risk-adjusted portfolio performance metrics exist, but here we use the Sortino ratio. Unlike the Sharpe ratio, it only penalizes downside volatility.

First, as per our strategy, we compute the moving averages for each stock price over time, for a triangular matrix of slow and fast window size combinations. We then generate the entry and exit signals at MA crossovers.

ind_price = price
if not is_realtime:
    # By default, vectorbt executes orders priced at the signal's time.
    # This simulates a real-time system with no delay between analysis and execution.
    # The below line optionally introduces this delay to avoid lookahead bias.
    ind_price = ind_price.shift()

fast_ma, slow_ma = [
    ma.ma
    for ma in vbt.MA.run_combs(ind_price, window=windows, short_names=['fast', 'slow'])
]

entries = fast_ma.vbt.crossed_above(slow_ma)
exits = fast_ma.vbt.crossed_below(slow_ma)

entries.head(2)
fast_window 5 ... 145
slow_window 10 ... 150
symbol AAPL ADBE ADI ADM ADSK AEP AIG ALL APO BE ... UDR UPS URI VZ WFC WST WY XEL XOM YUM
date
2020-04-02 False False False False False False False False False False ... False False False False False False False False False False
2020-04-03 False False False False False False False False False False ... False False False False False False False False False False

2 rows × 43500 columns

Note that the indicators and signals vary across four variables – time, symbol, and the two window sizes. VectorBT handles this by using multi-level columns (MultiIndex) for the output dataframes.

Next, we split the prices and signals, as per the shown scheme. It is important to do this after indicators and signals are computed – otherwise, the latter would contain leading missing values in each split.

def split(df: pd.DataFrame):
    df = df.iloc[lead_size:]  # exclude leading buffer
    sets = df.vbt.rolling_split(**split_kwargs)
    return [v for s in sets for v in s]


train_price, _, val_price, val_times = split(price)
train_entries, _, val_entries, _ = split(entries)
train_exits, _, val_exits, _ = split(exits)

train_entries.head(2)
split_idx 0 ... 9
fast_window 5 ... 145
slow_window 10 ... 150
symbol AAPL ADBE ADI ADM ADSK AEP AIG ALL APO BE ... UDR UPS URI VZ WFC WST WY XEL XOM YUM
0 False False False False False False False False False False ... False False False False False False False False False False
1 False False False False False False True True False False ... False False False False False False False False False False

2 rows × 435000 columns

For each input dataframe, this produces two outputs (for the training and validation sets). The outputs have as many rows as the split size, and as many columns as the inputs multiplied by the number of splits. The split position is indicated by an additional column level.

For each set, we create a VectorBT portfolio and simulate trades according to the signals.

train_pf = vbt.Portfolio.from_signals(train_price, train_entries, train_exits, freq='D')
val_pf = vbt.Portfolio.from_signals(val_price, val_entries, val_exits, freq='D')

params = cast(list[str], train_pf.wrapper.columns.names[1:-1])
all_params = ['split_idx', *params]

To better understand the strategy’s risk, relative performance, and sensitivity to the market, besides the main metric, we compute various others such as win rate, exposure, drawdown, returns, alpha, and beta.

metrics = [main_metric, 'max_gross_exposure', 'max_dd', 'total_trades', 'win_rate']
returns_metrics = ['ann_return', 'alpha', 'beta']


def compute_stats(pf: vbt.Portfolio, group_by: list[str] | bool) -> pd.DataFrame | pd.Series:
    return pd.concat(
        [
            pf.stats(metrics=metrics, group_by=group_by, agg_func=None),
            pf.returns_stats(metrics=returns_metrics, group_by=group_by, agg_func=None),
        ],
        axis=(1 if isinstance(group_by, list) else 0),
    )


train_stats = compute_stats(train_pf, all_params)
val_stats = compute_stats(val_pf, all_params)

metric_names = dict(zip(metrics + returns_metrics, train_stats.columns))
main_metric_name = metric_names[main_metric]

Parameter selection

Obtaining a smooth and reliable estimate of the performance metric across the parameter space requires simulating large numbers of trades across a diverse universe. However, this contradicts the aim to backtest for current market conditions with recent data for a narrow universe. Additionally, limited computer memory and simulation time may require using small data samples. As a result, the performance across the parameter space can contain significant noise. A few lucky trades can produce a “hot spot” for an otherwise suboptimal parameter combination. Naively selecting the parameters with the highest performance introduces the risk of overfitting. Instead, we aim to use the middle of a wide peak with near-best performance. We smooth the metric with a Gaussian filter, select the top fraction of parameters, and use the medoid of their DBSCAN cluster with the highest product of member count and average performance.

Note

Smoothing is disabled in the configuration, as it reduces the end-to-end performance for this dataset. However, we still present it as an option for other experiments.

def smooth_surface(s: pd.Series, sigma: float) -> pd.Series:
    grid = s.unstack(s.index.names[1])
    v = grid.to_numpy()
    valid = np.isfinite(v)

    # normalized convolution: ignore missing cells instead of treating them as 0
    num = ndimage.gaussian_filter(np.where(valid, v, 0), sigma, mode='constant')
    den = ndimage.gaussian_filter(valid.astype(np.float64), sigma, mode='constant')
    out = np.where(valid, num / den, np.nan)

    smoothed = cast(pd.Series, pd.DataFrame(out, index=grid.index, columns=grid.columns).stack())
    return smoothed.reindex(s.index)


def select_params(stats: pd.DataFrame, return_top: bool = False) -> tuple | pd.Series:
    split_idx = stats.index.get_level_values('split_idx')[0]
    stats = stats.droplevel('split_idx')
    objective = stats[main_metric_name]

    smoothed = smooth_surface(objective, conv_sigma)

    # select the top parameter combinations
    top = smoothed[smoothed >= smoothed.quantile(1 - params_frac)]
    if (stats.loc[top.index, metric_names['total_trades']] < min_trades).any():
        warnings.warn('Total trades below required minimum')
    if return_top:
        return top

    # work in log space, since windows are ratio-like
    X = np.log(top.index.to_frame(index=False).to_numpy())

    # cluster the parameters
    labels = DBSCAN(
        eps=np.log(1 + cluster_tol),  # relative max neighbor distance
        min_samples=min_samples,
        metric='chebyshev',  # max per-parameter distance
    ).fit_predict(X)

    # select a cluster based on average score and size
    cluster_stats = top.groupby(labels).agg(['mean', 'size']).drop(-1, errors='ignore')
    cluster_scores = cluster_stats['mean'] * cluster_stats['size'] ** size_power
    if len(cluster_scores) > 0:
        mask = labels == cluster_scores.idxmax()
        top, X = top[mask], X[mask]

    # find the cluster's medoid
    i = spatial.distance.cdist(X, X).sum(axis=1).argmin()
    return (split_idx, *top.index[i.item()])
sel_params = train_stats.groupby('split_idx').apply(cast(Callable, select_params))
train_stats.loc[sel_params].index.to_frame().set_index('split_idx')
fast_window slow_window
split_idx
0 5 130
1 100 115
2 95 125
3 110 130
4 55 70
5 25 50
6 30 70
7 25 55
8 15 65
9 10 135

The optimal parameters vary significantly across splits.

Results and analysis

The main metric as a function of the strategy’s parameters:

Code
_PROPS_BOLD = 'font-weight: bold;'


def format_stats(df: pd.DataFrame, highlight: bool = False):
    metric_cols = lambda *metrics: [metric_names[m] for m in metrics]
    round0 = metric_cols('total_trades')
    round1 = metric_cols('max_gross_exposure', 'max_dd', 'win_rate', 'ann_return')
    round2 = metric_cols(main_metric)
    round3 = metric_cols('alpha', 'beta')
    hl_max = metric_cols(main_metric, 'win_rate', 'ann_return', 'alpha')
    hl_min = metric_cols('max_dd', 'beta')

    styler = (
        df.style
        .format(subset=round0, precision=0)
        .format(subset=round1, precision=1)
        .format(subset=round2, precision=2)
        .format(subset=round3, precision=3)
    )
    styler = (
        styler
        .highlight_max(subset=hl_max, props=_PROPS_BOLD)
        .highlight_min(subset=hl_min, props=_PROPS_BOLD)
    ) if highlight else styler
    return styler


def format_desc(desc: pd.DataFrame):
    return (
        desc.style.format(precision=3)
        .highlight_max(subset=list(set(desc) - {'std'}), props=_PROPS_BOLD)
        .highlight_min(subset=['std'], props=_PROPS_BOLD)
    )


def get_plot_metric(train: pd.DataFrame, val: pd.DataFrame):
    panels = [('Training', train), ('Validation', val)]
    n_panels = len(panels)

    # top params per split from training stats
    top_params = train_stats.groupby('split_idx').apply(
        cast(Callable, lambda s: select_params(s, return_top=True))
    )

    # combined value range across all splits and both panels
    all_vals = pd.concat([train[main_metric_name], val[main_metric_name]])
    all_vals = all_vals.replace([np.inf, -np.inf], np.nan)
    lo, hi = all_vals.min(), all_vals.max()

    def plot_metric(t: str):
        fig = cast(vbt.FigureWidget, vbt.make_subplots(
            rows=n_panels, cols=1, shared_xaxes=True,
            vertical_spacing=0.05,
            subplot_titles=[name for name, _ in panels],
        ))
        owners = []  # split position that each trace belongs to, for the slider

        for i in range(n_splits):
            top_p1, top_p2 = [top_params[i].index.get_level_values(j) for j in range(2)]
            sel_p1, sel_p2 = sel_params[i][1:]

            for row, (_, stats) in enumerate(panels, start=1):
                at = dict(row=row, col=1)
                is_upper = row == 1
                is_start = i == 0

                # heatmap, drawn on the shared color axis
                stats[main_metric_name][i].vbt.heatmap(
                    x_level=params[0], y_level=params[1], symmetric=True,
                    fig=fig, add_trace_kwargs=at,
                    trace_kwargs=dict(visible=is_start, coloraxis='coloraxis'),
                    template=t,
                )

                # top params
                vbt.plotting.Scatter(
                    data=top_p2, x_labels=top_p1,
                    trace_names=['Filtered top'],
                    trace_kwargs=dict(
                        mode='markers', marker=dict(size=4, color='black'),
                        legendgroup='top', showlegend=is_upper, visible=is_start,
                    ),
                    add_trace_kwargs=at, fig=fig,
                )

                # selected params
                vbt.plotting.Scatter(
                    data=[sel_p2], x_labels=[sel_p1],
                    trace_names=['Selected'],
                    trace_kwargs=dict(
                        mode='markers',
                        marker=dict(
                            symbol='x', size=10, color='white',
                            line=dict(width=2, color='black'),
                        ),
                        legendgroup='selected', showlegend=is_upper, visible=is_start,
                    ),
                    add_trace_kwargs=at, fig=fig,
                )

                owners += [i] * (len(fig.data) - len(owners))

        # one shared colorbar spanning the combined range
        hm = fig.data[0]
        fig.update_layout(coloraxis=dict(
            cmin=lo, cmax=hi, colorscale=hm.colorscale,
        ))

        # one slider toggling every trace that belongs to the chosen split
        fig.update_layout(
            title=main_metric_name,
            sliders=[dict(
                currentvalue=dict(prefix='split_idx: '),
                steps=[dict(
                    method='update', label=str(i),
                    args=[dict(visible=[o == i for o in owners])],
                ) for i in range(n_splits)],
            )],
        )

        # pin axes to the heatmap extent so edge markers don't expand the range
        for axis, vals in [('x', hm.x), ('y', hm.y)]:
            half = (vals[1] - vals[0]) / 2
            rng = min(vals) - half, max(vals) + half
            fig.update_xaxes(range=rng) if axis == 'x' else fig.update_yaxes(range=rng)

        # x axis title only on the bottom subplot
        fig.update_xaxes(title_text=None, row=1, col=1)
        fig.update_xaxes(title_text=params[0], row=n_panels, col=1)
        for row in range(1, n_panels + 1):
            fig.update_yaxes(title_text=params[1], row=row, col=1)
        return fig

    return plot_metric
plot_metric = get_plot_metric(train_stats, val_stats)
multiplot(plot_metric, height=layout['width'])

Unfortunately, most peaks are not wide enough to accommodate the variance of the selected parameters. As a result, the values selected in training are often suboptimal in validation, leading to reduced performance.

Evolution of the main metric for the selected parameters:

sel_train_stats = train_stats.loc[sel_params].droplevel([1, 2])
sel_val_stats = val_stats.loc[sel_params].droplevel([1, 2])

evals = pd.concat([
    sel_train_stats[main_metric_name].rename(f'Training'),
    sel_val_stats[main_metric_name].rename(f'Validation'),
], axis=1)

multiplot(
    lambda t: evals.vbt.plot(
        title='Cross-validation',
        xaxis1=dict(title='Split'),
        yaxis1=dict(title=main_metric_name),
        template=t,
    )
    .update_xaxes(type='category')
)

On average, the validation performance is lower than the training performance, and varies more. The returns are negative in the bear market periods.

Metric means and dispersion:

evals.describe().T[['mean', 'std']].round(2)
mean std
Training 2.15 1.53
Validation 1.26 2.34

Detailed metrics per split:

print('Training metrics:')
display(format_stats(sel_train_stats))
print('Validation metrics:')
display(format_stats(sel_val_stats))
Training metrics:
  Sortino Ratio Max Gross Exposure [%] Max Drawdown [%] Total Trades Win Rate [%] Annualized Return [%] Alpha Beta
split_idx                
0 4.46 73.2 2.7 201 40.8 23.3 0.005 0.472
1 0.68 60.1 4.0 145 43.4 2.8 0.011 0.342
2 1.02 44.0 5.6 125 44.8 4.3 0.064 0.257
3 0.76 88.8 5.5 171 39.6 4.0 0.028 0.254
4 0.70 91.2 6.8 248 41.8 4.0 -0.013 0.439
5 2.76 91.9 5.1 264 46.1 14.2 0.016 0.472
6 3.76 83.4 4.9 213 48.2 21.8 -0.006 0.627
7 0.79 74.8 7.9 234 45.1 4.0 -0.004 0.335
8 2.72 83.9 5.2 239 32.5 14.4 0.075 0.346
9 3.87 72.4 6.7 203 29.6 28.7 0.026 0.652
Validation metrics:
  Sortino Ratio Max Gross Exposure [%] Max Drawdown [%] Total Trades Win Rate [%] Annualized Return [%] Alpha Beta
split_idx                
0 -1.14 50.5 4.0 135 7.8 -4.7 -0.029 0.236
1 2.51 39.5 2.6 77 49.0 6.3 0.071 0.122
2 -0.41 67.5 4.9 89 25.0 -2.5 -0.069 0.312
3 -0.65 51.4 5.0 85 32.4 -2.2 -0.047 0.277
4 2.36 81.7 5.2 130 39.1 12.9 -0.079 0.545
5 4.01 75.1 3.9 154 43.8 16.3 0.017 0.497
6 -1.90 41.4 6.4 76 13.2 -7.8 -0.076 0.208
7 5.19 71.7 2.3 142 46.1 27.6 0.062 0.632
8 2.18 58.3 4.4 134 24.4 8.1 0.001 0.346
9 0.47 53.0 2.9 107 8.8 1.4 -0.037 0.350

The lower validation performance is likely caused by unforeseen changes in the market and the strategy’s sensitivity to them. Perhaps it could be improved by using shorter training windows. However, this would require increasing the universe size by the same factor to compute stable metrics, raising the computational difficulty.

End-to-end performance

So far, we evaluated the strategy’s performance only piecewise, per split. Next, we perform an end-to-end simulation of the combined validation time span with a single uninterrupted portfolio.

We start by assembling (stitching) the indicators, obtained using the different parameters selected per split. It is important to assemble indicators and not signals, as the latter approach could lead to missed crossover events due to parameter changes at split boundaries. As an ablation study, we also apply the parameters that naively maximize the training metric, as well as reference parameters (40, 150), a scaled-down version of the classic 50-200 example (200 is outside the searched window range).

def assemble_walk_forward(get_params: Callable[[int], tuple]):
    wf_fast_ma, wf_slow_ma = [
        pd.concat([
            ma.set_axis(entries.columns, axis=1).loc[val_times[i], get_params(i)]
            for i in range(n_splits)
        ])
        for ma in [fast_ma, slow_ma]
    ]

    wf_entries = wf_fast_ma.vbt.crossed_above(wf_slow_ma)
    wf_exits = wf_fast_ma.vbt.crossed_below(wf_slow_ma)
    return wf_entries, wf_exits


wf_price = price[(lead_size + train_size):]

wf_entries, wf_exits = assemble_walk_forward(lambda i: sel_params[i][1:])

top1_params = train_stats[main_metric_name].groupby('split_idx').idxmax()
wf_top1_entries, wf_top1_exits = assemble_walk_forward(lambda i: top1_params[i][1:])

ref_entries, ref_exits = assemble_walk_forward(lambda i: ref_params)

Next, we simulate the resulting portfolios. For comparison, we include a buy-and-hold strategy, as well as one of random signals.

wf_pf = vbt.Portfolio.from_signals(wf_price, wf_entries, wf_exits, freq='D')
wf_top1_pf = vbt.Portfolio.from_signals(wf_price, wf_top1_entries, wf_top1_exits, freq='D')
ref_pf = vbt.Portfolio.from_signals(wf_price, ref_entries, ref_exits, freq='D')

wf_trades = cast(vbt.portfolio.trades.Trades, wf_pf.trades)
n_trades = wf_trades.records.shape[0] / wf_price.shape[1]  # avg wf trades per symbol
rand_pf = vbt.Portfolio.from_random_signals(wf_price, n=n_trades, seed=0, freq='D')
hold_pf = vbt.Portfolio.from_holding(wf_price, freq='D')

Portfolio metrics:

format_stats(pd.concat([
    compute_stats(wf_pf, True).rename('Walk forward'),
    compute_stats(wf_top1_pf, True).rename('WF top1'),
    compute_stats(ref_pf, True).rename('Reference'),
    compute_stats(rand_pf, True).rename('Random'),
    compute_stats(hold_pf, True).rename('Holding'),
], axis=1).T, highlight=True)
  Sortino Ratio Max Gross Exposure [%] Max Drawdown [%] Total Trades Win Rate [%] Annualized Return [%] Alpha Beta
Walk forward 1.05 93.3 11.8 1202 42.4 7.5 0.007 0.482
WF top1 0.77 93.1 16.4 2281 44.9 6.1 -0.015 0.555
Reference 0.97 91.7 12.3 534 36.0 7.2 -0.001 0.526
Random 1.13 64.2 9.6 1200 54.6 6.2 0.006 0.393
Holding 1.16 100.0 19.4 100 nan 14.0 0.000 1.000

Returns per symbol:

returns = pd.DataFrame({
    name: pf.returns_acc.annualized().to_numpy().reshape(-1)  # equiv pf.annualized_return()
    for name, pf in [
        ('Walk forward', wf_pf),
        ('WF top1', wf_top1_pf),
        ('Reference', ref_pf),
        ('Random', rand_pf),
        ('Holding', hold_pf),
    ]
})

multiplot(lambda t: returns.vbt.boxplot(
    title='Returns per symbol',
    yaxis1=dict(title='Annualized return', range=[-0.3, 0.5]),
    template=t,
))

Returns summary:

format_desc(returns.describe().drop('count').T)
  mean std min 25% 50% 75% max
Walk forward 0.044 0.121 -0.200 -0.036 0.006 0.107 0.606
WF top1 0.029 0.122 -0.190 -0.051 -0.001 0.098 0.489
Reference 0.038 0.127 -0.171 -0.052 0.011 0.101 0.542
Random 0.044 0.095 -0.168 -0.014 0.040 0.078 0.350
Holding 0.094 0.156 -0.249 -0.008 0.079 0.175 0.630
TipWhy are the means less than the portfolios’ annualized returns?

Because annualized returns are non-linear. They are defined as:

annualized\_return = (1 + total\_return)^{252 / n\_days} - 1

Since the simulated time span is more than a year, the function is concave. The portfolios’ annualized returns are computed from the means of their per-stock total returns. Due to Jensen’s inequality:

annualized(mean(total\_return)) \ge mean(annualized(total\_return))

Results for the stock with the median Sortino ratio:

metric = wf_pf.returns_stats(metrics=[main_metric], agg_func=None)[main_metric_name]
median_symbol = (metric - metric.median()).abs().idxmin()

multiplot(
    lambda t: (
        cast(vbt.FigureWidget, wf_pf[median_symbol].plot(
            title=median_symbol, template=t,
        ))
        .update_xaxes(
            title_text=wf_price.index.name.capitalize(),
            row=len(wf_pf.plots_defaults['subplots']),
        )
    ),
    height=(layout['width'] // 2),
)

Portfolio results in time:

multiplot(
    lambda t: (
        cast(vbt.FigureWidget, wf_pf.regroup(group_by=True).plot(
            subplots=['gross_exposure', 'cum_returns'],
            title='Walk forward portfolio metrics',
            template=t,
        ))
        .update_xaxes(title_text=wf_price.index.name.capitalize(), row=2)
    ),
    height=(layout['width'] // 2),
)

Compared to buy-and-hold, our strategy’s returns are smaller but more consistent. Its drawdowns are shallower. Unfortunately, the performance is not far from that of random signals.

Our strategy outperforms the version that naively selects parameters maximizing the metric. This suggests that our approach to reduce overfitting can be effective. Perhaps a real-world system would benefit even more from human oversight.