Financial Calculations & Valuation
Advanced
Markowitz Mean-Variance Portfolio Optimization in Python (SciPy)
Find the optimal asset allocation weights that maximize the Sharpe Ratio using SciPySLSQP optimization and historical covariance matrices in Python.
#pandas#numpy#scipy
Problem Statement
Equal-weight portfolios ignore asset correlations. This script uses Sequential Least Squares Programming (SLSQP) to compute exact portfolio weights that maximize risk-adjusted return.
Formula / Core Logic
Portfolio Variance = W^T * Cov_Matrix * W
Objective: Minimize (-Sharpe Ratio) subject to Sum(W) = 1 and 0 <= W_i <= 1.
Installation
pip install pandas numpy scipy
markowitz-portfolio-optimization-efficient-frontier-python.py
import numpy as np
import pandas as pd
from scipy.optimize import minimize
def optimize_max_sharpe(returns_df, rf=0.05):
mean_ret = returns_df.mean() * 252
cov_matrix = returns_df.cov() * 252
num_assets = len(mean_ret)
def neg_sharpe(weights):
port_ret = np.dot(weights, mean_ret)
port_vol = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
return -(port_ret - rf) / port_vol
constraints = ({'type': 'eq', 'fun': lambda w: np.sum(w) - 1})
bounds = tuple((0, 1) for _ in range(num_assets))
init_w = num_assets * [1. / num_assets]
opt = minimize(neg_sharpe, init_w, method='SLSQP', bounds=bounds, constraints=constraints)
return dict(zip(returns_df.columns, np.round(opt.x, 4)))
Get the Complete 100+ Python Quant & Automation Bundle
Instant lifetime access to all production-ready scripts, valuation models, and trading bots ($19).
Buy Full Bundle on Gumroad ($19) →Frequently Asked Questions
Q: How do I prevent 80% allocation into a single stock?
Change `bounds = tuple((0, 0.25) for _ in range(num_assets))` to cap any single position at 25%.