Backtrader – Portfolio Rebalancing with Alpha Vantage

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.

  1. Replacing Quandl Wiki Data with Alpha Vantage
  2. Backtrader: Alpha Vantage Data: Direct Ingest

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:

Example Code

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.

next()

During next() we loop through each datafeed and check whether the most recent datetimeis 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_dictand set the asset to Falseagain 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.

Find This Post Useful?

If this post saved you time and effort, please consider support the site! There are many ways to support us and some won’t even cost you a penny. 

Backtest Rookies is a registered with Brave publisher!

Brave users can drop us a tip.

Alternatively, support us by switching to Brave using this referral link and we will receive some BAT! 


https://brave.com/bac691

Referral Link

Enjoying the content and thinking of subscribing to Tradingview? Support this site by clicking the referral link before you sign up! 

https://tradingview.go2cloud.org/SHpB


Donate with PayPal using any payment method you are comfortable with! 


3HxNVyh5729ieTfPnTybrtK7J7QxJD9gjD

0x9a2f88198224d59e5749bacfc23d79507da3d431

M8iUBnb8KamHR18gpgi2sSG7jopddFJi8S