Sharpe ratio bootstrap in Python: the best of 216 strategies reached 0.72 by chance

Backtesting
Tutorial
Python
In a simulated market with no edge, the best of 216 strategies has a Sharpe ratio of 0.72, which, by searching alone, matches or beats 41% of the time.
Published

July 13, 2026

Updated

November 26, 2026

This post is more of a tutorial, and the whole purpose is to introduce the concept of bootstrapping your results. Even if you follow the book in your backtest, you may still have found the strategy by luck. Its Sharpe ratio, the average return divided by volatility, says nothing about future performance.

In a simulated market where no strategy has an edge, the best of 216 strategies has a Sharpe ratio of 0.72, and the whole search reaches 0.72 or more in 41% of the bootstrapped histories.

What bootstrapping does

So what you need to do is to generate alternative histories of the sample you have, by slicing it into blocks and drawing them with replacement, and then compute the Sharpe ratios of the strategies in each of these histories. Then you can see, within a certain percentile, whether you can reject the null hypothesis, for example, that the Sharpe ratio is zero.

Simulating the data

I simulate 40 stocks over about twelve years in a market where no strategy has an edge, so any pattern in the strategy returns is noise.

\[r_{i,t} = \beta_i\, m_t + \sigma_i\, \varepsilon_{i,t}, \qquad m_t = \sqrt{h_t}\, z_t, \qquad h_t = 0.05 \times 0.01^2 + 0.90\, h_{t-1} + 0.05\, m_{t-1}^2,\]

Every term has a mean of zero, so no strategy has an edge.

import numpy as np
import pandas as pd

def simulate_panel(n_stocks=40, n_days=3024, seed=7):
    """Daily returns for a panel of stocks, with no edge in them.

    Each stock is its own beta times a common market factor, plus noise that belongs to
    that stock alone. The factor has a mean of zero, so there is no premium to earn by
    holding the market and no strategy built on these returns has an expected edge.
    """
    random_generator = np.random.default_rng(seed)
    dates = pd.bdate_range("2014-01-02", periods=n_days)
    beta = random_generator.uniform(0.6, 1.4, n_stocks)       # exposure to the market factor
    idio_vol = random_generator.uniform(0.012, 0.022, n_stocks)   # stock-specific daily vol

    # The market factor is GARCH-like: today's variance is built out of yesterday's
    # variance and yesterday's squared return, so low-variance and high-variance periods arrive
    # in runs rather than at random. That clustering is the reason the bootstrap further
    # down resamples blocks of consecutive days instead of single days.
    market_variance = np.empty(n_days)
    market_return = np.empty(n_days)
    market_shock = random_generator.standard_normal(n_days)
    market_variance[0] = 0.01 ** 2
    for t in range(n_days):
        if t > 0:
            market_variance[t] = (0.01**2 * 0.05 + 0.90 * market_variance[t-1]
                                  + 0.05 * market_return[t-1]**2)
        market_return[t] = np.sqrt(market_variance[t]) * market_shock[t]

    stock_returns = np.zeros((n_days, n_stocks))
    for t in range(n_days):
        stock_noise = random_generator.standard_normal(n_stocks)
        stock_returns[t] = beta * market_return[t] + idio_vol * stock_noise

    tickers = [f"S{i:02d}" for i in range(n_stocks)]   # :02d pads to two digits: S00, S01
    return pd.DataFrame(stock_returns, index=dates, columns=tickers)

returns = simulate_panel()

simulated_stocks = returns.shape[1]              # shape is (rows, columns)
simulated_days = returns.shape[0]
print(f"{simulated_stocks} stocks x {simulated_days} trading days, "
      f"{returns.index[0].date()} to {returns.index[-1].date()}")
40 stocks x 3024 trading days, 2014-01-02 to 2025-08-05

Searching for the best strategy

I run 216 strategies on the same market, momentum, reversal, and low volatility with different windows, sizes, and lags. Each one buys the stocks with the highest signal and sells those with the lowest, so its daily return is

\[R_t = \overline{r}_{\text{long},t} - \overline{r}_{\text{short},t},\]

and its annualized Sharpe ratio, without trading costs, is

