Comprehending the Objective
\n\n
I'm starting with a clear understanding of the goal: build a Python program for financial portfolio optimization. This involves pinpointing the ideal asset allocation to either boost returns for a set risk or lower risk for a specific return. I'm focusing on defining 'best' in terms of risk-reward trade-offs.
Outlining Core Principles
\n\n
Now I'm diving into specifics. Assets like stocks, historical price data from yfinance, and calculating metrics such as expected returns and volatility are my focal points. I'm leaning heavily on Modern Portfolio Theory and its Efficient Frontier to guide the optimization process. I will utilize pandas, numpy, and matplotlib to handle the data, calculations, and visualization. Then, I plan to incorporate scipy.optimize for mathematical solutions.
Evaluating Library Choices
\n\n
I'm now deep in the library selection phase, specifically focusing on optimization strategies. I'm leaning heavily towards scipy.optimize and possibly incorporating Monte Carlo simulations for comparison. yfinance is solidified for data acquisition. I'll need to confirm that pandas and numpy can handle the scale of data and calculations, as well as confirm my plotting preference between matplotlib and seaborn.
Planning Code Implementation
\n\n
I'm now mapping out the coding phase. I'm focusing on data acquisition using yfinance, log return calculations, and setting up core functions for portfolio metrics. I'm choosing the core functions for portfolio return, volatility, and Sharpe ratio. I'm building out the strategies, starting with a Monte Carlo approach, and then using scipy.optimize with key constraints and bounds. I'm ready to translate this into Python, keeping in mind the need for clean structure and comments.
Planning Code Refinement
\n\n
I'm now focusing on the final touches, like adding comments and clarifying the code structure. I'm also ensuring the program includes the risk-free rate for accurate Sharpe ratio calculations. I've noted that np.dot requires careful attention to matrix dimensions. The program will output optimal weights, annual return, volatility, Sharpe ratio, and a plot visualizing the efficient frontier.
This is a Python program that implements Modern Portfolio Theory (MPT). It determines the optimal allocation of capital across a set of assets to maximize returns for a given level of risk (the Sharpe Ratio).
We will use two methods for this:
- Monte Carlo Simulation: Generating thousands of random portfolios to visualize the "Efficient Frontier."
- Mathematical Optimization (SciPy): Using linear algebra to find the precise weights for the best Sharpe Ratio.
Prerequisites
You will need to install the necessary libraries:
pip install yfinance pandas numpy matplotlib scipy
The Python Code
import numpy as np
import pandas as pd
import yfinance as yf
import matplotlib.pyplot as plt
import scipy.optimize as sco
# =========================================
# 1. Configuration & Data Retrieval
# =========================================
# Define the assets (Tickers)
assets = ['AAPL', 'MSFT', 'GOOGL', 'AMZN', 'TSLA']
start_date = '2020-01-01'
end_date = '2023-12-31'
risk_free_rate = 0.04 # 4% annual risk-free rate (e.g., Treasury Bond)
print(f"Downloading data for: {assets}...")
data = yf.download(assets, start=start_date, end=end_date)['Adj Close']
# Calculate Daily Log Returns
# Log returns are additive over time, which makes them preferred for math
log_returns = np.log(data / data.shift(1)).dropna()
# Calculate Covariance Matrix based on valid trading days (252 per year)
cov_matrix = log_returns.cov() * 252
print("Data Downloaded. Calculating stats...")
# =========================================
# 2. Helper Functions
# =========================================
def portfolio_annualized_performance(weights, mean_returns, cov_matrix):
"""
Calculates the annualized return and volatility of a portfolio given weights.
"""
returns = np.sum(mean_returns * weights) * 252
std = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
return returns, std
def generate_random_portfolios(num_portfolios, mean_returns, cov_matrix, risk_free_rate):
"""
Performs Monte Carlo simulation to generate random portfolio weights.
"""
results = np.zeros((3, num_portfolios))
weights_record = []
for i in range(num_portfolios):
# Generate random weights
weights = np.random.random(len(assets))
# Normalise weights so they sum to 1 (100% allocation)
weights /= np.sum(weights)
weights_record.append(weights)
# Calculate portfolio stats
portfolio_return, portfolio_std = portfolio_annualized_performance(weights, mean_returns, cov_matrix)
# Store results: [Standard Deviation, Return, Sharpe Ratio]
results[0,i] = portfolio_std
results[1,i] = portfolio_return
results[2,i] = (portfolio_return - risk_free_rate) / portfolio_std
return results, weights_record
# =========================================
# 3. Mathematical Optimization (SciPy)
# =========================================
def neg_sharpe_ratio(weights, mean_returns, cov_matrix, risk_free_rate):
p_ret, p_var = portfolio_annualized_performance(weights, mean_returns, cov_matrix)
return -(p_ret - risk_free_rate) / p_var
def maximize_sharpe_ratio(mean_returns, cov_matrix, risk_free_rate):
num_assets = len(mean_returns)
args = (mean_returns, cov_matrix, risk_free_rate)
# Constraints: Sum of weights must be 1
constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1})
# Bounds: Weights must be between 0 and 1 (no shorting)
bound = (0.0, 1.0)
bounds = tuple(bound for asset in range(num_assets))
# Initial guess: Equal distribution
initial_guess = num_assets * [1. / num_assets,]
result = sco.minimize(neg_sharpe_ratio, initial_guess, args=args,
method='SLSQP', bounds=bounds, constraints=constraints)
return result
# =========================================
# 4. Execution & Visualization
# =========================================
mean_returns = log_returns.mean()
# --- A. Monte Carlo Simulation ---
num_simulations = 5000
print(f"Simulating {num_simulations} portfolios relative to {len(assets)} assets...")
results, weights = generate_random_portfolios(num_simulations, mean_returns, cov_matrix, risk_free_rate)
# Extract data for max Sharpe ratio from Simulation
max_sharpe_idx = np.argmax(results[2])
sdp, rp = results[0,max_sharpe_idx], results[1,max_sharpe_idx]
max_sharpe_allocation_mc = pd.DataFrame(weights[max_sharpe_idx], index=data.columns, columns=['allocation'])
max_sharpe_allocation_mc.allocation = [round(i*100, 2)for i in max_sharpe_allocation_mc.allocation]
# --- B. Scipy Optimization ---
print("Optimizing for Maximum Sharpe Ratio...")
optimal_result = maximize_sharpe_ratio(mean_returns, cov_matrix, risk_free_rate)
optimal_weights = optimal_result.x
opt_ret, opt_vol = portfolio_annualized_performance(optimal_weights, mean_returns, cov_matrix)
opt_sharpe = (opt_ret - risk_free_rate) / opt_vol
# Create DataFrame for Optimal Weights
optimal_allocation = pd.DataFrame(optimal_weights, index=data.columns, columns=['allocation'])
optimal_allocation.allocation = [round(i*100, 2)for i in optimal_allocation.allocation]
# --- Output Results ---
print("\n" + "="*30)
print("OPTIMAL PORTFOLIO (SciPy)")
print("="*30)
print(f"Annualized Return: {round(opt_ret*100, 2)}%")
print(f"Annualized Volatility: {round(opt_vol*100, 2)}%")
print(f"Sharpe Ratio: {round(opt_sharpe, 2)}")
print("-" * 30)
print("Asset Allocation (%):")
print(optimal_allocation)
print("="*30)
# --- Plotting ---
plt.figure(figsize=(10, 7))
# Plot all random portfolios
plt.scatter(results[0,:], results[1,:], c=results[2,:], cmap='YlGnBu', marker='o', s=10, alpha=0.3)
plt.colorbar(label='Sharpe Ratio')
# Plot the Optimal Portfolio (Red Star)
plt.scatter(opt_vol, opt_ret, marker='*', color='r', s=500, label='Maximum Sharpe Ratio')
plt.title('Simulated Portfolio Optimization based on Efficient Frontier')
plt.xlabel('Annualized Volatility')
plt.ylabel('Annualized Returns')
plt.legend(labelspacing=0.8)
plt.grid(True)
plt.show()
How it works:
- Data: We download Adjusted Close prices from Yahoo Finance. We convert these prices into Log Returns. Log returns are preferred in finance because they are additive across time periods.
- Monte Carlo Simulation (The Scatter Plot):
- The code generates 5,000 (variable
num_simulations) theoretical portfolios.
- For each portfolio, it assigns random weights to the assets (ensuring the weights sum to 100%).
- It calculates the expected Return and Volatility (Standard Deviation) for that random combination.
- It plots these points. The curve shape formed at the top-left boundary is the Efficient Frontier.
- Scipy Optimization (The Red Star):
- Instead of guessing randomly, we use the
scipy.optimize.minimize function.
- Since SciPy finds the minimum, we tell it to minimize the Negative Sharpe Ratio (calculated as return divided by risk).
- This mathematically finds the exact combination of stocks that gives the highest return for the lowest risk.
- Constraint: We ensure that ∑weights=1 (you must invest 100% of your cash) and 0 (no short selling, no leverage).
Interpretation of Output:
- Sharpe Ratio: The higher, the better. It represents how much excess return you get for every unit of volatility you accept.
- Volatility: The standard deviation of the portfolio. A higher number means the portfolio value fluctuates more wildly.
- Allocation: The exact percentage of your money you should put into each stock to achieve these results mathematically.