How to Rebalance Your Stock Portfolio with Python

Intrinio
7 min readApr 20, 2022

This blog is the first part of a two-part tutorial designed to demonstrate how Intrinio’s Financial Data API & Alpaca’s Trading API can be used in harmony to build and rebalance a portfolio on an ongoing basis effectively.

Part II is Now Available Here

This tutorial walkthrough will discuss:

  • What are the Benefits of Rebalancing a Stock Portfolio?
  • Stock Weighting Methodologies and Python Snippets

What are the Benefits of Rebalancing a Stock Portfolio?

Investors should periodically rebalance their portfolios to maintain their designated portfolio weights over a long time horizon and across bullish and bearish market conditions.

The main benefits of rebalancing a portfolio are:

  • reduced portfolio risk,
  • increased portfolio diversity, and
  • avoiding mental investment biases.

Reduced Portfolio Risk

“Past performance is not indicative of future results.”
– Every Prospectus Ever

Reducing risk exposure is often the key objective of rebalancing a portfolio.

Rebalancing a portfolio on a recurring basis allows an investor to maintain an established asset allocation amongst their portfolio’s stocks and ultimately reduce risk exposure to a limited number of positions in the portfolio.

For example, imagine on January 1st, 2020, an investor had allocated equal portfolio weightings of 20% for the following five stocks — GME, TSLA, AMD, AMZN, and GOOG — and invested $1000 in each of them. At the time of this writing, each allocation would now roughly be worth the following amounts:

  • GME’s equity is worth $28,279 | GME’s portfolio weighting is 59.7%
  • TSLA’s equity is worth $12,709 | TSLA’s portfolio weighting is 26.8%
  • AMD’s equity is worth $2,581 | AMD’s portfolio weighting is 5.4%
  • GOOG’s equity is worth $2,065 | GOOG’s portfolio weighting is 4.4%
  • AMZN’s equity is worth $1,743 | AMZN’s portfolio weighting is 3.7%

All of the portfolio holdings appreciated in value; however, some, such as GME & TSLA, greatly exceeded their portfolio peers.

If the investor with the above portfolio decided to forego rebalancing the portfolio back to the initial 20% equal weights, they would find their portfolio has become highly concentrated in just two stocks. If GME or TSLA suffered a significant drawdown, the majority of profits in the portfolio would be at risk.

To reduce this portfolio risk, such an investor can rebalance periodically, trimming back outsized positions while simultaneously dollar-cost averaging more subpar performing stocks, ultimately smoothing their overall portfolio returns in the long run.

Overall, by periodically rebalancing, an investor can protect the portfolio’s performance from future drawdowns associated with an equity’s performance reverting to its long-term average due to multiple contractions, reduced growth and negative forward guidance or general macro changes.

Increased Portfolio Diversity

The most important thing you can have is a good strategic asset allocation mix.
– Ray Dalio

Doing in-depth research on equities and setting initial portfolio weights accordingly is a great strategy to ensure the highest possible long-term returns.

However, whether an investor desires to build an all-weather portfolio like Ray Dalio, a traditional 60/40 Equities/Bonds mix, or somewhere in between, over time, the value of the assets in a portfolio will drift away from the target allocations, making the portfolio more concentrated and less diverse.

For an investor to consistently achieve their long-term goals supported by their original investment thesis, they need to ensure the underlying holdings don’t drift too far away from their initial weights. As a result, some investments will need to be sold, and others purchased to ensure the original weightings of the portfolio stay intact.

By rebalancing on a quarterly or annual basis, investors can protect themselves from decreased diversity when one asset class or sector outperforms its portfolio peers. Ultimately, ensuring that when the market’s outlook shines brighter on different sectors or investment factors, an investor consistently benefits from the upside and minimizes their downside.

Avoiding Mental Investment Biases

Over a short time increment, one observes the variability of the portfolio, not the returns.
– Nassim Taleb, Fooled by Randomness

Finally, constructing an initial set of portfolio weights and rebalancing on a recurring basis assists investors with maintaining a level head and steady plan for long-term success.

Without a robust long-term strategy and the proper execution of such a strategy, volatility in the markets will subject both institutional and retail investors to make emotional decisions not logical ones, more often than not to the detriment of their long-term performance and overall portfolio returns.

These emotional decisions become further unavoidable as a select few of a portfolio’s holdings grow more significant than their peers and seemingly control the returns of the entire portfolio.

By rebalancing back to the initial weights of the portfolio and properly allocating profits when necessary, an investor can ease themselves of mental burdens spurred by market movements and avoid checking stock prices every minute of every day. In the end, scheduled rebalancing will provide an investor with more time to perform in-depth market research and discover their next ten-bagger.

Stock Weighting Methodologies and Python Snippets

