How to Rebalance Your Stock Portfolio with Alpaca Trading API ~ Part II
The walkthrough in Part I of this two-part tutorial demonstrated how to calculate portfolio weights. This Part II walkthrough will show you how to use these weights to automatically invest and rebalance a portfolio with Alpaca’s Trading API.
What is the Alpaca Trading API?
The Alpaca Trading API is an API interface that allows you to programmatically buy, sell, short stocks, and crypto — the best part being every trade executed is commission-free.
Why use Alpaca Trading API?
Between its ease of use and comprehensive features, there are a few main reasons to use Alpaca’s trading API. What makes it perfect for our walkthrough today are the following highlights:
- No Fee Trading
- Supports Fractional Shares
- Simple API and SDK Offerings & Helpful Documentation
- Paper Trading for Trading Practice & Model Integration
Getting Started with Alpaca Trading API
To follow along with this walkthrough, you will need to sign up for an Alpaca API account and retrieve your Alpaca API Key and Alpaca Secret API Key.
You can sign up here.
After signing up and logging in, you will want to navigate to the upper left corner of Alpaca’s site and switch from a “Live Account” to your “Paper Account.”
Once on your Paper Account Dashboard, you will be able to retrieve your API Keys by clicking the “View” button on the right side of your screen.
Note: Alpaca only provides you with your Alpaca Secret Key once, so if it is compromised, you will have to regenerate it again, so make sure to store it in a safe space.
Now that you have retrieved these API key details we will use them with Alpaca’s Python SDK as shown below and the following code snippets will show you how to take the portfolio weights you constructed in Part I and automatically rebalance your portfolio according to them.
How to Rebalance a Portfolio with Alpaca’s Trading API?
The steps we will take to initiate and rebalance a portfolio with Alpaca’s trading API are as follows:
- Construct Initial Portfolio Weightings — See Part I;
- Ensure Symbols are Eligible for Fractional Trading;
- Close Unnecessary Portfolio Positions;
- Retrieve and Adjust our Rebalance Equity;
- Adjust Current Portfolio Allocations; and
- Buy and Sell Equities Based on our Portfolio Allocations
Construct Initial Portfolio Weightings
Our final function will require a python dictionary of your desired portfolio weightings as an argument; therefore, please refer to Part I of this walkthrough on the methodologies and code to achieve this requirement.
Ensure Symbols are Eligible for Fractional Trading
While you can refactor the following code to only trade in whole share units, the following code requires fractional trading.
This design choice was made to ensure that even investors with smaller portfolios can begin to rebalance and automate their investing journey whether they have $50 or $5,000 to invest.
Therefore, the following _all_symbols_eligible_for_fractionals function accepts the list of stocks you wish to purchase as an argument and returns a Boolean (True/False) if all shares qualify for fractional investing with Alpaca.
A resource to learn more about Fractional Share trading with Alpaca’s API.
Close Unnecessary Portfolio Positions
When it comes to automating the rebalance of a portfolio, one of the most important steps is to close and sell positions before buying new ones. Selling must occur before purchasing because it allows us to replenish our account with the equity needed to buy shares to reach our allocation. If we reversed these steps, our automation would not be able to proceed because there would be no capital available to invest.
Therefore, after ensuring fractional eligibility for our symbols, we then check which symbols may need to be closed to reach our current portfolio allocation goals.
For example, let’s say our portfolio already has the following ETFs in it:
VOO | VGT | VOOG | VUG | QQQ
and we’ve decided that we want to reduce our allocation towards growth and tech stocks, and our new portfolio allocations are:
VOO | VTI | VYM | BND | FSTA.
Well, the following _alpaca_symbols_to_close function would accept both our current alpaca holdings:
VOO | VTI | VOOG | VUG | QQQ
(which are retrieved with the _alpaca_latest_positions function) and the ones we now want in our portfolio:
VOO | VTI | VYM | BND | FSTA
and ultimately return the list of positions that we no longer wish to hold:
VOOG | VUG | QQQ.
We will then pass this list to our alpaca_close_positions function, where it will iterate through our list of unneeded positions and use the Alpaca SDK’s close_positions method to liquidate these holdings.
The while loop in our alpaca_close_positions function ensures that we do not proceed to close the next position until the current position is officially closed. It performs this task by constantly checking the status of our close order and not breaking until the status changes from “pending” to “filled.”
Note: These steps will be inconsequential if we do not currently hold any stocks in our Alpaca trading account.
Retrieve and Adjust our Rebalance Equity
To properly trim and allocate towards our desired weightings & positions, we must first know how much equity we have available in the portfolio.
The _rebalance_equity function allows us to retrieve our current Alpaca portfolio value, which we will later use to calculate how many dollars to invest in each of our holdings.
Note: We set aside 5% of our portfolio as cash by default. This default amount ensures that we can adequately allocate towards all of our holdings. If we set aside no funds, then any drift of a securities price during the rebalance process would prevent us from purchasing the stock due to lack of funds. Additionally, some investors increase the cash percentage to 10% or 20%. This additional cash percentage allows them to have some dry powder to invest in during times of market downturn where stock prices can become very favorable.
Adjust Current Portfolio Allocations
Now that we have closed out any unnecessary positions and retrieved our portfolio’s equity, we can proceed to trim and re-allocate our funds.
We need first to calculate the dollar allocations to designate to each equity to perform our adjustments. The _portfolio_symbols_equity_allocations function accepts our target allocations and our available portfolio equity to accomplish just this task.
After calculating our desired equity allocations, we must then use these values to compare them with our current allocations.
The _alpaca_latest_positions_allocations function allows us to retrieve the current equity allocation for all of our positions.
With our desired allocations (based on our latest weight sizings) and our current allocations, we use the _alpaca_symbols_to_sell_and_buy function to calculate the allocation adjustments needed and separate the positions that need to be sold and bought so that we may properly rebalance our portfolio.
Finally, we run each allocation calculated above through our handle_sell_orders and handle_buy_orders functions, which iterate through our dictionary of orders to sell and buy based on the equity allocations associated with each ticker.
Again, selling overweight equity positions must always occur before purchasing underweight equities; otherwise, there will not be enough funds to process these orders and properly rebalance our portfolio.
The alpaca_rebalance function below handles all of the processes we have just discussed, and all that is needed to rebalance your portfolio successfully is your desired target_allocations and cash weight.
The results after running our alpaca_rebalance function can be seen below. Perfect allocation of $19,000 in each of the associated ETFs and $5,000 set aside for a rainy day.
We hope you found this guide helpful in automating your portfolio’s rebalance process with Alpaca’s streamlined and easy-to-use trading API.
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 toolsfor 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.