\[\widehat{S} = \sqrt{252}\,\frac{\overline{R}}{s_R},\]

\[\sum_{k=s}^{s+L-1} \ln(1 + r_{i,t-k}),\]

where \(L\) is the lookback window, and \(s\) is the lag.

# Three signal families times these three lists is 216 strategies.
LOOKBACKS = [21, 42, 63, 126, 189, 252]    # days the signal reads; reversal reads a third
HOLDINGS  = [3, 5, 8, 12]                  # stocks held on each side
SKIPS     = [1, 5, 21]                     # days between the signal and the trade


def long_short_weights(signal, n_hold, rebalance_day):
    """Buy the n_hold stocks with the highest signal, sell the n_hold lowest.

    Each side is equally weighted and each side sums to one, so the portfolio holds a
    dollar long for every dollar short.
    """
    # rank(axis=1) ranks the stocks against each other within each day, rather than
    # ranking each stock down its own column. A stock with no signal yet is left
    # unranked, and the notna() check keeps it out of the portfolio.
    rank_from_top = signal.rank(axis=1, ascending=False)
    rank_from_bottom = signal.rank(axis=1, ascending=True)
    long_flag = ((rank_from_top <= n_hold) & signal.notna()).astype(float)
    short_flag = ((rank_from_bottom <= n_hold) & signal.notna()).astype(float)

    # Divide by the number of names held that day, so the weights on each side
    # add to one. replace(0, np.nan) leaves a day with nothing to hold missing rather
    # than dividing by zero.
    long_count = long_flag.sum(axis=1).replace(0, np.nan)
    short_count = short_flag.sum(axis=1).replace(0, np.nan)
    long_weight = long_flag.div(long_count, axis=0)      # axis=0 divides each row by its own count
    short_weight = short_flag.div(short_count, axis=0)
    weight = long_weight - short_weight

    # where() keeps the weights on rebalance days and blanks every other day, and ffill
    # then copies the last set forward, so the same weights apply every day until the next
    # rebalance. Holding the shares instead would let the weights change with prices. Days
    # before the first rebalance stay missing, because the strategy is not active yet.
    return weight.where(rebalance_day).ffill()


