DEV Community

Cover image for I Built a Luck Check for Stock Backtests in Python. Here's the Code and What It Caught
Sarthak Verma for MarketDeck

Posted on AI-assisted

I Built a Luck Check for Stock Backtests in Python. Here's the Code and What It Caught

Most backtests answer the wrong question.

They ask "did my strategy beat the index?" On Indian stocks from 2022 to 2026, that question is almost useless. We tested a strategy that buys Nifty 500 companies whose name starts with S. It grew 22.4% a year against the index's 10.1%.

The better question is: did my strategy beat random portfolios built exactly like it?

This post shows how to build that check in about 60 lines of Python, then what happened when we ran it on nine real strategies.

The idea: random twins

For each strategy, generate N random portfolios that copy everything except the stock-picking rule:

Keep the same Why
Number of stocks A 20-stock basket and a 500-stock basket have very different spreads of outcomes
Universe Picking from small caps vs large caps changes everything
Rebalance dates So both face the same market days
Turnover per rebalance So both pay the same trading costs
Weighting and costs Equal weight vs market cap is a huge hidden effect

Then count how many of the twins the strategy beat. 50% means coin flip. 95%+ means the rule probably carries information (in that sample).

The code

It runs on synthetic prices so you can copy it and run it now. Swap in your own monthly returns DataFrame to test a real idea.

import numpy as np
import pandas as pd

rng = np.random.default_rng(7)

# 1. Fake universe: 200 stocks, 60 months
n_stocks, n_months = 200, 60
drift = rng.normal(0.010, 0.006, n_stocks)
vol = rng.uniform(0.05, 0.14, n_stocks)
market = rng.normal(0.008, 0.045, n_months)
noise = rng.normal(0, 1, (n_months, n_stocks)) * vol
rets = pd.DataFrame(market[:, None] + drift + noise,
                    columns=[f"S{i:03d}" for i in range(n_stocks)])

# 2. Strategy: hold the 20 best trailing 12-month performers
def momentum_picks(rets, k=20, lookback=12):
    picks = {}
    for t in range(lookback, len(rets)):
        trailing = (1 + rets.iloc[t - lookback:t]).prod() - 1
        picks[t] = trailing.nlargest(k).index
    return picks

def portfolio_return(rets, picks, cost_per_turnover=0.002):
    growth, prev = 1.0, set()
    for t, names in picks.items():
        names = set(names)
        turnover = len(names - prev) / len(names) if prev else 1.0
        month = rets.iloc[t][list(names)].mean() - turnover * cost_per_turnover
        growth *= 1 + month
        prev = names
    return growth - 1

picks = momentum_picks(rets)
idea_total = portfolio_return(rets, picks)

# 3. Random twins: same size, same dates, same number of swaps each month
def random_twin(rets, picks, rng):
    twin, prev = {}, None
    universe = rets.columns
    for t, names in picks.items():
        k = len(names)
        if prev is None:
            cur = set(rng.choice(universe, k, replace=False))
        else:
            n_swap = len(set(names) - set(picks[t - 1])) if (t - 1) in picks else k
            keep = set(rng.choice(sorted(prev), k - n_swap, replace=False))
            pool = [s for s in universe if s not in keep]
            cur = keep | set(rng.choice(pool, n_swap, replace=False))
        twin[t] = list(cur)
        prev = cur
    return twin

N = 1000
random_totals = np.array([
    portfolio_return(rets, random_twin(rets, picks, rng)) for _ in range(N)
])

beaten = (random_totals < idea_total).mean() * 100
se = np.sqrt(beaten / 100 * (1 - beaten / 100) / N) * 100
p5, p50, p95 = np.percentile(random_totals * 100, [5, 50, 95])

print(f"Strategy total return     : {idea_total * 100:6.1f}%")
print(f"Random portfolios (median): {p50:6.1f}%   5th-95th: {p5:.1f}% to {p95:.1f}%")
print(f"Share of {N} random portfolios beaten: {beaten:.1f}% (+/- {1.96 * se:.1f} pts)")
Enter fullscreen mode Exit fullscreen mode

Output on my machine:

