Monte Carlo backtesting: how to stress-test a trading strategy (with Python)

Updated Nov 17, 2026 · 7 min read

A Monte Carlo backtest rebuilds a strategy’s equity curve thousands of times to show the range of drawdowns it could have had. Methods, pitfalls, and Python on Hyperliquid BTC data.

What is a Monte Carlo backtest? It takes the trades your backtest produced and rebuilds the equity curve thousands of times: by shuffling their order, by drawing them at random with replacement, or by drawing returns from a fitted model. Each run has its own max drawdown and final result, and their spread shows what a single backtest curve hides. It tests the luck of the sequence, not whether the edge is real.

Key takeaways

  • One backtest is one path. Monte Carlo shows the range the same trades could have produced.
  • Shuffling trades changes the drawdown, never the final equity. To vary both, bootstrap or simulate from a model.
  • In the BTC example below, the backtest’s max drawdown was 29.7%; in the worst 5% of bootstrap runs it was 52.4% or deeper.
  • More runs can’t fix a short trade history or a flawed backtest.

Three ways to build the runs

Our guide on how to backtest a crypto trading strategy uses the simplest version, drawing 365 daily returns with replacement. The methods answer different questions.

MethodHow each run is builtWhat changes between runsWhat it misses
Reshuffle (permutation)The same trades, in a random orderDrawdown and losing streaks; final equity is identicalAny outcome other than the one you got
BootstrapDraw as many trades as you had, with replacementDrawdown and final equityStreaks, because it treats trades as independent
ParametricDraw returns from a fitted distribution, such as a normal with the trades’ mean and spreadDrawdown and final equity, including results the history never showedAnything the chosen distribution leaves out
Common Monte Carlo methods for trading backtests.

Reshuffling is the one people get wrong. Compounded returns multiply, and a product is the same in any order, so every reshuffled run ends at the backtest’s final equity. Use it for drawdown; use the bootstrap or a model for the range of final results.

It can’t show whether the edge is real: an overfit rule resamples into a confident range, and lookahead bias or missing fees pass into every run. Resampling closed trades also misses the drawdown inside an open trade (max drawdown explained).

Worked example: Monte Carlo on a BTC moving-average cross

An illustration, not a strategy

The script pulls BTC 4-hour candles from Hyperliquid’s public info API (candleSnapshot, no key needed), which keeps only the most recent 5,000 candles, about 833 days at 4 hours. The rule goes long when the 20-candle average closes above the 50-candle average and exits when it closes below, filling at the next candle’s open. Each trade pays the 0.045% base-tier taker fee on both sides plus 1 basis point of slippage per side (Hyperliquid fees). Each method runs 10,000 times with a fixed seed. Tested with Python 3.9.6 and numpy 2.0.2 on Nov 17, 2026; the candle window rolls forward, so later runs shift a little.

python
"""Monte Carlo backtest, worked example (illustration only, not a recommended strategy).
1) Pull BTC 4-hour candles from Hyperliquid's public info API (candleSnapshot, no key needed).
2) Run a simple, illustrative rule: long when the 20-candle average is above the 50-candle average.
3) Monte Carlo the trade returns three ways (reshuffle, bootstrap, parametric), 10,000 runs, fixed seed.
Tested with Python 3.9.6 and numpy 2.0.2 on Nov 17, 2026."""
import json
import urllib.request
from datetime import datetime, timezone

import numpy as np

END = datetime(2026, 11, 17, tzinfo=timezone.utc)  # fixed end, so the run is repeatable
COST_PER_SIDE = 0.00045 + 0.0001  # base-tier taker fee 0.045% + 1 bp slippage allowance
FAST, SLOW = 20, 50                # illustrative moving-average lengths, not tuned
RUNS, SEED = 10_000, 42


def get_candles(coin="BTC", interval="4h"):
    body = {"type": "candleSnapshot", "req": {"coin": coin, "interval": interval,
            "startTime": 0, "endTime": int(END.timestamp() * 1000) - 1}}
    req = urllib.request.Request("https://api.hyperliquid.xyz/info", json.dumps(body).encode(),
                                 {"Content-Type": "application/json"})
    return json.load(urllib.request.urlopen(req, timeout=30))  # API keeps the latest 5,000 candles


def ma_cross_trades(candles):
    """Signal on a closed candle, fill at the next candle's open (no lookahead). Long-only, 1x."""
    opens = np.array([float(c["o"]) for c in candles])
    closes = np.array([float(c["c"]) for c in candles])
    trades, entry = [], None
    for i in range(SLOW - 1, len(candles) - 1):
        fast, slow = closes[i - FAST + 1:i + 1].mean(), closes[i - SLOW + 1:i + 1].mean()
        if entry is None and fast > slow:
            entry = opens[i + 1]
        elif entry is not None and fast < slow:
            gross = opens[i + 1] / entry - 1
            trades.append(gross - 2 * COST_PER_SIDE)
            entry = None
    return np.array(trades)  # a trade still open at the end is left out


def max_drawdown(equity):
    """Deepest fall from a running peak, per row; equity paths start at 1."""
    return (equity / np.maximum.accumulate(equity, axis=1) - 1).min(axis=1)


def simulate(paths):
    equity = np.hstack([np.ones((len(paths), 1)), np.cumprod(1 + paths, axis=1)])
    return max_drawdown(equity), equity[:, -1]


