Python Quantitative Backtesting and Performance Evaluation
Backtesting is the process of simulating and evaluating a trading strategy on historical market data.
It is the most critical part of quantitative trading: past performance does not guarantee the future, but a strategy without historical validation does not even qualify for discussion.
This article will hand-write a complete vectorized backtest, compute four major performance metrics, and thoroughly explain the backtest pitfalls beginners most easily fall into.
General Steps of a Backtest
A rigorous backtest usually includes the following steps:
| Step | Description |
|---|---|
| Define the Trading Strategy | Determine the rules for when to buy, sell or hold, such as moving-average crosses, breakouts, arbitrage conditions, etc. |
| Obtain Historical Data | Get prices, volume and other data within the backtest period |
| Simulate Trading | Generate signals day by day on historical data according to the strategy rules and compute the profit/loss of each trade |
| Compute Performance Metrics | Compute annualized return, maximum drawdown, Sharpe ratio, etc., to quantitatively evaluate strategy performance |
| Optimization and Re-validation | Adjust parameters and retest when results are poor; even when results are good, validate on a data segment not used in tuning |
The whole process is interlinked; after optimization you must return to the simulation step to re-validate, forming a closed loop:
Hand-Writing the First Backtest
Without any backtest framework, use pandas directly to simulate a dual moving-average strategy on Moutai data from 2019 to 2021.
The biggest benefit of writing it yourself is seeing exactly what happens in every detail of the backtest:
Example
import
yfinance
as
yf
import
matplotlib.
pyplot
as
plt
Get the backtest period data
data
=
yf.
download
(
"600519.SS"
,
start
=
"2019-01-01"
,
end
=
"2021-01-01"
,
progress
=
False
,
multi_level_index
=
False
)
Compute the dual moving averages
data
[
"SMA50"
]
=
data
[
"Close"
]
.
rolling
(
window
=
50
)
.
mean
(
)
data
[
"SMA200"
]
=
data
[
"Close"
]
.
rolling
(
window
=
200
)
.
mean
(
)
Generate signals: record 1 (long) when the short-term MA is above, -1 (flat) when below
data
[
"Signal"
]
=
0
data.
loc
[
data
[
"SMA50"
]
data
[
"SMA200"
]
,
"Signal"
]
=
1
data.
loc
[
data
[
"SMA50"
]
<
data
[
"SMA200"
]
,
"Signal"
]
=
1
data
[
"Daily_Return"
]
=
data
[
"Close"
].
pct_change
(
)
The key line: multiply yesterday's signal by today's return
shift(1) shifts the signal back by one day, meaning 'the signal is computed at today's close and can only be executed tomorrow'
data
[
"Strategy_Return"
]
=
data
[
"Signal"
]
.
shift
(
1
)
- data
[
"Daily_Return"
]
Compute the cumulative net value of the strategy and buy-and-hold
data
[
"Cum_Strategy"
]
=
(
1
- data
[
"Strategy_Return"
]
)
.
cumprod
(
)
data
[
"Cum_Stock"
]
=
data
[
"Close"
]
/ data
[
"Close"
]
.
iloc
[
0
]
Plot the cumulative return curve
plt.
figure
(
figsize
=
(
12
,
6
)
)
plt.
plot
(
data
[
"Cum_Strategy"
]
,
label
=
"Strategy Cumulative Return"
,
color
=
"b"
)
plt.
plot
(
data
[
"Cum_Stock"
]
,
label
=
"Stock Cumulative Return"
,
color
=
"g"
)
plt.
title
(
"Cumulative Return of Strategy vs. Stock"
)
plt.
xlabel
(
"Date"
)
plt.
ylabel
(
"Cumulative Return"
)
plt.
legend
(
)
plt.
show
(
)
Run the code above and the output chart is as follows; the blue line is the strategy net value and the green line is the buy-and-hold net value:

