Skip to content

Overfitting checks for a parameter sweep

A sweep over N parameter combinations always has a winner. These three statistics say what that winner is worth: whether the selection itself overfits, whether the winning Sharpe ratio clears the bar that N unskilled trials set, and whether the winning point sits on a plateau or on a spike. They work on the sweep's own outputs, the per-period returns and the metric per combination, and need nothing from the engine.

Probability of backtest overfitting

pbo_cscv(returns, num_blocks=16) takes the per-period returns of every combination as a (trials, periods) array and runs combinatorially symmetric cross-validation: the periods are cut into num_blocks blocks, every way of choosing half of the blocks is an in-sample set with the other half out of sample, and on each split the in-sample best combination is ranked among all combinations out of sample. The relative rank is r / (N + 1), its logit log(w / (1 - w)), and pbo is the fraction of splits whose logit is below zero: the in-sample winner did worse than the out-of-sample median. A sweep whose winner is a fit to the sample answers around 0.5 or more; a real edge answers near 0.

The result also carries splits (there are 12 870 with 16 blocks), mean_oos_rank and mean_logit. Nothing is sampled, so the same inputs give the same answer. The inputs cannot be split with fewer than two trials, an odd block count, or fewer periods than blocks, and pbo is then NaN.

Reference: Bailey, Borwein, López de Prado, Zhu (2017), "The Probability of Backtest Overfitting", Journal of Computational Finance 20(4).

Deflated Sharpe ratio

deflated_sharpe(returns, trial_sharpes=None) takes the selected combination's per-period returns and the per-period Sharpe ratio of every trial the selection ran over. The expected maximum Sharpe ratio of that many unskilled trials, expected_max_sharpe, follows from the number of trials and the variance of their Sharpe ratios; dsr is the probability that the selected strategy's true Sharpe ratio is above it, with the sample length, the skewness and the kurtosis of the returns taken into account. Without trial_sharpes there is no selection, the expected maximum is 0, and dsr is the probabilistic Sharpe ratio against zero.

The function returns sharpe (per period, mean over sample standard deviation), skewness, kurtosis (3 for normal returns), expected_max_sharpe and dsr. Annualise nothing before calling it: every quantity is per period. Fewer than two periods, or a zero return variance, answer NaN throughout.

References: Bailey, López de Prado (2014), "The Deflated Sharpe Ratio", Journal of Portfolio Management 40(5); Bailey, López de Prado (2012), "The Sharpe Ratio Efficient Frontier", Journal of Risk 15(2).

Neighbourhood of a grid point

grid_neighborhood(values, radius=1) takes the metric of every combination as an n-dimensional array over the parameter grid and returns, for every cell, neighbor_mean (the metric averaged over the cells whose index differs by at most radius on every axis, the cell itself excluded, NaN cells skipped) and neighbor_count. Both have the shape of values. A corner of a two-dimensional grid has three neighbours at radius 1, an interior point eight; a cell with none gets NaN.

The decision is the caller's. A winner whose neighbourhood mean is close to its own value sits on a plateau, and a small move in either parameter keeps most of the edge; a winner far above its neighbours is a spike, which is what a fit to noise looks like on a grid.

The three together

"""
Three questions to ask a parameter sweep before trusting its winner.

The sweep here is synthetic so the script runs anywhere: 24 parameter
combinations laid out on a 4 x 6 grid, each with 512 periods of returns.
One region of the grid carries a real edge, the rest is noise.

Usage:
    cd /path/to/lrvx
    PYTHONPATH=build/python python3 docs/examples/python_robustness_statistics.py
"""

import numpy as np

import lrvx

rng = np.random.default_rng(2026)
SHAPE = (4, 6)
PERIODS = 512

# Per-period returns of every combination, row-major over the grid: trial
# index = row * 6 + col. The edge sits in rows 1-2, columns 2-4.
returns = rng.standard_normal((SHAPE[0] * SHAPE[1], PERIODS)) * 0.01
for row in (1, 2):
    for col in (2, 3, 4):
        returns[row * SHAPE[1] + col] += 0.0015

sharpes = returns.mean(axis=1) / returns.std(axis=1, ddof=1)
best = int(np.argmax(sharpes))

# 1. Is the winner of the sweep a fit to the sample? PBO is the fraction of
#    in-sample / out-of-sample splits where the in-sample best lands below
#    the out-of-sample median. Near 0.5 means the selection is a coin toss.
pbo = lrvx.pbo_cscv(returns, num_blocks=8)
print(f"pbo={pbo['pbo']:.3f} over {pbo['splits']} splits, "
      f"mean out-of-sample rank of the in-sample best {pbo['mean_oos_rank']:.2f}")

# 2. Is the winner's Sharpe ratio above what the best of 24 unskilled trials
#    would show? DSR is the probability that it is, after skewness, kurtosis
#    and sample length.
dsr = lrvx.deflated_sharpe(returns[best], trial_sharpes=sharpes)
print(f"best trial {best}: sharpe={dsr['sharpe']:.3f} per period, "
      f"expected max of {len(sharpes)} unskilled trials {dsr['expected_max_sharpe']:.3f}, "
      f"dsr={dsr['dsr']:.3f}")

# 3. Does the winner sit on a plateau or on a spike? The neighbourhood mean
#    of a grid point is the metric averaged over its adjacent cells.
grid = lrvx.grid_neighborhood(sharpes.reshape(SHAPE), radius=1)
row, col = divmod(best, SHAPE[1])
own = sharpes[best]
around = grid["neighbor_mean"][row, col]
print(f"best point ({row}, {col}): own sharpe {own:.3f}, "
      f"neighbours ({grid['neighbor_count'][row, col]}) average {around:.3f}")
for r in range(SHAPE[0]):
    print("  " + " ".join(f"{sharpes[r * SHAPE[1] + c]:+.2f}" for c in range(SHAPE[1])))

In C++ the same functions are lrvx::stats::pboCscv, lrvx::stats::deflatedSharpeRatio and lrvx::stats::gridNeighborhood in lrvx/stats/; in Node they are pboCscv, deflatedSharpe and gridNeighborhood.

See also