In this post, we will take a look at how to perform a simple 60/40 portfolio rebalancing strategy in Backtrader. For those of you that are unaware, the 60/40 portfolio is almost like the “hello world” of portfolios. It describes the ratio of stocks to bonds in the portfolio. In other words, a ratio of 60% stocks and 40% bonds. More on that later…
Diversification and Portfolio Rebalancing
The old saying goes, “don’t put all of your eggs in one basket”. That is often good advice for investing. In our world, we can think of the eggs are our selected investments and asset classes are our baskets. If one basket breaks (e.g. stocks) then (hopefully) another basket will be stronger (e.g. bonds). So the idea is to select a mixture of non-correlated assets. (assets which do not go up and down at the same time!).
Rebalancing a portfolio is the simple exercise of making sure you don’t fill one basket with too many eggs. At regular intervals, we take a look at our portfolio “weight” and decide whether we need to reduce or increase the size of each asset in order to balance the baskets.
The 60/40
The general idea behind selecting a ratio of 60% stocks and 40% bonds is that traditionally, they have been inversely correlated. This means that when the stock market cools off, bond prices tend to rise and act as a hedge against losing your shirt. The portfolio is weighted towards stocks as they tend to appreciate more over the long run.
Of course, nothing is perfect and we are starting to see some commentators speculate that the inverse correlation between stocks and bonds is ready to die. As such, readers should not treat this overview as an endorsement or basis for an investment decision.
Requirements
This article builds on the shoulders of some other posts which use Alpha Vantage as a data source. As such, this article will not cover the mechanics of downloading and ingesting the data. To learn more about how this is done, please take a look at these articles.
API Key
If you have not read the articles above, you will need to get yourself an API key or swap out the data feeds to use this code.
The API key will grant you lifetime access to Alpha Vantage data. Head over to the following link and sign up.
Source: https://www.alphavantage.co/support/#api-key
Adjusted Data
This post will make use of adjusted price data which will allow us to easily simulate dividend re-investment. For more information regarding dividends and adjusted data, see these articles:
- Backtesting 101: Dividends and Adjustments
- Backtrader: Manage Dividends and Splits with Adjusted Close Data
Example Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
''' Author: www.backtest-rookies.com MIT License Copyright (c) 2020 backtest-rookies.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ''' import backtrader as bt from datetime import datetime import pandas as pd import numpy as np from alpha_vantage.timeseries import TimeSeries # IMPORTANT! # ---------- # Register for an API at: # https://www.alphavantage.co/support/#api-key # Then insert it here. Apikey = 'INSERT YOUR API KEY' def adjust(date, close, adj_close, in_col, rounding=4): ''' If using forex or Crypto - Change the rounding accordingly! ''' try: factor = adj_close / close return round(in_col * factor, rounding) except ZeroDivisionError: print('WARNING: DIRTY DATA >> {} Close: {} | Adj Close {} | in_col: {}'.format(date, close, adj_close, in_col)) return 0 def alpha_vantage_daily_adjusted(symbol_list, compact=False, debug=False, rounding=4, *args, **kwargs): ''' Helper function to download Alpha Vantage Data. My framework expects a nested list to be returned containing the pandas dataframe and the name of the feed. ''' data_list = list() size = 'compact' if compact else 'full' for symbol in symbol_list: if debug: print('Downloading: {}, Size: {}'.format(symbol, size)) # Submit our API and create a session alpha_ts = TimeSeries(key=Apikey, output_format='pandas') # Get the data data, meta_data = alpha_ts.get_daily_adjusted(symbol=symbol, outputsize=size) #data, meta_data = alpha_ts.get_daily(symbol=symbol, outputsize=size) if debug: print(data) #Convert the index to datetime. data.index = pd.to_datetime(data.index) # Adjust the rest of the data data['adj open'] = np.vectorize(adjust)(data.index.date, data['4. close'], data['5. adjusted close'], data['1. open'], rounding=rounding) data['adj high'] = np.vectorize(adjust)(data.index.date, data['4. close'], data['5. adjusted close'], data['2. high'], rounding=rounding) data['adj low'] = np.vectorize(adjust)(data.index.date, data['4. close'], data['5. adjusted close'], data['3. low'], rounding=rounding) # Extract the colums we want to work with and rename them. data = data[['adj open', 'adj high', 'adj low','5. adjusted close','6. volume']] data.columns = ['Open','High','Low','Close','Volume'] data_list.append((data, symbol)) return data_list class RebalanceStrategy(bt.Strategy): params = (('assets', list()), ('rebalance_months', [1,6]),) # Float: 1 == 100% def __init__(self): self.rebalance_dict = dict() for i, d in enumerate(self.datas): self.rebalance_dict[d] = dict() self.rebalance_dict[d]['rebalanced'] = False for asset in self.p.assets: if asset[0] == d._name: self.rebalance_dict[d]['target_percent'] = asset[1] def next(self): for i, d in enumerate(self.datas): dt = d.datetime.datetime() dn = d._name pos = self.getposition(d).size if dt.month in self.p.rebalance_months and self.rebalance_dict[d]['rebalanced'] == False: print('{} Sending Order: {} | Month {} | Rebalanced: {} | Pos: {}'.format(dt,dn,dt.month, self.rebalance_dict[d]['rebalanced'], pos )) self.order_target_percent(d, target=self.rebalance_dict[d]['target_percent']/100) self.rebalance_dict[d]['rebalanced'] = True # Reset if dt.month not in self.p.rebalance_months: self.rebalance_dict[d]['rebalanced'] = False def notify_order(self, order): date = self.data.datetime.datetime().date() if order.status == order.Completed: print('{} >> Order Completed >> Stock: {}, Ref: {}, Size: {}, Price: {}'.format( date, order.data._name, order.ref, order.size, 'NA' if not order.price else round(order.price,5) )) def notify_trade(self, trade): date = self.data.datetime.datetime().date() if trade.isclosed: print('{} >> Notify Trade >> Stock: {}, Close Price: {}, Profit, Gross {}, Net {}'.format( date, trade.data._name, trade.price, round(trade.pnl,2), round(trade.pnlcomm,2))) startcash = 10000 #Create an instance of cerebro cerebro = bt.Cerebro() # strategy Params strat_params = [ ('VUKE.L', 30), ('VUSA.L', 30), ('VGOV.L', 20), ('INXG.L', 20) ] symbol_list = [x[0] for x in strat_params] #Add our strategy cerebro.addstrategy(RebalanceStrategy, assets=strat_params) data_list = alpha_vantage_daily_adjusted( symbol_list, compact=False, debug=False) for i in range(len(data_list)): data = bt.feeds.PandasData( dataname=data_list[i][0], # This is the Pandas DataFrame name=data_list[i][1], # This is the symbol timeframe=bt.TimeFrame.Days, compression=1, fromdate=datetime(2014,1,1), todate=datetime(2020,1,1) ) #Add the data to Cerebro cerebro.adddata(data) # Set our desired cash start cerebro.broker.setcash(startcash) cerebro.broker.set_checksubmit(False) # Run over everything cerebro.run() #Get final portfolio Value portvalue = cerebro.broker.getvalue() pnl = portvalue - startcash #Print out the final result print('Final Portfolio Value: ${}'.format(portvalue)) print('P/L: ${}'.format(pnl)) #Finally plot the end results cerebro.plot(style='candlestick') |
Code Commentary
The strategy itself is a relatively small part of the overall code but we will mainly focus on it as the data download and general setup of Backtrader is covered in other articles. The strategy will rebalance each asset on the first call of next()
when the month is equal to the given “rebalance” months. The rebalance months can be adjusted as strategy parameters with 1 (Jan) and 6 (Jun) as the defaults.
checksubmit
The one part of the setup that is worth mentioning is checksubmit
. We set this parameter to False
which means that orders will not be checked to see if you can afford it before submitting them. We need that as we might be sending orders to increase the weight of an asset before decreasing another. More on that later…
init()
During init()
we simply loop through each of the data feeds and assign the given ideal weights to each. We also add a simple boolean flag that we will use for tracking whether we have rebalanced each asset. Matching of the weights to each asset is done by comparing the data feed name to name in the asset list that is passed to the strategy on startup.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# strategy Params strat_params = [ ('VUKE.L', 30), ('VUSA.L', 30), ('VGOV.L', 20), ('INXG.L', 20) ] symbol_list = [x[0] for x in strat_params] #Add our strategy cerebro.addstrategy(RebalanceStrategy, assets=strat_params) |
next()
During next()
we loop through each datafeed
and check whether the most recent datetime
is a match for our target rebalance months. If it is, we send an order to rebalance and then update our rebalance_dict
so we don’t try and rebalance again this month.
Calculating how much we need to buy or sell to rebalance is easy. We can simply let Backtrader handle it with the built-in order_target_percent()
function. This is super handy for rebalancing. It will perform the calculations you need and either buy or sell an asset to get you to the target weight. This is also why the checksubmit
argument is needed that we discussed earlier. Due to the way we loop through all the data feeds, there is no guarantee that the first asset we loop through is an asset we want to sell before increasing the weight of another. For this reason, we want to be able to send an order to increase the weight of an asset before looping through to the next asset.
Finally, once the current month is not equal to one of our rebalance months, we can safely update the rebalance_dict
and set the asset to False
again for rebalancing.
Results
Running the code, you should see something like this on the charts. Note that not all assets will be bought or sold during each rebalance cycle. They may already be close to the target weight and buying or selling would take you further from it. In these cases, no operation needs to be performed.
thank you for your good job, I have learned a lot, but I still have a question, how to set a stop loss in the rebalance strategy?