CodeForFinance
Python Tutorial

Automated Portfolio Rebalancing in Python

Build a tool that calculates how to rebalance your portfolio back to target allocations.

Define Portfolio

import pandas as pd

# Current holdings
portfolio = pd.DataFrame({
    "Asset": ["UK Equity", "US Equity", "Bonds", "Gold", "Cash"],
    "Current Value": [12000, 18000, 8000, 3000, 4000],
    "Target %": [25, 35, 25, 10, 5],
})

total = portfolio["Current Value"].sum()
portfolio["Current %"] = (portfolio["Current Value"] / total * 100).round(1)
portfolio["Drift"] = (portfolio["Current %"] - portfolio["Target %"]).round(1)
print(portfolio.to_string(index=False))
print(f"
Total portfolio: £{total:,.0f}")

Calculate Trades

# Calculate rebalancing trades
portfolio["Target Value"] = total * portfolio["Target %"] / 100
portfolio["Trade"] = portfolio["Target Value"] - portfolio["Current Value"]
portfolio["Action"] = portfolio["Trade"].apply(
    lambda x: f"BUY £{x:,.0f}" if x > 0 else f"SELL £{abs(x):,.0f}" if x < 0 else "HOLD"
)

print("
Rebalancing Trades:")
for _, row in portfolio.iterrows():
    if abs(row["Trade"]) > 10:
        print(f"  {row['Asset']:>12}: {row['Action']}")

Developer Essentials

As an Amazon Associate we may earn from qualifying purchases.