Buy and Hold Trading Strategy. Calculating the performance of the... | by Roman Orac | Towards Data Science

Buy and Hold strategy is when you simply buy an asset with the first incoming data point and see what the portfolio value is available with the last data point.
The Buy and Hold strategy is sometimes also used as a baseline for testing the performance of other strategies. If a carefully crafted logic cannot beat a simple buy and hold approach, the strategy is probably not worth a dime.
While it is not hard to measure the performance of the Buy and Hold strategy by hand, it is useful to have a backtesting framework — you can further work on improving the strategy and it usually comes with plotting capability.
See my other articles about this topic:
romanorac.medium.com
Here are a few links that might interest you:
- Labeling and Data Engineering for Conversational AI and Analytics- Data Science for Business Leaders [Course]- Intro to Machine Learning with PyTorch [Course]- Become a Growth Product Manager [Course]- Deep Learning (Adaptive Computation and ML series) [Ebook]- Free skill tests for Data Scientists & Machine Learning Engineers
Some of the links above are affiliate links and if you go through them to make a purchase I’ll earn a commission. Keep in mind that I link courses because of their quality and not because of the commission I receive from your purchases.
Backtrader is an open-source Python framework for backtesting and trading. It allows you to focus on writing reusable trading strategies, indicators and analyzers instead of having to spend time building infrastructure.
Before installing it, make you have TA-LIB dependency installed:
# Mac OS Xbrew install ta-lib# see https://github.com/mrjbq7/ta-lib for other platforms
To install Backtrader is as simple as with every python package:
pip install backtrader[plotting]
We are going to calculate how much would we gain if we would invest $10.000 in Microsoft on the 1st of January 2010 and hold it till now.
We only need a few lines of code to implement the Buy and Hold Strategy with Backtrader.
Explanation of the code below:
start method sets the initial amount of cash.
the nextstart method is called exactly once with the first data point. This is perfect for implementing buy and hold strategy.
All the available cash is used to buy a fixed amount of stocks. It is truncated to int as all the brokers don’t support the fractional stocks.
the returns are calculated in the stop method, using the current value of the portfolio and the initial amount of cash.
import backtrader as btclass BuyAndHold_Buy(bt.Strategy):    def start(self):        # set the starting cash        self.val_start = self.broker.get_cash()     def nextstart(self):        # Buy stocks with all the available cash        size = int(self.val_start / self.data)        self.buy(size=size)    def stop(self):        # calculate the actual returns        self.roi = (self.broker.get_value() / self.val_start) - 1.0        print("ROI: %.2f, Cash: %.2f" % (100.0 * self.roi, self.broker.get_value()))
As already mentioned above, we would like to calculate how much would we gain by holding Microsoft stock for ~10 years.
We define the ticker, date parameters and initialize the data feed:
from datetime import datetimedata = bt.feeds.YahooFinanceData(    dataname="MSFT", fromdate=datetime(2010, 1, 1), todate=datetime(2020, 10, 23))
Then we initialize the Cerebro engine:
cerebro = bt.Cerebro()
Add the data feed to the engine:
cerebro.adddata(data)
Add the strategy to the engine:
cerebro.addstrategy(BuyAndHold_Buy, "HODL")
Set the cash:
cerebro.broker.setcash(100000.0)
Run the backtest:
cerebro.run()# The outputROI: 788.00, Cash: 88800.40
We would make a crazy return of 788%. If we could only go back in time 😊
We all heard the saying “A picture is worth a thousand words”. This is where Backtrader shines.
Backtrader can visualize a strategy with entry and exit points. In our example, we only have one entry point so the trading strategy visualization won’t be as dramatic. But we would need to spend a considerable amount of time to make a visualization that we get out of the box with Backtrader
Let’s try it (command below works in JupyterLab):
cerebro.plot(iplot=False)
To learn more about the Buy and Hold strategy, visit Backtraders docs.
As usual, you can download this Jupyter Notebook to try examples on your machine.
Follow me on Twitter, where I regularly tweet about Data Science and Machine Learning.