The following sections will illustrate three rebalance methodologies and show an investor how to use Python & Intrinio’s Financial APIs to quickly calculate portfolio weightings for their holdings once they decide on the stock they desire to own.

Three of the more popular portfolio weightings and rebalance methodologies are:

  • Equal Weight,
  • Market Cap Weight, and
  • Efficient Frontier Weight.

Equal Weight Rebalancing

Equal weight rebalancing is typically identified as a value-based methodology.

This rebalance method will ultimately result in the investor trimming down winning positions and dollar-cost averaging out-of-favor positions. The tradeoff is that equal weight doesn’t allow you to let your “winners run.”

However, investors making this tradeoff appreciate that a well-balanced and adequately allocated portfolio often results in lower drawdowns and more opportunity to include a future outperforming equity in their portfolio.

The following simple _target_equal_weights function accepts a list of equities and returns a dictionary containing a ticker & portfolio weight key-value pair.

Market Cap Rebalancing

Unlike an equal weight rebalance, market weight rebalancing is a momentum-based methodology.

As the portfolio’s underlying stock prices (market caps) shift around in value, stocks that increase in performance (or increase their overall share price/market cap) will receive more funds in the next allocation, and the position sizes of poorer performers may be trimmed down or left the same.

Investors utilizing this rebalancing methodology typically have a higher risk tolerance and appreciate the increased volatility that can occur with a concentrated portfolio. This methodology will naturally increase allocations into a smaller number of holdings, particularly if a portfolio includes companies with very high valuations.

The following Python scripts demonstrates how to use Intrinio’s Historical Data for Company endpoint to ingest each underlying securities’ market cap and structure the weightings accordingly.

The _market_cap function accepts a ticker as an argument and returns the latest daily market associated with it.

The _market_caps function accepts a list of tickers, iterates and retrieves the market cap of each ticker, and then returns a dictionary containing a ticker & market cap key-value pair.

Finally, the _target_market_cap_weights function accepts a list of tickers, and uses the above helper functions to retrieve their associated market caps. Once all market caps are retrieved, the function calculates the individual weighting of each stock by dividing its market cap by the sum of all market caps in the portfolio, it then returns a dictionary containing a ticker & portfolio weight key-value pair.

Efficient Frontier Rebalancing

For investors looking to take a more quantitative focus on their portfolio allocation and rebalance methodologies, efficient frontier weighting is an excellent option to maximize returns while reducing risk.

The Efficient Frontier methodology provides a set of optimal portfolios that offers the highest expected returns at differing levels of risk depending on the bundle of equities you are considering allocating towards.

Any portfolio mix inside the efficient frontier is sub-optimal because its risk/reward attributes do not exceed those on the Efficient Frontier curve.

To formulate an efficient frontier curve and retrieve the optimal portfolio weights, you need to calculate your portfolio holdings’ expected returns and standard deviation of returns.

Fortunately, there is already a great library available called PyPortfolioOpt that will help us perform these tasks efficiently and ultimately provide us with optimal weightings of our holdings for the highest future returns.

_hist_end_of_day_prices is a a recursive function that utilizes Intrinio’s Stock Prices by Security API’s paging functionality to retrieve and return a Pandas DataFrame containing a single column containing the stock’s full adjusted close end-of-day price history. The column name is adjusted to reflect the name of the ticker to ensure PyPortfolioOpt is able to properly assign portfolio weights.

The @retry decorator ensures that data is returned regardless of a user hitting their API limitations.

_hist_stock_prices_dataset iterates through a list of tickers and returns a Pandas DataFrame where each column merged in represents the associated stock price history returned from the _hist_end_of_day_prices. In order to process this data with PyPortfolioOpt the order of stock data is then reversed so that the first row is the oldest available stock date and the last row is the latest.

We are then able to gather the inputs needed to formulate our Efficient Frontier by feeding the the Pandas DataFrame containing our historical adjusted close end-of-day price history into the two PyPortfolioOpt methods mean_historical_return and CovarianceShrinkage.

Now, using PyPortfolioOpt’s EfficientFrontier class, we can calculate our Efficient Frontier and then ultimately extract the clean portfolio weights that are predicted to maximize our portfolio’s Sharpe Ratio moving forward.

To continue on with this tutorial Part II is Now Available Here

Where to access clean market data

At Intrinio, we’re recognized for being one of the top data providers that specializes in high-quality data, immediate customer service, and modern tools for a variety of fintech platforms and businesses. Our dedicated team wants to help you find the best data package that fits your unique needs. Reach out to one of our data specialists today to find out more about our equities market data packages. And to learn more about all our financial services and data please visit intrinio.com.

--

--

Intrinio

High-quality financial data. Tools built for developers. First-class, US-based support. Data doesn’t have to be hard or expensive.