The Problem With a Single Backtest
A backtest gives you a number: total PnL, Sharpe, max drawdown. The first two are (roughly) order-independent if you're just summing returns. Max drawdown is not. Neither is the probability that your equity curve touches a ruin threshold before the backtest window ends.
Consider two strategies with identical trade lists: same 300 trades, same total PnL, same win rate. One sequence happens to cluster its losses early and its wins late. The other does the reverse. Same totals, radically different drawdowns, radically different risk of blowing up mid-stream. Your backtest only sampled one of the possible orderings — the one that actually happened, or worse, the one your optimization pipeline selected for.
A Monte Carlo permutation test fixes this cheaply. Shuffle the realized trade PnL sequence thousands of times, recompute max drawdown and ruin indicators on every shuffle, then look at the resulting distribution. If your backtest's drawdown sits at the 5th percentile of the shuffled distribution, your headline number is flattering you. If it sits near the median, the strategy's risk is roughly order-neutral and you can trust the backtest more.
The key assumption: the multiset of trade PnLs is fixed, only the order is random. This tests sensitivity to sequencing, not to whether the trades themselves were lucky. It's a stress audit of path risk, not a validation of edge.
Setting Up the Data
Assume you have a vector of per-trade PnL in account currency (or in R-multiples — the math is identical, only the ruin thresholds change units).
import numpy as np
rng = np.random.default_rng(42)
# Example: 300 trades, mean +0.35R, std 1.2R, slight positive skew
pnl = rng.normal(0.35, 1.2, size=300)
# Add a few fat losses to make it realistic
pnl[:5] = -2.5
The permutation test only cares about the values, not their original order. If you want to audit the actual backtest drawdown, keep the original array around — you'll compare it against the shuffled distribution.
Vectorized NumPy Implementation
The naive approach loops over 5000 shuffles in Python and calls np.cumsum each time. That's fine for 300 trades but painful at 5000 trades × 5000 shuffles. Vectorize it: build a matrix of shape (n_sims, n_trades), cumsum along axis 1, then compute running max and drawdown per row.
import numpy as np
def permutation_drawdowns(pnl, n_sims=5000, seed=0):
pnl = np.asarray(pnl, dtype=np.float64)
n = pnl.size
rng = np.random.default_rng(seed)
# (n_sims, n) matrix of shuffled PnL
idx = rng.permuted(np.tile(np.arange(n), (n_sims, 1)), axis=1)
sims = pnl[idx]
# Cumulative equity per simulation
equity = np.cumsum(sims, axis=1)
# Running peak and drawdown
peaks = np.maximum.accumulate(equity, axis=1)
# Include starting equity of 0 as a peak
peaks = np.maximum(peaks, 0.0)
dd = peaks - equity
max_dd = dd.max(axis=1)
return max_dd, equity
Two details matter here:
-
rng.permutedshuffles each row independently in one call.np.random.shuffleon a 2D array shuffles along axis 0 only, which is not what you want. -
Seed the peak at 0. If the first few trades are losses, equity starts negative and
np.maximum.accumulatewould treat the first (negative) value as the peak, understating drawdown. Prepending a zero to the equity curve — or folding 0 into the peak vianp.maximum— fixes this.
For 5000 trades and 5000 simulations, that's a 25M-element float64 array — about 200 MB. If memory is tight, chunk the simulations:
def permutation_drawdowns_chunked(pnl, n_sims=5000, chunk=500, seed=0):
pnl = np.asarray(pnl, dtype=np.float64)
n = pnl.size
rng = np.random.default_rng(seed)
out = np.empty(n_sims, dtype=np.float64)
for start in range(0, n_sims, chunk):
stop = min(start + chunk, n_sims)
idx = rng.permuted(np.tile(np.arange(n), (stop - start, 1)), axis=1)
equity = np.cumsum(pnl[idx], axis=1)
peaks = np.maximum(np.maximum.accumulate(equity, axis=1), 0.0)
out[start:stop] = (peaks - equity).max(axis=1)
return out
Ruin Probability
Max drawdown is one number per shuffle. Ruin probability is the fraction of shuffles where the equity curve drops below a threshold at any point. Compute it directly from the drawdown matrix — no extra pass needed.
def ruin_probabilities(pnl, thresholds, n_sims=5000, seed=0):
pnl = np.asarray(pnl, dtype=np.float64)
n = pnl.size
rng = np.random.default_rng(seed)
idx = rng.permuted(np.tile(np.arange(n), (n_sims, 1)), axis=1)
equity = np.cumsum(pnl[idx], axis=1)
peaks = np.maximum(np.maximum.accumulate(equity, axis=1), 0.0)
dd = peaks - equity
# For each threshold, fraction of sims that ever exceeded it
hits = dd[:, :, None] >= np.asarray(thresholds)[None, None, :]
return hits.any(axis=1).mean(axis=0)
Pass thresholds in the same units as your PnL. If you're sizing in R-multiples and risking 1% of equity per trade, a 20R drawdown is roughly a 20% equity hit (ignoring compounding). Pick thresholds that map to real operational limits: margin call levels, a hard stop-loss on the strategy, a psychological "I'd shut this down" number.
Pure-Python Fallback
Sometimes you want this in a script with no numpy dependency — a research notebook on a locked-down box, a quick check in a CI step, or a port to another language. The pure-Python version is 20 lines and fast enough for a few hundred trades.
import random
def permutation_drawdowns_py(pnl, n_sims=5000, seed=0):
rnd = random.Random(seed)
values = list(pnl)
n = len(values)
result = []
for _ in range(n_sims):
rnd.shuffle(values) # in-place, O(n)
equity = 0.0
peak = 0.0
max_dd = 0.0
for x in values:
equity += x
if equity > peak:
peak = equity
dd = peak - equity
if dd > max_dd:
max_dd = dd
result.append(max_dd)
return result
random.Random.shuffle mutates the list in place, so you don't rebuild it every iteration — that's the main cost saver. If you need ruin probabilities too, track the minimum equity inside the loop and collect it. For 1000 trades × 5000 sims this takes a few seconds; the numpy version is roughly 50–100× faster.
Reading the Percentiles
Now the part that actually matters. You have a distribution of 5000 max drawdowns. What do you do with it?
max_dd = permutation_drawdowns(pnl, n_sims=5000, seed=42)
backtest_dd = 12.4 # your actual backtest max DD, same units
p50, p95, p99 = np.percentile(max_dd, [50, 95, 99])
print(f"P50: {p50:.2f} P95: {p95:.2f} P99: {p99:.2f}")
print(f"Backtest DD: {backtest_dd:.2f}")
print(f"Percentile of backtest DD: {(max_dd <= backtest_dd).mean() * 100:.1f}%")
Interpretation:
- P50 is the median drawdown over all orderings. If your backtest DD equals P50, you got an average-luck ordering. Nothing suspicious.
- P95 is the drawdown you'd exceed in 5% of orderings. This is the number to size against. If your risk limits are calibrated to the backtest DD and P95 is 2× higher, you're under-reserved.
- P99 is your tail scenario. If P99 exceeds your ruin threshold, the strategy has a material chance of hitting it under sequencing alone.
The percentile of your backtest DD tells you how flattering the realized order was. A backtest DD at the 10th percentile means 90% of orderings produce a worse drawdown — the strategy's risk is understated. At the 50th, you're unbiased. At the 90th, your backtest was unusually unlucky and the strategy is probably better than it looks (rare, but it happens with short samples).
The Pass/Reject Decision Rule
A concrete rule that works in practice:
- Compute P95 of max drawdown. This is your planning number.
- Compare to your operational drawdown limit — the level at which you'd cut the strategy (margin, mandate, or discipline).
- Compute ruin probability at that limit. This is the fraction of shuffles that touch it.
Decision:
- Pass if P95 max DD < operational limit and ruin probability at the limit < 5%.
- Marginal if P95 max DD < limit but ruin probability is 5–15%. Reduce size or tighten stops.
- Reject if P95 max DD ≥ limit or ruin probability > 15%. The strategy's headline drawdown is not representative of its path risk.
def audit(pnl, limit, n_sims=5000, seed=0):
dd = permutation_drawdowns(pnl, n_sims=n_sims, seed=seed)
p50, p95 = np.percentile(dd, [50, 95])
ruin = (dd >= limit).mean()
verdict = "PASS"
if p95 >= limit or ruin > 0.15:
verdict = "REJECT"
elif ruin > 0.05:
verdict = "MARGINAL"
return {"p50": p50, "p95": p95, "ruin": ruin, "verdict": verdict}
One caveat worth stating plainly: this test assumes trade PnLs are exchangeable. Real strategies have autocorrelation — volatility clustering, regime shifts, correlated losses during stress. Permutation tests ignore that, so they can understate tail drawdowns when losses cluster. If you suspect serial dependence, the permutation test is a lower bound on path risk, not an upper one. Combine it with a block bootstrap or a regime-conditional analysis if the strategy is sensitive to volatility regimes.
What This Test Does and Doesn't Tell You
It tells you whether your backtest drawdown is representative of the drawdown distribution over all orderings of the same trades. It does not tell you whether the trades themselves are predictive, whether the sample is large enough, or whether the strategy will work out of sample. Those are separate questions with separate tests.
What it does well: it catches the specific failure mode where a strategy looks safe because the backtest got a lucky ordering. That failure mode is common, cheap to test for, and expensive to discover live. Five thousand shuffles and a percentile lookup is a small price.
More notes like this ship every week on this site.
Daily Picks
The following pairs are selected from the multi-timeframe trend scanner (Gate.io futures) and are for technical-analysis study only — not investment advice.
Data updated: 2026-11-09 08:46:35
Long
| Pair | Signal | Price | Take Profit | Stop Loss | R/R |
|---|---|---|---|---|---|
| CLAUDIA | 短平快做多 | $0.0061 | $0.0063 | $0.0059 | 1:1.2 |
Short
| Pair | Signal | Price | Take Profit | Stop Loss | R/R |
|---|---|---|---|---|---|
| BLESS | 衰竭做空 | $0.0081 | $0.0078 | $0.0084 | 1:1.2 |
2 picks selected. Scanner runs every 15 minutes.
Top comments (0)