Use bt plus randomized windows to run statistical tests on your backtest
Published: 2026-02-07
URL: https://pyquantnews.substack.com/p/pressure-test-your-equity-curve-early
Each week, I send out one Python tutorial to help you get started with algorithmic trading, market data analysis, and quant finance. Upgrade to a paid plan to access the code notebooks. Subscribe now In todayâs post, youâll build a bt backtest and then run a Monte Carlo sanity check on it. Backtesting as an experiment A backtest is a controlled simulation that turns a trading rule and historical prices into performance metrics you can evaluate.
The idea became mainstream as markets digitized and researchers could replay history cheaply on computers. Once hedge funds and bank quant desks started running large research pipelines in the 1990s and 2000s, they learned the hard way that impressive in-sample results often came from chance.
How pros pressure-test results Today, professionals treat backtests as the start of the research process. A common workflow is to implement the rule with a framework like bt, run it with realistic frictions, then inspect the stats youâd actually risk-manage against.
That includes things like the daily Sharpe ratio, drawdowns, and how concentrated the exposure is through time. After that, they run âwhat would this look like if prices were randomâ tests, because it gives a baseline for how often a strategy can look good without having any real edge.
In this issue, that pressure test is simple and practical. You shuffle the daily prices, keep your trading rule exactly the same, rerun the backtest many times, and collect the resulting Sharpe ratios. Then you compare your original Sharpe to the shuffled distribution and compute a p-value as the fraction of random runs that beat your result.
Why this matters early This matters because it forces you to separate âthe strategy logicâ from âthis specific slice of history.â That one habit will save you from parameter tweaking that feels like research but behaves like curve fitting. Once you can run a quick Monte Carlo check, youâll waste less time optimizing noise and youâll get faster feedback when your data handling leaks information. Letâs see how it works with Python.
This Substack is reader-supported. To get the code notebooks, consider becoming a free or paid subscriber. Library installation This installs all required libraries for running the notebook. The bt library is a flexible backtesting framework that bundles yfinance for data retrieval, pandas for data manipulation, and matplotlib for plotting. Installing bt pulls in all dependencies we need. Imports and setup We use bt for building and running backtests with minimal boilerplate, and matplotlib.pyplot for visualizing equity curves and performance distributions.
Download data and define strategy helpers This downloads daily adjusted close prices for TLT (iShares 20+ Year Treasury Bond ETF) from Yahoo Finance over a 12-year period. Treasury bonds are a useful test asset because they exhibit seasonality patterns and tend to behave differently than equities. Using a long historical window gives us enough market cycles to assess whether any observed edge is real or just noise.
This function creates a bt Strategy object that selects all assets, applies target weights, and rebalances the portfolio on each trading day. The bt framework uses an algorithm-based approach where each step in the trading logic is a composable building block. WeighTarget reads from a DataFrame of target weights, allowing us to define complex position-sizing rules outside the strategy itself.
This function wraps a strategy with price data, starting capital, and a commission model to create a runnable backtest. Separating the backtest configuration from the strategy definition makes it easy to test the same strategy under different assumptions. We can swap commission models or change initial capital without touching the trading logic.
This function extracts the day of month from the index and adds it as a column, which we need to implement our calendar-based trading rule. Calendar-based features like day of month are commonly used to exploit institutional flow patterns.
For example, pension funds and mutual funds often rebalance at month-end, creating predictable price pressure. This function implements a tiered commission structure where larger trades pay higher fixed fees, simulating realistic brokerage costs. Transaction costs are one of the main reasons strategies that look good on paper fail in practice. Including commissions in our backtest helps us understand whether the edge is large enough to survive real-world trading friction.
This function creates target weights for a calendar-based strategy that is short during the first week, flat in the middle, and long during the last week of each month. This turn-of-the-month strategy attempts to capture a well-documented calendar anomaly in fixed income markets.
By encoding our trading logic as a DataFrame of weights, we keep the signal generation separate from the execution machinery. Build and run the strategy backtest This assembles all our components and runs the backtest, chaining together data preparation, weight calculation, strategy building, and execution.
The bt.run function simulates every trading day, tracking positions, cash, and performance metrics as it processes the price data. This is where all the heavy lifting happens under the hood. This displays a comprehensive table of performance statistics including returns, risk metrics, and drawdown analysis.
The Sharpe ratio of 0.49 tells us the strategy earns about half a unit of return per unit of risk. The max drawdown of -19% shows the worst peak-to-trough decline we would have experienced. These numbers look reasonable, but we cannot yet tell if they are statistically significant or just luck.
This plots the equity curve showing how our portfolio value evolved over time. The result is a chart that looks like this. The equity curve visualizes the compounding of returns over the full backtest period. Flat or declining sections reveal drawdown periods, while steep upward slopes show when the strategy performed well. Validate strategy with permutation testing This function randomly shuffles the order of daily prices while preserving the date index, breaking any real calendar relationship in the data.
Permutation testing helps us answer a critical question: would our calendar-based strategy have worked just as well if there was no actual calendar pattern in prices? By shuffling prices, we create a null hypothesis where calendar effects cannot exist.
This stores the original strategyâs Sharpe ratio and prepares to collect Sharpe ratios from 1000 randomized backtests. Running 1000 permutations gives us a distribution of outcomes under the null hypothesis. If our original Sharpe falls in the extreme tail of this distribution, we have evidence that the calendar pattern is real.
This loop runs the full backtest 1000 times on shuffled price data, collecting the Sharpe ratio from each run to build a null distribution. Monte Carlo permutation testing is a non-parametric method that makes no assumptions about the distribution of returns.
This makes it more robust than traditional statistical tests that assume normality, which rarely holds in financial data. This plots a histogram of Sharpe ratios from the shuffled backtests with a vertical line showing where our actual strategyâs Sharpe falls.
The result is a chart that looks like this. The dashed line should fall far to the right of the histogram if our strategy has real predictive power. When the line sits inside the distribution, the performance could plausibly have come from random chance.
This computes and displays the p-value by counting how many shuffled backtests produced a Sharpe ratio higher than our original strategy. Your next steps You can now run a bt backtest and then quantify how often the same Sharpe shows up when you shuffle prices, using the resulting distribution and p-value as a sanity check.
That gives you a baseline for âluck versus edgeâ and keeps you from spending time tuning strategies that only worked in one noisy window.