Building a Markowitz Optimizer with SciPy: A Step-by-Step Guide for Quants
If you’ve ever tried to build an investment portfolio, you’ve faced the universal tradeoff: how do you maximize returns without taking on more risk than you can tolerate? Harry Markowitz’s 1952 Modern Portfolio Theory (MPT) solved this problem mathematically, giving birth to quantitative investing as we know it. Today, we’re going to build a fully functional Markowitz optimizer from scratch using SciPy, so you can ditch black-box portfolio tools and understand exactly how your asset allocations are calculated. This tutorial is part of our open-source quant tooling series on Quantopia, with full runnable code available at quantopia.net/building-a-markowitz-optimizer-with-scipy.
By Tom Roberts · Editor, Quantopia
Published · Updated
Table of Contents#
- Core Concepts of Modern Portfolio Theory (MPT)
- Mathematical Formulation for SciPy Optimization
- Step-by-Step SciPy Implementation of Markowitz Optimizer
- Plotting the Efficient Frontier
- Common Pitfalls & Best Practices
- When to Use SciPy vs. Specialized Portfolio Optimization Libraries
- Conclusion
- References
Core Concepts of Modern Portfolio Theory (MPT)#
MPT is a mathematical framework for constructing portfolios that maximize expected return for a given level of risk, or minimize risk for a given target return. It relies on a few core metrics:
Key MPT Metrics#
| Metric | Formula | Definition |
|---|---|---|
| Expected Portfolio Return | Weighted average of individual asset expected returns ( = vector of asset returns, = vector of asset weights) | |
| Portfolio Variance | Measure of portfolio risk, calculated using the covariance matrix () of asset returns | |
| Portfolio Volatility | Standard deviation of returns, the most common measure of portfolio risk | |
| Sharpe Ratio | Risk-adjusted return, comparing excess return over the risk-free rate () to portfolio volatility |
Critical MPT Portfolios#
- Efficient Frontier: The set of all optimal portfolios that offer the highest return for a given risk level, or lowest risk for a given return level.
- Maximum Sharpe Ratio (MSR) Portfolio: The tangency point where a line from the risk-free rate touches the efficient frontier, representing the highest possible return per unit of risk.
- Minimum Variance Portfolio (MVP): The portfolio on the efficient frontier with the absolute lowest volatility, regardless of return.
Mathematical Formulation for SciPy Optimization#
SciPy’s scipy.optimize.minimize only supports minimization, so we reframe all MPT optimization problems to fit this constraint:
1. Maximum Sharpe Ratio Portfolio#
- Objective: Minimize the negative Sharpe Ratio:
- Constraints: (weights sum to 100%)
- Bounds: for all assets (long-only portfolio, no short selling)
2. Minimum Volatility Portfolio#
- Objective: Minimize portfolio volatility:
- Constraints:
- Bounds:
3. Efficient Frontier Portfolios#
For a grid of target returns between the lowest and highest individual asset returns:
- Objective: Minimize portfolio volatility
- Constraints: and (portfolio meets target return)
- Bounds:
We use the SLSQP (Sequential Least Squares Programming) solver from SciPy, which is purpose-built for constrained multi-variable optimization problems like these.
Step-by-Step SciPy Implementation of Markowitz Optimizer#
We’ll build an optimizer for a portfolio of 5 assets: AAPL, MSFT, GOOG, AMZN, and TLT (long-term Treasury bond ETF).
Prerequisites#
Install required packages first:
pip install numpy scipy yfinance scikit-learn matplotlibStep 1: Load and Preprocess Data#
Pull 5 years of daily adjusted close prices and compute log returns:
import numpy as np
import scipy.optimize as sco
import yfinance as yf
# Download data
tickers = ["AAPL", "MSFT", "GOOG", "AMZN", "TLT"]
data = yf.download(tickers, period="5y")["Adj Close"]
returns = np.log(data / data.shift(1)).dropna()
# Compute inputs for MPT
mean_returns = returns.mean() * 252 # Annualize returns (252 trading days/year)
cov_matrix = returns.cov() * 252 # Annualize covariance
risk_free_rate = 0.04 # 2026 10-year Treasury yieldStep 2: Define Helper Functions#
def portfolio_performance(weights, mean_returns, cov_matrix):
"""Calculate portfolio return and volatility for given weights"""
p_return = np.dot(weights, mean_returns)
p_volatility = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights)))
return p_return, p_volatility
def neg_sharpe_ratio(weights, mean_returns, cov_matrix, risk_free_rate):
"""Negative Sharpe Ratio to use as minimization objective"""
p_ret, p_vol = portfolio_performance(weights, mean_returns, cov_matrix)
return -(p_ret - risk_free_rate) / p_volStep 3: Optimize for Maximum Sharpe Ratio Portfolio#
num_assets = len(mean_returns)
args = (mean_returns, cov_matrix, risk_free_rate)
# Constraints and bounds
constraints = {"type": "eq", "fun": lambda x: np.sum(x) - 1}
bounds = tuple((0, 1) for asset in range(num_assets))
initial_guess = num_assets * [1. / num_assets] # Equal weights initial guess
# Run optimization
msr_result = sco.minimize(
neg_sharpe_ratio,
initial_guess,
args=args,
method="SLSQP",
bounds=bounds,
constraints=constraints
)
# Extract results
msr_weights = msr_result.x
msr_return, msr_vol = portfolio_performance(msr_weights, mean_returns, cov_matrix)
print("Maximum Sharpe Ratio Portfolio Performance:")
print(f"Return: {msr_return:.1%}, Volatility: {msr_vol:.1%}, Sharpe Ratio: {(msr_return - risk_free_rate)/msr_vol:.2f}")
# Print weights mapping to returns.columns (avoids ticker sorting bugs)
print("Weights:", dict(zip(returns.columns, np.round(msr_weights, 4))))Step 4: Optimize for Minimum Volatility Portfolio#
def min_volatility(weights, mean_returns, cov_matrix):
return portfolio_performance(weights, mean_returns, cov_matrix)[1]
mvp_result = sco.minimize(
min_volatility,
initial_guess,
args=(mean_returns, cov_matrix),
method="SLSQP",
bounds=bounds,
constraints=constraints
)
mvp_weights = mvp_result.x
mvp_return, mvp_vol = portfolio_performance(mvp_weights, mean_returns, cov_matrix)
print("Minimum Variance Portfolio Performance:")
print(f"Return: {mvp_return:.1%}, Volatility: {mvp_vol:.1%}, Sharpe Ratio: {(mvp_return - risk_free_rate)/mvp_vol:.2f}")
print("Weights:", dict(zip(returns.columns, np.round(mvp_weights, 4))))Plotting the Efficient Frontier#
To visualize the full set of optimal portfolios, we calculate the minimum volatility for a grid of target returns:
import matplotlib.pyplot as plt
# Define target return range
target_returns = np.linspace(mvp_return, mean_returns.max(), 50)
efficient_volatilities = []
for target in target_returns:
# Add target return constraint
ef_constraints = [
{"type": "eq", "fun": lambda x: np.sum(x) - 1},
{"type": "eq", "fun": lambda x: portfolio_performance(x, mean_returns, cov_matrix)[0] - target}
]
ef_result = sco.minimize(
min_volatility,
initial_guess,
args=(mean_returns, cov_matrix),
method="SLSQP",
bounds=bounds,
constraints=ef_constraints
)
efficient_volatilities.append(ef_result.fun)
# Plot results
plt.figure(figsize=(10,6))
# Plot 10,000 random portfolios for context
random_weights = np.random.dirichlet(np.ones(num_assets), 10000)
random_returns, random_vols = [], []
for w in random_weights:
r, v = portfolio_performance(w, mean_returns, cov_matrix)
random_returns.append(r)
random_vols.append(v)
plt.scatter(random_vols, random_returns, c=(np.array(random_returns)-risk_free_rate)/np.array(random_vols), cmap="viridis", alpha=0.3)
# Plot efficient frontier
plt.plot(efficient_volatilities, target_returns, "r--", linewidth=3, label="Efficient Frontier")
# Plot MSR and MVP
plt.scatter(msr_vol, msr_return, c="red", s=200, marker="*", label="Max Sharpe Ratio Portfolio")
plt.scatter(mvp_vol, mvp_return, c="blue", s=200, marker="*", label="Minimum Variance Portfolio")
plt.xlabel("Annualized Volatility")
plt.ylabel("Annualized Return")
plt.colorbar(label="Sharpe Ratio")
plt.legend()
plt.title("Markowitz Efficient Frontier")
plt.show()Common Pitfalls & Best Practices#
Markowitz optimization is notorious for producing unrealistic portfolios if not implemented carefully:
1. Input Sensitivity (Error Maximization)#
Small estimation errors in expected returns or covariance matrices lead to highly concentrated, unstable weight allocations.
- Fix for covariance noise: Use Ledoit-Wolf shrinkage to reduce noise in sample covariance matrices:
from sklearn.covariance import LedoitWolf cov_shrunk = LedoitWolf().fit(returns).covariance_ * 252 - Fix for expected return errors: Avoid using raw historical returns as forecasts. Use factor models (Fama-French), Black-Litterman, or machine learning return forecasts instead.
2. Overly Concentrated Weights#
If your optimizer returns portfolios with 80%+ allocated to a single asset, add L2 regularization to the objective function to force diversification:
def regularized_neg_sharpe(weights, mean_returns, cov_matrix, risk_free_rate, gamma=0.01):
p_ret, p_vol = portfolio_performance(weights, mean_returns, cov_matrix)
return -(p_ret - risk_free_rate)/p_vol + gamma * np.sum(weights**2)Tune the gamma hyperparameter to control diversification strength.
3. Ignoring Transaction Costs#
Standard MPT does not account for trading costs. Add a turnover constraint (limit maximum weight change from previous allocations) or a transaction cost penalty to the objective function when rebalancing.
4. Silent Ticker Mismatch Bug#
A very common programming error in custom Markowitz implementations is mapping the optimal weights back to the wrong assets. When you download data using yfinance with a specific list of tickers:
tickers = ["AAPL", "MSFT", "GOOG", "AMZN", "TLT"]
data = yf.download(tickers, period="5y")["Adj Close"]Pandas automatically sorts the columns of the returned DataFrame alphabetically, yielding: ['AAPL', 'AMZN', 'GOOG', 'MSFT', 'TLT'].
If you map the output weights using the original tickers list:
# BUG: Scrambles the allocations (e.g., maps MSFT weight to AMZN and vice-versa)
weights_dict = dict(zip(tickers, msr_weights))Your portfolio will be completely incorrect.
- Fix: Always map weights using the DataFrame’s columns:
weights_dict = dict(zip(returns.columns, msr_weights))
When to Use SciPy vs. Specialized Portfolio Optimization Libraries#
SciPy is ideal for small portfolios (<20 assets), quick prototyping, and learning purposes, but for production use cases, consider these alternatives:
- PyPortfolioOpt: Specialized portfolio optimization library that supports MPT, Black-Litterman, covariance shrinkage, and plotting out of the box. Uses CVXPY under the hood.
- CVXPY: Convex optimization library that solves quadratic programming (QP) MPT problems much faster and more reliably than SciPy’s SLSQP for large portfolios.
- Riskfolio-Lib: Comprehensive library supporting advanced risk measures like VaR, CVaR, and entropic VaR for more sophisticated portfolio construction.
For a full comparison of these tools, see our library guide at quantopia.net/building-a-markowitz-optimizer-with-scipy.
Conclusion#
Building a Markowitz optimizer with SciPy is a great way to master the fundamentals of Modern Portfolio Theory while building a practical tool for your quant workflow. Key takeaways:
- Use SLSQP solver for constrained MPT optimization in SciPy
- Always use shrunk covariance matrices and robust return forecasts to avoid error maximization
- Add regularization if you get overly concentrated portfolio weights
- For large production portfolios, use specialized libraries like CVXPY or PyPortfolioOpt instead of SciPy
References#
- Markowitz, H. (1952). Portfolio Selection. The Journal of Finance, 7(1), 77-91.
- Ledoit, O., & Wolf, M. (2004). Honey, I Shrunk the Covariance Matrix. The Journal of Portfolio Management, 30(4), 110-119.
- SciPy Optimize Documentation: https://docs.scipy.org/doc/scipy/reference/optimize.html
- PyPortfolioOpt Documentation: https://pyportfolioopt.readthedocs.io/
- Quantopia Markowitz Optimizer Guide: https://quantopia.net/building-a-markowitz-optimizer-with-scipy