Core detail: the line data["Signal"].shift(1) is the cornerstone of backtest fairness. Today's return must be determined by yesterday's signal, because today's signal can only be computed after today's close and cannot be filled the same day. Omitting this shift makes backtest returns absurdly inflated - this is look-ahead bias, which will be covered in detail below.
Computing the Four Major Performance Metrics
The net value curve is only an intuitive impression; evaluating a strategy requires numbers.
Continuing the code above, compute the annualized return, annualized volatility, Sharpe ratio and maximum drawdown:
Example
import
numpy
as
np
days
=
len
(
data
)
Number of trading days in the backtest period
cum
=
(
1
- data
[
"Strategy_Return"
]
)
.
cumprod
(
)
Strategy net value curve
Annualized return: compound the period's cumulative return into one year
ann_return
=
cum.
iloc
[
1
]
**
(
252
/ days
)
1
Annualized volatility: standard deviation of daily returns x sqrt(252)
ann_vol
=
data
[
"Strategy_Return"
]
.
std
(
)
- np.
sqrt
(
252
)
Sharpe ratio: excess return per unit of volatility, with the risk-free rate set to 3%
sharpe
=
(
ann_return -
0.03
)
/ ann_vol
Maximum drawdown: the largest drop of net value relative to its historical peak
max_drawdown
=
(
cum / cum.
cummax
(
)
1
)
.
min
(
)
(
f
"Strategy cumulative return: {(cum.iloc[-1] - 1):.2%}"
)
(
f
"Buy-and-hold cumulative return: {(data['Close'].iloc[-1] / data['Close'].iloc[0] - 1):.2%}"
)
(
f
"Annualized return: {ann_return:.2%}"
)
(
f
"Annualized volatility: {ann_vol:.2%}"
)
(
f
"Sharpe ratio: {sharpe:.2f}"
)
(
f
"Max drawdown: {max_drawdown:.2%}"
)
The output is shown below:
策略累计收益: 36.29%
买入持有累计收益: 242.46%
年化收益率: 17.45%
年化波动率: 21.71%
夏普比率: 0.67
最大回撤: -22.47%
The metrics are interpreted in the table below:
| Pointer | Value in This Backtest | How to Read It |
|---|---|---|
| Cumulative Return | 36.29% | Total return over the period, but looking at it alone is easily misled by the period length |
| Annualized Return | 17.45% | Return folded into a per-year figure, directly comparable with any strategy |
| Annualized Volatility | 21.71% | How bumpy the net value is; the larger it is, the worse the holding experience |
| Sharpe Ratio | 0.67 | Generally above 1 is excellent, below 0.5 warrants caution, and 0.67 is moderate |
| Maximum Drawdown | -22.47% | A worst-case loss of 22% - consider whether you can withstand it |
An honest conclusion: over these two years Moutai itself rose 242%, while the dual moving-average strategy significantly underperformed buy-and-hold. A trend strategy misses most of the gains in a one-way rally - this is determined by the strategy's character, not a coding error. This is exactly the point of backtesting: using data to recognize the strategy's applicable boundaries, not to prove it can do everything.
Three Major Backtest Pitfalls
The greatest danger in backtesting is not miscalculation, but results that look 'too beautiful'. The following three pitfalls can make a garbage strategy perform like a money printer in a backtest.
Look-Ahead Bias
Look-ahead bias means using data that could not possibly have been known at the moment the signal was generated.
It is the most hidden and most fatal pitfall; its common forms are compared with the correct way of writing as follows:
| Syntax | Code | Problem |
|---|---|---|
| Error | data["Signal"] = (data["Close"].shift(-1) > data["Close"]).astype(int) | Using tomorrow's closing price to decide today's signal is equivalent to looking at the answer in advance |
| Correct | data["Position"] = data["Signal"].shift(1) | The signal is computed at today's close and executed only the next day, so the signal aligns with executability |
There is only one sentence to the criterion: at every point in time, all data used by the strategy must be no later than that moment.
Using the current day's closing price to compute a moving average and then filling on the same day is likewise a mild form of look-ahead bias - in live trading you cannot guarantee a fill exactly at the close; the rigorous approach is to fill at the next day's open.
Overfitting and Data Snooping
Tuning the moving-average parameters from 50/200 to 48/195 raises the backtest return by 5 points, and another small tweak raises it by 3 more - if you go all the way down this road, what you optimize is not the strategy but the noise in this stretch of historical data.
This is overfitting: the parameters fit the past perfectly but have no predictive power for the future.
Along with it comes data snooping: repeatedly trying different strategies and parameters until one backtest result looks good; the more times you try, the greater the chance of hitting a 'coincidentally good' result.
The defense is in-sample / out-of-sample separation: tune parameters using only an earlier data segment (in-sample), then validate on a later segment never used in optimization (out-of-sample) - out-of-sample performance is what approaches the real level. A more rigorous approach is Walk-Forward validation.
Survivorship Bias
If you backtest using only 'stocks still alive today', you quietly remove all delisted stocks.
Delisted stocks are often the ones that crashed; removing them makes backtest returns systematically too high.
The defense is to include historically delisted stocks in the stock pool, or to use a professional data source that includes delisted stocks.
There is also a hidden pitfall: transaction costs. The backtest above did not account for commissions and slippage; for low-frequency strategies like dual moving averages the impact is still small, but for high-turnover strategies, once a 0.03% commission plus slippage is included, the backtest return can flip from positive to negative. Any backtest should set fee rates consistent with reality.