def monte_carlo(r, method, leverage=1.0, seed=SEED, runs=RUNS):
    rng = np.random.default_rng(seed)
    r = r * leverage
    if method == "reshuffle":      # same trades, new order
        paths = rng.permuted(np.tile(r, (runs, 1)), axis=1)
    elif method == "bootstrap":    # draw trades with replacement
        paths = rng.choice(r, size=(runs, len(r)), replace=True)
    elif method == "parametric":   # normal returns with the trades' mean and spread
        paths = np.clip(rng.normal(r.mean(), r.std(ddof=1), size=(runs, len(r))), -0.99, None)
    return simulate(paths)


def pct(x):
    return f"{x * 100:+.1f}%"


candles = get_candles()
first = datetime.fromtimestamp(candles[0]["t"] / 1000, timezone.utc)
last = datetime.fromtimestamp(candles[-1]["T"] / 1000, timezone.utc)
print(f"BTC 4h candles: {len(candles)}, {first:%Y-%m-%d %H:%M} to {last:%Y-%m-%d %H:%M} UTC")
print(f"pulled at {datetime.now(timezone.utc):%Y-%m-%d %H:%M} UTC")

trades = ma_cross_trades(candles)
dd, final = simulate(trades[None, :])
print(f"trades: {len(trades)}, win rate {np.mean(trades > 0):.0%}, "
      f"mean {pct(trades.mean())}, best {pct(trades.max())}, worst {pct(trades.min())}")
print(f"backtest as run: final equity {final[0]:.3f}x, max drawdown {pct(dd[0])}\n")

print("method      lev | median maxDD | worst-5% maxDD | median final | worst-5% final | P(DD<-30%) | runs worse DD than actual")
for method, lev in [("reshuffle", 1), ("bootstrap", 1), ("parametric", 1), ("bootstrap", 3)]:
    mdd, fin = monte_carlo(trades, method, lev)
    actual_dd = simulate(trades[None, :] * lev)[0][0]
    print(f"{method:<11} {lev}x  | {pct(np.median(mdd)):>12} | {pct(np.percentile(mdd, 5)):>14} | "
          f"{np.median(fin):>11.3f}x | {np.percentile(fin, 5):>13.3f}x | {np.mean(mdd < -0.30):>10.1%} | "
          f"{np.mean(mdd < actual_dd):.0%}")

print("\nseed check, bootstrap 1x, worst-5% max drawdown:",
      ", ".join(pct(np.percentile(monte_carlo(trades, "bootstrap", seed=s)[0], 5)) for s in (1, 2, 3)))

The backtest as run: 55 closed trades, 44% of them winners, ending at 1.097 times the starting equity with a 29.7% max drawdown along the way.

MethodLeverageMedian max drawdownWorst 5% max drawdownMedian final equityWorst 5% final equityRuns that fell more than 30%
Backtest as run1x−29.7% (one path)n/a1.097xn/an/a
Reshuffle1x−30.0%−42.3%1.097x1.097x49.9%
Bootstrap1x−30.9%−52.4%1.084x0.560x53.1%
Parametric (normal)1x−33.8%−57.8%1.086x0.528x62.3%
Bootstrap3x−71.4%−91.7%0.808x0.123x99.9%
Source: Hyperliquid API (candleSnapshot), BTC 4-hour candles Aug 6, 2024 12:00 to Nov 16, 2026 23:59 UTC, pulled 19:15 UTC on Nov 17, 2026. 10,000 runs per method, seed 42. Fees and a slippage allowance included; funding and liquidation not modelled. Illustrative rule only. Market data only; not a forecast or a trade signal.

In the worst 5% of bootstrap runs, the same 55 trades lost 44% or more of the account. At 3x, the median run ended below its start: a position sizing lesson. Seeds 1, 2 and 3 gave a bootstrap worst-5% drawdown of 52.6%, 52.7% and 52.6%, so 10,000 runs was enough.

Where Senpi fits

Senpi doesn’t run backtests; Simulations, paper trading with simulated money, are coming. On Senpi, a strategy you confirm runs as code on Senpi’s runtime, and by default no AI model makes live trading decisions. Each strategy trades from its own strategy wallet; the agent holds no key and cannot withdraw.

Strategies built from a rule or a template carry the Dynamic Stop-Loss (DSL), a stop that ratchets up as the trade gains, from the first fill, and each can have its own daily-loss halt, which lifts at the next UTC midnight, or a drawdown halt, which waits until you resume it. Copy strategies carry at most a flat stop. A drawdown halt set near the level your Monte Carlo test says you could reach is one way to act on the result.

How many Monte Carlo simulations should I run for a backtest?

Enough that re-running with a different seed barely moves the worst-5% drawdown. In the example above, 10,000 runs moved it by 0.1 points across three seeds.

Can a Monte Carlo backtest predict future returns?

No. Every run is built from past trades or a model fitted to them, so it shows how much luck sat inside the result, not what the market will do next.

Does Senpi run Monte Carlo backtests?

No. Senpi doesn’t run backtests; Simulations, paper trading with simulated money, are coming.

Sources: Hyperliquid API docs, info endpoint (candleSnapshot: only the most recent 5,000 candles) and Hyperliquid fee schedule (0.045% taker, 0.015% maker at the base tier on perps), both checked Nov 17, 2026; BTC 4-hour candles from the Hyperliquid info API, pulled 19:15 UTC on Nov 17, 2026.

This page is educational, not financial advice. The example rule is an illustration, not a recommendation.

Run a tested rule as code

On Senpi, a strategy you confirm runs as code on Senpi’s runtime, from its own strategy wallet.

Try Senpi free
Share

Related articles