# Backtesting a Cross-Sectional Mean Reversion Strategy in Python

In this post we will look at a cross-sectional mean reversion strategy from Ernest Chan’s book Algorithmic Trading: Winning Strategies and Their Rationale and backtest its performance using Backtrader.

Typically, a cross-sectional mean reversion strategy is fed a universe of stocks, where each stock has its own relative returns compared to the mean returns of the universe. A stock with a positive relative return is shorted while a stock with a negative relative return is bought, in hopes that a stock that under or outperformed the universe will soon revert to the mean of the universe.

The strategy described in Chan’s book is as follows: Everyday, every stock $i$ in the universe is assigned a weight $w_i$ according to the following formula:

$w_i = -(r_i - r_m) / \sum_k | r_k - r_m |$

Where $r_m$ is the mean returns of the universe. This weight will tell us how much of the portfolio will be long or short that particular stock. As we can see in the formula, the farther an individual stock’s returns are from the mean, the greater its weight will be.

## Collecting Data

In order to test this strategy, we will need to select a universe of stocks. In this case we will use the S&P 500. So we don’t have to re-download the data between backtests, lets download daily data for all the tickers in the S&P 500. We’ll start by reading in the list of tickers from Wikipedia, and save them to a file spy/tickers.csv.

import pandas as pd
import numpy as np
from datetime import datetime

table = data
tickers = table[1:].tolist()
pd.Series(tickers).to_csv("spy/tickers.csv")


Now that we have a the list of tickers, we can download all of the data from the past 5 years. We will use concurrent.futures.ThreadPoolExecutor to speed up the task.

from concurrent import futures

end = datetime.now()
start = datetime(end.year - 5, end.month , end.day)

df.to_csv(f"spy/{ticker}.csv")



Now we should have all our data in the spy directory! Now we can get to writing the strategy.

## Strategy

Here is the full strategy using the above formula.

class CrossSectionalMR(bt.Strategy):
def prenext(self):
self.next()

def next(self):
# only look at data that existed yesterday
available = list(filter(lambda d: len(d), self.datas))

rets = np.zeros(len(available))
for i, d in enumerate(available):
# calculate individual daily returns
rets[i] = (d.close- d.close[-1]) / d.close[-1]

# calculate weights using formula
market_ret = np.mean(rets)
weights = -(rets - market_ret)
weights = weights / np.sum(np.abs(weights))

for i, d in enumerate(available):
self.order_target_percent(d, target=weights[i])


Note: It is worth mentioning that Backtrader only calls a strategy’s next() method when it has a price tick from every data feed. This means that by default the strategy will not trade if, for example, a company in the universe has not started trading publicly yet. We can circumvent this issue by calling next() in prenext() and then applying the weight calculation formula to only stocks in which we have data to.

## Backtesting

We’re ready to backtest! Lets see how this strategy works with an initial capital of \$1,000,000.

cerebro = bt.Cerebro(stdstats=False)
cerebro.broker.set_coc(True)

for ticker in tickers:
data = bt.feeds.GenericCSVData(
fromdate=start,
todate=end,
dataname=f"spy/{ticker}.csv",
dtformat=('%Y-%m-%d'),
openinterest=-1,
nullvalue=0.0,
plot=False
)

cerebro.broker.setcash(1_000_000)
results = cerebro.run()

print(f"Sharpe: {results.analyzers.sharperatio.get_analysis()['sharperatio']:.3f}")
print(f"Norm. Annual Return: {results.analyzers.returns.get_analysis()['rnorm100']:.2f}%")
print(f"Max Drawdown: {results.analyzers.drawdown.get_analysis()['max']['drawdown']:.2f}%")
cerebro.plot()

Sharpe: 1.173
Norm. Annual Return: 7.98%
Max Drawdown: 6.58% ## Conclusion

As we can see the algorithm did fairly well! It had a Sharpe ratio of 1.17 with a normalized annual return of 7.9%. Although the returns might not be much better then buying and holding SPY, the volatility is greatly reduced. We do, however, have to take a few things into consideration:

1. The dataset we are using may have a slight survivorship bias as it does not contain companies who where in the S&P 500 5 years ago, but have since been removed.

2. The above backtest assumes that it will compute weights at market close then be able to trade at the exact market close price. In reality we wouldn’t be able to compute weights with the exact close price, but it would be pretty close.

3. Since this particular algorithm trades every stock in the universe at once, the investor will need a large amount of capitol to accurately match the computed weights.