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.


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


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.


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.


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…


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.


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.


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.