Backtesting made Easy: Buy and Hold Strategy with Backtrader

Backtrader is powerful library facilitating backtest in Python. In this article, I explain method to implement Buy and Hold strategy and perform backtest using data of past 10 years simply.

1. Preparation of Environment

Installation of library

# install requirement
%pip install backtrader yfinance matplotlib

2. Import of Library

Import necessary libraries

# import libs
import datetime
import backtrader as bt
import yfinance as yf
import matplotlib.pyplot as plt

3. Parameter Setting

Set necessary parameters.

## ticker and ratio
TICKERS = {"VTI": 0.4, "BND": 0.4, "GLD": 0.2}
## start date and end date
FROMDATE = datetime.datetime(2014, 7, 1)
TODATE = datetime.datetime(2024, 7, 1)

4. Implement Strategy

Strategy - Backtrader

python backtesting trading algotrading algorithmic quant quantitative analysis

www.backtrader.com
# Definition of Buy and Hold strategy
class BuyAndHold(bt.Strategy):
def __init__(self):
pass
def next(self):
if not self.position:
for data in self.datas:
allocation= data.target
cash_for_asset = self.broker.get_cash() * allocation
self.buy(data=data, size=int(cash_for_asset // data.close[0]))

5. Execute Backtest

Perform data reading, and execute backtest.

# Initialization of backtrader
cerebro = bt.Cerebro()
cerebro.broker.set_cash(10000)
cerebro.addstrategy(BuyAndHold)
# Read data from yahoofinance
for ticker, target in TICKERS.items():
data = bt.feeds.PandasData(
dataname=yf.download(ticker, start=FROMDATE, end=TODATE)
)
data.target = target
cerebro.adddata(data, name=ticker)
# Execution of backtest
print('Starting Portfolio Value: %.2f' % cerebro.broker.getvalue())
cerebro.run()
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue())

Execution Result

Starting Portfolio Value: 10000.00
Final Portfolio Value: 17274.97

6. Visualize result of backtest

Since backtrader has built-in visualization function, execute it. It can be read that buy is performed only at beginning.

Plotting - Backtrader

python backtesting trading algotrading algorithmic quant quantitative analysis

www.backtrader.com
plt.rcParams['figure.figsize'] = [12, 10]
cerebro.plot()
Backtest Result of Buy&Hold
Backtest Result of Buy&Hold