Strategy total return     :   63.5%
Random portfolios (median):   60.1%   5th-95th: 24.7% to 104.5%
Share of 1000 random portfolios beaten: 54.2% (+/- 3.1 pts)
Enter fullscreen mode Exit fullscreen mode

That is the correct answer. The fake prices have no momentum in them (each month is independent), so a momentum rule should beat about half the twins, and it does. Note the spread: random 20-stock baskets ranged from +25% to +105%. A strategy showing +63% means nothing on its own.

A note on the error bar: with N = 1,000 the standard error of a share near 50% is about 1.6 points. Do not quote "beat 96.3%" as if the decimal means something.

What it caught on real Indian data

We ran the same method (with fees, slippage and per-name turnover matching) on nine ideas using our research engine and daily Indian prices to 3 December 2026.

Strategy Universe CAGR Index CAGR Random twins beaten (return) Fees + slippage
12-1 momentum, top 30 Nifty 500 39.6% 10.8% 100% 13.3%
50/200-day golden cross Nifty 100 24.1% 11.9% 99% 2.4%
6-1 momentum, top 20 Nifty 200 29.5% 10.7% 98% 17.1%
Strongest 3 sector indices Sector indices 13.0% 13.0% 78% 17.0%
Price above 200-day average Nifty 100 19.7% 11.9% 69% 16.0%
Names starting with S (control) Nifty 500 22.4% 10.1% 62% 2.1%
1-month losers (reversal) Nifty 500 16.8% 10.1% 58% 39.0%
Closest to 52-week high, top 30 Nifty 500 17.9% 10.8% 34% 23.1%
Lowest 60-day volatility, 30 Nifty 500 12.8% 9.8% 2% 5.9%

Historical simulation. Price return before tax, no dividends. Survivors-only data with today's index lists, which flatters every row, including the random twins. Fees + slippage are % of starting capital over the whole run. Not investment advice.

Try it: throw your own darts

Pick any of the nine strategies and throw random portfolios at it. The darts are drawn from a distribution fitted to each run's real luck-check percentiles.

Four patterns the luck check caught

1. "Beats the index" is free in some periods. Eight of eight stock strategies beat their index on CAGR. Equal weighting plus survivorship plus a small- and mid-cap rally did that, not the rules. The alphabet control proves it.

2. A smooth line can hide a bad picker. Low volatility beat its index (12.8% vs 9.8%) and fell less than 96% of its twins. But it beat only 2% of them on total return. In this period, choosing calm stocks meant choosing the wrong stocks.

3. Turnover is a cost line, not a detail. The reversal strategy replaced ~91% of its basket every month and spent 39% of starting capital on fees and slippage. It still beat 58% of twins, because the twins pay the same costs. That is why turnover-matching matters: otherwise you are comparing a busy strategy against lazy random portfolios.

4. Even winners need a holdout. 12-1 momentum's Sharpe went from 1.30 in-sample to 1.08 on the held-out final 18 months. Still there, but weaker. The low-volatility idea went from 0.68 to 0.11.

Gotchas when you build your own

  • Match turnover, not just size. Random portfolios that never trade will look worse after costs than they should.
  • Use the same universe at each date. If your universe is "today's Nifty 500," your twins must draw from the same list, and you should say so.
  • Count your trials. If you tried 40 parameter sets, the best one beating 97% of twins is expected. Look up the deflated Sharpe ratio (Bailey and López de Prado) for a correction.
  • Check more than one metric. We report the share beaten on return, Sharpe and max drawdown separately. They often disagree.
  • Vectorise if you scale it. The loop above takes ~14 seconds for 1,000 twins. For a big universe, precompute a returns matrix and draw index arrays with NumPy.

Try it on your own idea

The script above is enough to get started. If you would rather not wire up data, we built the same check into MarketDeck's Research Desk, which runs it on every backtest for Indian stocks, along with the holdout and cost breakdown.

What strategy would you like to see run against 1,000 random twins next? Tell me in the comments and I'll run the most-requested one.


Research and education only, not investment advice. Results are historical simulations and do not indicate future results. Cover illustration is AI-generated.

Top comments (0)