Member-only story

Exploring Backtesting Python Libraries with a practical example

Xavier Escudero
5 min readFeb 22, 2024

--

Image created with Leonardo.AI

Backtesting allows us to apply entry and exit rules of a strategy to historical data, to simulate the operations that would have been carried out in the past. This allows us to analyze the results of the strategy and evaluate its profitability.

In previous articles we have used the backtrader library, but there are also other quite popular Python backtesting libraries such as Backtesting.py and vectorbt. In the past zipline (the base of quantopian) and pyalgotrade were very popular in the past, but they have remained a little more into oblivion.

In this article we will implement a practical example of the Golden Cross strategy with backtrader, Backtesting.py and vectorbt, using a period of 50 days for the shortest or fastest average, and a period of 200 days for the longest or slowest average.

The Golden Cross strategy is based on the crossing of two moving averages of different periods to determine buy and sell signals. A bullish crossover of the shorter moving average above the longer moving average is considered a buy signal. A bearish crossover of the longer moving average below the shorter moving average is considered a sell signal.

Backtrader

from backtrader import Cerebro
import backtrader as bt
import yfinance as yf


class GoldenCross(bt.Strategy):
params = dict(
p_fast=50,
p_slow=200
)

def __init__(self):
sma1 = bt.ind.SMA(period=self.p.p_fast)
sma2 = bt.ind.SMA(period=self.p.p_slow)
self.crossover = bt.ind.CrossOver(sma1, sma2)

def next(self):
if self.crossover > 0:
if not self.position:
self.buy()
elif self.crossover < 0:
self.close()


if __name__ == "__main__":
starting_cash = 10000
commission = 0.0025

cerebro = Cerebro()
cerebro.broker.setcash(starting_cash)
cerebro.broker.setcommission(commission=commission)

ticker = yf.Ticker('MSFT')
df = ticker.history(period='5y')
cerebro.adddata(bt.feeds.PandasData(dataname=df))
cerebro.addstrategy(GoldenCross)
cerebro.run()
cerebro.plot()

We will not go into much more detail about this code, since we have talked at length in other articles, but we can highlight the…

--

--

Xavier Escudero
Xavier Escudero

Written by Xavier Escudero

Innovation enthusiast, passionate about automation in several fields, like software testing and trading bots

Responses (2)