def build_grid(returns):
    """One column per strategy, holding that strategy's daily portfolio return."""
    # log1p turns a simple return into a log return, which can be added across days.
    log_return = np.log1p(returns)

    # A rebalance happens on the first trading day of each calendar month. Grouping the
    # dates by year and month and asking for the first date in each group finds them.
    dates = returns.index.to_series()
    month_groups = dates.groupby([returns.index.year, returns.index.month])
    is_rebalance_day = month_groups.transform("first") == returns.index

    # The weights have one column per stock, so the day flag is repeated across the
    # columns to give a True or False for every stock on every day.
    rebalance_day = pd.DataFrame(
        np.repeat(is_rebalance_day.values[:, None], returns.shape[1], axis=1),
        index=returns.index, columns=returns.columns)

    strategy_columns = {}
    for lookback in LOOKBACKS:
        trailing_return = log_return.rolling(lookback).sum()
        trailing_vol = returns.rolling(lookback).std()
        for skip in SKIPS:
            for n_hold in HOLDINGS:
                # Reversal reads a shorter window than momentum: a third of the lookback,
                # and never fewer than five days.
                reversal_window = max(lookback // 3, 5)
                reversal_return = log_return.rolling(reversal_window).sum()
                signals = {
                    "mom": trailing_return.shift(skip),      # buy the winners
                    "rev": -reversal_return.shift(skip),     # buy the losers
                    "lvol": -trailing_vol.shift(skip),       # buy the low-volatility stocks
                }
                for signal_name, signal in signals.items():
                    weight = long_short_weights(signal, n_hold, rebalance_day)
                    # shift(1) applies today's return to yesterday's weights.
                    position_return = weight.shift(1) * returns
                    # min_count=1 keeps a day missing while no position is held yet,
                    # instead of adding nothing up and calling the answer zero.
                    daily_return = position_return.sum(axis=1, min_count=1)
                    column_name = f"{signal_name}_lb{lookback}_n{n_hold}_sk{skip}"
                    strategy_columns[column_name] = daily_return
    # Keep only days on which every strategy is active, so all 216 are judged on the
    # same sample.
    return pd.DataFrame(strategy_columns).dropna(how="any")



strategy_returns = build_grid(returns)
TRADING_DAYS_PER_YEAR = 252                # turns a daily Sharpe ratio into an annual one


def sharpe(returns_array, axis=0):
    """Annualised Sharpe ratio, with no risk-free rate deducted.

    ddof=1 asks for the sample standard deviation, which divides by n - 1 rather than n.
    """
    values = np.asarray(returns_array)
    average = values.mean(axis=axis)
    volatility = values.std(axis=axis, ddof=1)
    daily_sharpe = average / volatility
    return daily_sharpe * np.sqrt(TRADING_DAYS_PER_YEAR)

observed = pd.Series(sharpe(strategy_returns.values), index=strategy_returns.columns)
winner = observed.idxmax()                       # idxmax gives the label of the highest value
winner_sharpe = observed.loc[winner]             # .loc looks up the value with that label

print(f"{strategy_returns.shape[1]} candidates over {strategy_returns.shape[0]} common days")
print(f"grid Sharpe   min {observed.min():.2f} | median {observed.median():.2f} | "
      f"90th {observed.quantile(0.90):.2f} | max {observed.max():.2f}")
print(f"winner        {winner}   Sharpe {winner_sharpe:.2f}")
216 candidates over 2741 common days
grid Sharpe   min -0.68 | median 0.08 | 90th 0.45 | max 0.72
winner        rev_lb21_n3_sk1   Sharpe 0.72

The Sharpe ratios run from −0.68 to 0.72, and the best is a reversal strategy on seven days of past returns, with three stocks on each side, at 0.72 over nearly eleven years. Past returns here say nothing about future returns, so that 0.72 comes from chance.

Method 1: Measuring the precision of the 0.72

In method 1, I focus only on the winning strategy. I resample its daily returns in blocks thousands of times, compute the Sharpe ratio each time, and see whether zero is outside the 95% interval.

def block_indices(n_days, n_draws, mean_block, seed=101):
    """One row per resample, holding the day numbers that resample is built from.

    This is the stationary bootstrap. Each day either continues the block that is
    running or starts a new block at a randomly chosen day, and the chance of starting
    a new one is 1 / mean_block. That makes the block lengths random with an average of
    mean_block days, and blocks of consecutive days keep the day-to-day dependence partly intact.
    """
    random_generator = np.random.default_rng(seed)
    new_block_chance = 1.0 / mean_block

    indices = np.empty((n_draws, n_days), dtype=np.int32)
    indices[:, 0] = random_generator.integers(0, n_days, n_draws)
    for t in range(1, n_days):
        starts_new_block = random_generator.random(n_draws) < new_block_chance
        fresh_day = random_generator.integers(0, n_days, n_draws)
        next_day = (indices[:, t-1] + 1) % n_days    # % wraps the last day back to the first
        # np.where makes the choice separately for every draw: the fresh day where a new
        # block starts, and otherwise the day after the one already drawn.
        indices[:, t] = np.where(starts_new_block, fresh_day, next_day)
    return indices


def bootstrap_sharpes(daily_returns, resample_indices):
    """Sharpe ratio of every column of daily_returns, for every resample.

    A resample is a list of day numbers, and a Sharpe ratio does not depend on the order
    those days come in. Only how often each day was drawn matters, so counting the draws
    once and then multiplying the counts by the returns gives the same answer as building
    thousands of resampled return series one at a time.
    """
    n_draws, n_days = resample_indices.shape

    draw_counts = np.zeros((n_draws, n_days))
    for draw in range(n_draws):
        # bincount counts how often each day number appears. minlength keeps the row the
        # full length of the series, so a day never drawn is recorded as zero.
        draw_counts[draw] = np.bincount(resample_indices[draw], minlength=n_days)

    # @ is matrix multiplication. It multiplies each row of counts through the returns
    # and adds the products, giving one total per draw per strategy.
    sum_of_returns = draw_counts @ daily_returns
    sum_of_squares = draw_counts @ daily_returns**2

    mean_return = sum_of_returns / n_days
    # The sample variance rebuilt from the two sums, dividing by n - 1 as ddof=1 does.
    variance = (sum_of_squares - n_days * mean_return**2) / (n_days - 1)

    daily_sharpe = mean_return / np.sqrt(variance)
    return daily_sharpe * np.sqrt(TRADING_DAYS_PER_YEAR)

BOOTSTRAP_DRAWS = 5_000
MEAN_BLOCK = 21                # about one trading month of consecutive days per block

n_common_days = strategy_returns.shape[0]
resample_indices = block_indices(n_common_days, BOOTSTRAP_DRAWS, MEAN_BLOCK)

# The double brackets ask for a one-column frame rather than a plain series, which is
# the shape bootstrap_sharpes works on. ravel() then flattens its result, which has one
# row per draw and one column per strategy, into one Sharpe ratio per draw.
winner_returns = strategy_returns[[winner]].values
winner_sharpes = bootstrap_sharpes(winner_returns, resample_indices).ravel()

interval_low, interval_high = np.percentile(winner_sharpes, [2.5, 97.5])
bootstrap_se = winner_sharpes.std()
share_at_or_below_zero = (winner_sharpes <= 0).mean()

print(f"observed Sharpe   {winner_sharpe:.2f}")
print(f"bootstrap se      {bootstrap_se:.2f}")
print(f"95% interval      [{interval_low:.2f}, {interval_high:.2f}]")
print(f"share of bootstrap Sharpe ratios at or below 0: {share_at_or_below_zero:.1%}")
observed Sharpe   0.72
bootstrap se      0.30
95% interval      [0.14, 1.31]
share of bootstrap Sharpe ratios at or below 0: 0.7%

The 95% interval runs from 0.14 to 1.31, and the bootstrap standard error is 0.30.

So a usual test would call the winner significant, even though the result is pure chance, because method 1 treats the winner as if it had been chosen in advance.

Method 2: Testing the winner against searches with no edge

But someone may have tried several strategies, and if you test several, you may find one that looks good by luck. In method 2, you focus on every strategy instead of one. You still generate the alternative histories, compute each strategy’s Sharpe ratio, and take the maximum for that round, and then you repeat the procedure and compare the Sharpe ratio from the original sample with these maxima. To give every strategy zero edge first, I subtract its average return,

\[R^0_{j,t} = R_{j,t} - \overline{R}_j,\]

# Taking each strategy's own average return away leaves its volatility, and its
# co-movement with the other 215, exactly as they were.
null_panel = strategy_returns - strategy_returns.mean()

# One Sharpe ratio per draw per strategy: 5000 rows by 216 columns.
null_grid = bootstrap_sharpes(null_panel.values, resample_indices)

# axis=1 takes the maximum across the strategies, so each row is the winner of one
# simulated search over the whole grid.
best_of_search = null_grid.max(axis=1)

# Counting the observed search itself, by adding one above and below, keeps the p-value
# away from an exact zero that the number of draws cannot support.
searches_at_least_as_good = (best_of_search >= winner_sharpe).sum()
p_value = (1 + searches_at_least_as_good) / (BOOTSTRAP_DRAWS + 1)

null_median = np.median(best_of_search)
null_90th = np.percentile(best_of_search, 90)
null_95th = np.percentile(best_of_search, 95)
share_beaten = (winner_sharpe > best_of_search).mean()

print("best Sharpe from a search with no edge:")
print(f"  median {null_median:.2f} | 90th {null_90th:.2f} "
      f"| 95th {null_95th:.2f} | max {best_of_search.max():.2f}")
print(f"our winner   {winner_sharpe:.2f}")
print(f"p-value      {p_value:.3f}   (beats {share_beaten:.0%} of searches with no edge)")
best Sharpe from a search with no edge:
  median 0.69 | 90th 0.91 | 95th 0.98 | max 1.65
our winner   0.72
p-value      0.407   (beats 59% of searches with no edge)

The median winning Sharpe ratio of a search with no edge is 0.69, and 41% of the searches reach 0.72 or more, with a p-value of 0.41. A winner would need a Sharpe ratio near 1 to be unusual, so the 0.72 is ordinary.

import matplotlib.pyplot as plt

RED, TEAL, ORANGE, GREY = "#C0392B", "#17868A", "#D2822B", "#888888"
# The site's chart colours: a cream background, a light grid and a pale frame, so every chart
# on the site has the same look.
BG, INK, GRID, SPINE, AXIS_TEXT = "#FCEFE3", "#1f1f1f", "#EADCCC", "#D5C6B4", "#4a4a4a"


def style_chart(figure, axis):
    """Give a finished chart the site's cream background, light grid and pale frame."""
    figure.patch.set_facecolor(BG)
    axis.set_facecolor(BG)
    axis.grid(True, axis="y", color=GRID, lw=1.0)
    axis.set_axisbelow(True)
    for side in ("top", "right"):
        axis.spines[side].set_visible(False)
    for side in ("left", "bottom"):
        axis.spines[side].set_color(SPINE)
    axis.tick_params(axis="both", length=0, colors=INK, pad=6)
    axis.xaxis.label.set_color(AXIS_TEXT)
    axis.yaxis.label.set_color(AXIS_TEXT)
    axis.title.set_color(INK)
    # Each legend entry in the colour of what it labels: a line's colour or a bar's fill.
    # get_legend() returns None when the chart has no legend.
    legend = axis.get_legend()
    if legend is not None:
        for text, handle in zip(legend.get_texts(), legend.legend_handles):
            if hasattr(handle, "get_color"):
                text.set_color(handle.get_color())
            else:
                text.set_color(handle.get_facecolor())


# plt.subplots(1, 2) returns the figure and the two panels side by side, and unpacking
# them here gives each panel a name instead of a position.
fig, (method1_panel, method2_panel) = plt.subplots(1, 2, figsize=(11, 4))

method1_panel.hist(winner_sharpes, bins=60, color=TEAL, alpha=.85)
method1_panel.axvline(winner_sharpe, color=INK, lw=1.5,
                      label=f"observed {winner_sharpe:.2f}")
method1_panel.axvline(interval_low, color=INK, ls="--", lw=1)
method1_panel.axvline(interval_high, color=INK, ls="--", lw=1)
method1_panel.axvline(0, color=RED, lw=1.2)
method1_panel.set_title("Method 1: how precisely is the winner measured?")
method1_panel.set_xlabel("bootstrapped Sharpe ratio")
method1_panel.legend(frameon=False)
style_chart(fig, method1_panel)

method2_panel.hist(best_of_search, bins=60, color=GREY, alpha=.85,
                   label="best Sharpe in a search with no edge")
method2_panel.axvline(winner_sharpe, color=INK, lw=1.5,
                      label=f"observed winner {winner_sharpe:.2f}")
method2_panel.axvline(null_95th, color=RED, ls="--", lw=1.2,
                      label="95th percentile of the null")
method2_panel.set_title("Method 2: best Sharpe ratio in a search with no edge")
method2_panel.set_xlabel("best Sharpe ratio in the search")
method2_panel.legend(frameon=False, fontsize=8)
style_chart(fig, method2_panel)

plt.tight_layout()
plt.savefig("sharpe_uncertainty.png", dpi=120, bbox_inches="tight", facecolor=BG)
plt.show()

Limitations

This is a tutorial, but the limitation is that a strategy can still pass this test and give a backtest that looks good.

In the end, the most important thing is that you have economic reasoning. You always need to think about whether the strategy you found makes sense and whether there is an economic reason for why it should work, because otherwise it can still be pure data mining, and that can also pass this test.

Conclusion

So the conclusion is that bootstrapping shows how much confidence a backtested Sharpe ratio deserves. Here, searching alone gives a best Sharpe ratio of at least 0.72 in 41% of the repetitions, so the winner can be luck. But in the end, you never know what a strategy’s future performance will be, and that is always an uncertainty you need to live with.

References

Politis, D. N., & Romano, J. P. (1994). The stationary bootstrap. Journal of the American Statistical Association, 89(428), 1303–1313. https://doi.org/10.1080/01621459.1994.10476870