40 stocks x 1512 trading days, 2018-01-02 to 2023-10-18
STK00 STK01 STK02 STK03 STK04 STK05
date
2018-01-02 0.021 -0.008 0.013 0.013 0.008 0.000
2018-01-03 -0.012 0.001 -0.029 0.006 -0.021 -0.027
2018-01-04 0.013 0.006 0.016 0.005 0.007 0.028
2018-01-05 0.000 0.003 -0.013 -0.003 0.027 -0.029
2018-01-08 -0.034 -0.007 -0.021 -0.014 -0.003 -0.019
How to backtest a trading strategy in Python with bt
A backtest estimates what a strategy would have earned in the past.
I wanted to write the shortest backtest I could, and also show how fast you can backtest something. Of course, this may not be the most realistic way to backtest, but it is at least the shortest and fastest I can do with the bt package. I test a monthly momentum strategy, which buys the stocks with the highest past returns.
Step 1. Loading the data
I simulate almost six years of daily returns for 40 stocks so you can get the same data and run the same tests. I wanted momentum to be a pure edge that the backtest will show. The block below loads returns.csv, made by a separate script.
Each stock’s daily return is a market move shared by all stocks, the stock’s own part of the expected return, and noise,
\[r_{i,t} = m_t + e_{i,t} + \varepsilon_{i,t}, \qquad e_{i,t} = 0.997\,e_{i,t-1} + \sqrt{1 - 0.997^2}\;\sigma_e\,u_{i,t},\]
where the market move \(m_t\) averages 0.05% a day with a standard deviation of 1%, and the noise \(\varepsilon_{i,t}\) has a standard deviation of 1.2%. The stock’s own part retains 99.7% of yesterday’s value each day.
That persistence is the momentum, and all these numbers are assumptions.
import pandas as pd
# The dates are in the first column of the file. index_col=0 makes that column the row
# index, and parse_dates=True reads the text as real dates, so .date() works below.
returns = pd.read_csv("returns.csv", index_col=0, parse_dates=True)
number_of_days = returns.shape[0] # shape is (rows, columns), and one row is one day
number_of_stocks = returns.shape[1] # one column is one stock
first_day = returns.index[0].date() # .date() drops the midnight time stamp
last_day = returns.index[-1].date() # position -1 counts back from the end
print(f"{number_of_stocks} stocks x {number_of_days} trading days, "
f"{first_day} to {last_day}")
# iloc selects by position, so this is the first five days and the first six stocks.
# print shows the table in a script as well as in a notebook.
corner_of_returns = returns.iloc[:5, :6].round(3)
print(corner_of_returns.to_string())Each row is a day, each column a stock.
Step 2. Defining the strategy
Once a month, I rank stocks by their past-year return and hold the top eight equally weighted.
I lag the ranking by a day to avoid look-ahead bias, since I am still trying to make the backtest somehow realistic. The strategy ranks on the latest close before the rebalance day and trades at the rebalance day’s close.
In bt, the lag is one argument.
import bt
# One year of calendar time does two jobs below: it is the history a stock needs before it
# can be ranked at all, and it is the period the momentum ranking is measured over.
RANKING_WINDOW = pd.DateOffset(months=12)
RANKING_LAG = pd.DateOffset(days=1) # rank on the day before the trade, excluding the trade day
# bt runs this list in order on every day and stops as soon as a step returns False. That
# is how RunMonthly keeps the rest of the steps to one day a month.
momentum_steps = [
bt.algos.RunMonthly(), # rebalance once a month
bt.algos.SelectAll(), # consider every stock
bt.algos.SelectHasData(lookback=RANKING_WINDOW, # look back one year and require...
min_count=252), # ...~252 valid daily prices before ranking
bt.algos.SelectMomentum(n=8, # of those, keep the 8 with the highest...
lookback=RANKING_WINDOW, # ...past-12-month return...
lag=RANKING_LAG), # ...read up to the day BEFORE
bt.algos.WeighEqually(), # weight those 8 equally
bt.algos.Rebalance()] # trade to those weights
momentum = bt.Strategy("Momentum", momentum_steps)
# A benchmark to beat: hold all 40 stocks, equally weighted, rebalanced monthly. The same
# steps as above, without the two that pick and rank a subset.
market_steps = [
bt.algos.RunMonthly(),
bt.algos.SelectAll(),
bt.algos.WeighEqually(),
bt.algos.Rebalance()]
market = bt.Strategy("Market", market_steps)Step 3. Running the backtest and charging for trading
bt works on prices, so I first turn the returns into prices starting at 100,
\[P_t = P_{t-1}\,(1 + r_t),\]
so a return of 1% and then one of −2% take 100 to 98.98.
Then I run the strategy twice, without a trading commission and with one.
I charge a flat 10 basis points (0.10%) of each trade’s value. This is an assumption, an approximation, and the cost can be much, much greater in real trading.
import io
import contextlib
# 1 + r is each day's growth factor, and cumprod multiplies the factors down each column
growth_factors = 1 + returns
prices = 100 * growth_factors.cumprod() # each path is based at 100 dollars, so stocks are comparable
def trading_cost(quantity, price):
"""The commission bt charges on one trade: 10 basis points of its value.
quantity is negative when the strategy sells, so abs treats a sale like a purchase.
Selling 100 shares at 20 dollars costs 100 * 20 * 0.0010 = 2 dollars.
"""
return abs(quantity) * price * 0.0010
# The same momentum strategy is run twice, once free of commission and once charged for
# it, so the difference between those two results is the cost of trading and nothing else.
momentum_gross = bt.Backtest(momentum, prices, name="Momentum",
integer_positions=False)
momentum_net = bt.Backtest(momentum, prices, name="Momentum_net",
commissions=trading_cost, integer_positions=False)
market_test = bt.Backtest(market, prices, name="Market",
integer_positions=False)
with contextlib.redirect_stderr(io.StringIO()): # suppress bt's progress bar
results = bt.run(momentum_gross, momentum_net, market_test)Step 4. Reading the result
Momentum and Momentum_net are the strategy before and after the commission.
# The stats table holds one row per measure and one column per run, so .loc picks the five
# rows worth showing here and keeps all three columns.
headline_measures = ["total_return", "cagr", "daily_sharpe", "max_drawdown", "calmar"]
headline_stats = results.stats.loc[headline_measures].round(3)
print(headline_stats.to_string()) Momentum Momentum_net Market
total_return 0.658037 0.616649 0.296259
cagr 0.091201 0.08645 0.045808
daily_sharpe 0.609221 0.582546 0.349611
max_drawdown -0.18793 -0.18946 -0.22415
calmar 0.485294 0.456298 0.204365
Momentum grew 9.1% a year before the commission and 8.6% after, against 4.6% for the market, and its worst drawdown was 18.8% against 22.4%.
# bt's turnover is the smaller of the day's purchases or sales, divided by the portfolio's
# value. dropna guards against a day where that ratio cannot be formed, and this panel has none.
turnover = results.backtests["Momentum"].turnover.dropna()
# Turnover is zero between rebalances and on the first purchase, which sells nothing. A
# True/False mask inside .loc keeps the days with positive turnover, so the average is per
# rebalance after the first purchase rather than per calendar day.
rebalance_days = turnover > 0
average_turnover = turnover.loc[rebalance_days].mean()
gross = results.stats.loc["cagr", "Momentum"] # yearly growth rate before costs
net = results.stats.loc["cagr", "Momentum_net"] # the same run after the 10 bps charge
cost_in_cagr = (gross - net) * 100 # the difference, in percentage points
print(f"Average turnover per rebalance: {average_turnover:.0%} of the portfolio")
print(f"Gross {gross:.1%}/yr -> net {net:.1%}/yr "
f"(cost in CAGR: {cost_in_cagr:.2f} percentage points/yr)")Average turnover per rebalance: 22% of the portfolio
Gross 9.1%/yr -> net 8.6%/yr (cost in CAGR: 0.48 percentage points/yr)
About 22% of the portfolio turns over at each rebalance, so the commission costs 0.48 percentage points a year.
The chart below draws the value of each run over time.
import matplotlib.pyplot as plt
RED, TEAL, ORANGE, GREY = "#C0392B", "#17868A", "#D2822B", "#888888"
# The site's chart colours: a cream background, a light grid and a pale frame, so every chart
# on the site has the same look.
BG, INK, GRID, SPINE, AXIS_TEXT = "#FCEFE3", "#1f1f1f", "#EADCCC", "#D5C6B4", "#4a4a4a"
def style_chart(figure, axis):
"""Give a finished chart the site's cream background, light grid and pale frame."""
figure.patch.set_facecolor(BG)
axis.set_facecolor(BG)
axis.grid(True, axis="y", color=GRID, lw=1.0)
axis.set_axisbelow(True)
for side in ("top", "right"):
axis.spines[side].set_visible(False)
for side in ("left", "bottom"):
axis.spines[side].set_color(SPINE)
axis.tick_params(axis="both", length=0, colors=INK, pad=6)
axis.xaxis.label.set_color(AXIS_TEXT)
axis.yaxis.label.set_color(AXIS_TEXT)
axis.title.set_color(INK)
# Each legend entry in the colour of what it labels: a line's colour or a bar's fill.
# get_legend() returns None when the chart has no legend.
legend = axis.get_legend()
if legend is not None:
for text, handle in zip(legend.get_texts(), legend.legend_handles):
if hasattr(handle, "get_color"):
text.set_color(handle.get_color())
else:
text.set_color(handle.get_facecolor())
# bt draws all three equity curves at once and passes the colours on to pandas, one per run
axis = results.plot(title="Momentum vs market (simulated data)", color=[TEAL, ORANGE, GREY])
axis.set_ylabel("value, starting at 100")
axis.legend(frameon=False)
style_chart(axis.get_figure(), axis)
# Saved to disk because the file is also the thumbnail the post lists in its frontmatter
plt.savefig("momentum_backtest_simulated.png", dpi=120, bbox_inches="tight", facecolor=BG)
plt.show()
Momentum beat the market before and after the commission.
Limitations
There is slippage, capacity, and overfitting, and real data contains more noise and is not as clear as this simulated data.
So the conclusion is that this was the short way, or maybe the fastest way, to backtest something to gain some intuition about whether something works or not.
References
Jegadeesh, N., & Titman, S. (1993). Returns to buying winners and selling losers: Implications for stock market efficiency. The Journal of Finance, 48(1), 65–91. https://doi.org/10.1111/j.1540-6261.1993.tb04702.x
Morissette, P. (n.d.). bt: Flexible backtesting for Python [Documentation]. https://pmorissette.github.io/bt/
Disclaimer: a teaching example on synthetic data. The returns here were generated, and the edge was planted on purpose. Not investment advice. Past performance does not guarantee future returns.