import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import minimize
# Elementary, my dear user. Here's a complete Python program to simulate financial
# portfolio optimization using the Markowitz mean-variance framework.
# It generates simulated daily returns for 5 assets over 5 years, computes the
# efficient frontier (long-only portfolios), and finds the maximum Sharpe ratio portfolio.
# Assumptions: Annualized metrics, risk-free rate = 0%, no leverage/shorting.
# Set random seed for reproducibility
np.random.seed(42)
# Parameters
n_assets = 5
n_days = 252 * 5 # 5 years of trading days
mu_daily = 0.0005 # Expected daily return (~12.7% annualized)
sigma_daily = 0.02 # Daily volatility
# Step 1: Generate simulated daily returns (multivariate normal for correlation)
returns = pd.DataFrame(
np.random.multivariate_normal(
mean=[mu_daily] * n_assets,
cov=np.eye(n_assets) * (sigma_daily ** 2) * 0.8 + np.eye(n_assets) * (sigma_daily ** 2) * 0.2,
size=n_days
),
columns=[f'Asset_{i+1}' for i in range(n_assets)]
)
# Step 2: Compute annualized expected returns and covariance matrix
mu = returns.mean() * 252 # Annualized means
cov_matrix = returns.cov() * 252 # Annualized covariance
print("Annualized Expected Returns (mu):")
print(mu)
print("\nAnnualized Covariance Matrix:")
print(cov_matrix.round(4))
# Step 3: Portfolio performance function
def portfolio_performance(weights, mu, cov):
"""
Compute portfolio return and volatility given weights.
"""
portfolio_return = np.dot(weights, mu)
portfolio_vol = np.sqrt(np.dot(weights.T, np.dot(cov, weights)))
return portfolio_return, portfolio_vol
# Step 4: Negative Sharpe ratio (objective to minimize for max Sharpe)
def neg_sharpe_ratio(weights, mu, cov, risk_free_rate=0.0):
"""
Negative Sharpe ratio (for minimization). Sharpe = (Ret - Rf) / Vol
"""
ret, vol = portfolio_performance(weights, mu, cov)
return -(ret - risk_free_rate) / vol
# Constraints and bounds
constraints = ({'type': 'eq', 'fun': lambda x: np.sum(x) - 1}) # Weights sum to 1
bounds = tuple((0.0, 1.0) for _ in range(n_assets)) # Long-only (no shorting)
# Initial guess: equal weights
init_guess = np.array([1.0 / n_assets] * n_assets)
# Step 5: Optimize for maximum Sharpe ratio portfolio
opt_result = minimize(
neg_sharpe_ratio,
init_guess,
args=(mu, cov_matrix),
method='SLSQP',
bounds=bounds,
constraints=constraints
)
optimal_weights = opt_result.x
opt_return, opt_vol = portfolio_performance(optimal_weights, mu, cov_matrix)
opt_sharpe = (opt_return - 0.0) / opt_vol
print("\n" + "="*50)
print("OPTIMAL MAX SHARPE PORTFOLIO")
print("="*50)
for i, w in enumerate(optimal_weights):
print(f"Asset_{i+1}: {w:.4f}")
print(f"Expected Annual Return: {opt_return:.4f}")
print(f"Annual Volatility: {opt_vol:.4f}")
print(f"Sharpe Ratio: {opt_sharpe:.4f}")
# Step 6: Generate Efficient Frontier (min vol for target returns)
target_returns = np.linspace(mu.min() * 0.9, mu.max() * 1.1, 50)
frontier_vols = []
frontier_returns = []
for target_ret in target_returns:
cons_target = (
{'type': 'eq', 'fun': lambda x: np.sum(x) - 1},
{'type': 'eq', 'fun': lambda x: np.dot(x, mu) - target_ret}
)
res = minimize(
lambda x: portfolio_performance(x, mu, cov_matrix)[1], # Minimize volatility
init_guess,
method='SLSQP',
bounds=bounds,
constraints=cons_target
)
if res.success:
frontier_vols.append(res.fun)
frontier_returns.append(target_ret)
# Step 7: Visualization
plt.figure(figsize=(10, 6))
plt.plot(frontier_vols, frontier_returns, 'b-', linewidth=2, label='Efficient Frontier (Long-Only)')
plt.plot(opt_vol, opt_return, 'ro', markersize=15, markeredgecolor='k', markeredgewidth=1, label=f'Max Sharpe Portfolio (Sharpe={opt_sharpe:.2f})')
# Plot individual assets
for i in range(n_assets):
plt.scatter(np.sqrt(cov_matrix.iloc[i, i]), mu.iloc[i], s=100, alpha=0.7, label=f'Asset_{i+1}')
plt.xlabel('Portfolio Volatility (Annualized)', fontsize=12)
plt.ylabel('Portfolio Return (Annualized)', fontsize=12)
plt.title('Markowitz Efficient Frontier Simulation', fontsize=14)
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
# Optional: Random portfolios for comparison
n_random = 1000
random_returns = np.zeros(n_random)
random_vols = np.zeros(n_random)
for i in range(n_random):
rand_weights = np.random.random(n_assets)
rand_weights /= rand_weights.sum()
random_returns[i], random_vols[i] = portfolio_performance(rand_weights, mu, cov_matrix)
plt.figure(figsize=(10, 6))
plt.scatter(random_vols, random_returns, c='gray', alpha=0.5, s=10, label='Random Portfolios')
plt.plot(frontier_vols, frontier_returns, 'b-', linewidth=3, label='Efficient Frontier')
plt.plot(opt_vol, opt_return, 'ro', markersize=15, markeredgecolor='k', markeredgewidth=2, label=f'Max Sharpe')
plt.xlabel('Volatility (Annualized)')
plt.ylabel('Return (Annualized)')
plt.title('Efficient Frontier vs. Random Portfolios')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
This self-contained program runs out-of-the-box with NumPy, Pandas, Matplotlib, and SciPy (install via pip install numpy pandas matplotlib scipy). It simulates correlated returns, optimizes portfolios, prints results, and visualizes the efficient frontier + max Sharpe portfolio. Diversification reduces risk—observe how the frontier dominates random portfolios! If you'd like tweaks (e.g., real data, short-selling, or transaction costs), just ask.