Use Backtrader to simulate a calendar strategy and benchmark it with QuantStats.
By PyQuant News
Published: 2026-04-25
URL: https://pyquantnews.substack.com/p/your-backtest-is-probably-broken
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.

In todayâs post, youâll use Python to backtest a real trading strategy on 20 years of bond data, then compare its performance against simply holding the same asset the entire time.
What backtesting actually means
A backtest is a simulation that runs your trading rules against historical market data to estimate how a strategy might have performed in the past.
The idea has been around since the early days of computerized trading in the 1980s, when firms first started using databases of old prices to test their ideas before risking capital.
As computing power got cheaper, backtesting became standard practice at hedge funds and trading desks, and eventually accessible to individual traders through open-source tools.
How professionals use it
Today, trading teams at firms of all sizes run backtests as a first filter before putting any strategy into production (meaning live trading with real capital).
They donât treat backtest results as predictions. Instead, they use them to check whether a strategyâs performance could be explained by chance, or whether it holds up across different time periods and market conditions.
A strategy that looks great on one slice of data but falls apart on another is usually the result of overfitting. That means the rules were tuned too tightly to match past events that wonât repeat.
Why this matters for you
If youâre learning Python for trading, backtesting is one of the first practical skills that will save you real money.
It lets you test an idea before you risk anything, and it forces you to think clearly about your assumptions. In this article, youâll use a library called Backtrader to build and run a complete backtest, then evaluate the results with a performance analysis tool called QuantStats.
Letâs see how it works with Python.
The PyQuant Newsletter is reader-supported. To receive new posts and the code notebooks, consider becoming a free or paid subscriber.
Library installation
This installs the core libraries for backtesting and performance analysis used in this notebook.

Imports and setup
We use datetime for date parsing, pandas for tabular data handling, openbb for fetching historical market data, quantstats for generating professional performance reports, and backtrader for running the backtest simulation itself.

Load and prepare historical data
This function fetches historical price data for a given symbol using OpenBB, saves it to CSV, and converts it into a Backtrader-compatible data feed.

Backtrader expects data in a specific format, so we save the OpenBB output as a CSV and reload it through Backtraderâs built-in Yahoo Finance CSV parser.
This intermediate step bridges two libraries that donât natively share a data format. The date range is explicitly passed to both the data fetch and the feed to ensure consistency.
This helper calculates the last calendar day of any given month, which the strategy needs to determine whether weâre near month-end.

The trick here is that day 28 exists in every month, so adding 4 days always lands in the next month. Subtracting back by the resulting day number gives us the last day of the original month. This avoids importing the calendar module for a simple calculation.
Define the monthly flows strategy
This strategy class encodes a calendar-based trading rule: go short during the first week of each month and go long during the last week. Backtrader strategies inherit from bt.Strategy and implement their logic in the next() method, which is called once per bar (each trading day).

The params tuple lets us adjust the day-of-month thresholds without editing the logic itself. The order\target\percent method tells Backtrader to size positions as a fraction of portfolio value, where -1 means fully short and 1 means fully long.
Notice that notify\_order resets self.order to None after each fill, which prevents the strategy from stacking multiple orders on consecutive bars. This is exactly the kind of guardrail that prevents subtle bugs in a backtest.
Run the backtest and evaluate results
We load 20 years of TLT (long-term U.S. Treasury bond ETF) data, which gives us a long enough history to see how the strategy behaves across multiple market regimes.

Cerebro is Backtraderâs central engine. We configure it with our data feed, starting capital, strategy, a portfolio value observer for plotting, and two analyzers that capture return metrics weâll need for evaluation.

Setting stdstats=False disables Backtraderâs default observers so we only track what we explicitly add. The TimeReturn analyzer records daily returns as a dictionary keyed by date, which weâll convert to a pandas DataFrame for QuantStats.
Starting with $1,000 keeps the numbers easy to interpret while still producing realistic percentage-based results.
We extract the daily strategy returns from the backtest result and reshape them into a DataFrame that QuantStats can consume.

Backtrader stores analyzers on the first element of the result list because cerebro.run() returns one result per strategy. Converting the dictionary to a DataFrame with a date index is the standard handoff format that QuantStats and most Python finance tools expect.
We load the same TLT price series as a benchmark, then generate a full QuantStats performance report comparing our strategy against a simple buy-and-hold approach.

This is the most important step in the entire workflow. Comparing against a benchmark answers the question every backtest should ask: did the strategy actually add value, or would we have been better off just holding the asset?
QuantStats produces dozens of metrics including Sharpe ratio, maximum drawdown, and win rate, giving us a professional-grade evaluation without writing any of that math ourselves.
Your next steps
You now have a working backtest pipeline that lets you test a strategy against real data and measure it against a benchmark.
Thatâs the difference between guessing and knowing and itâs the minimum standard before any strategy deserves real capital.