πŸ“Š
Mac Playbook
⏱ 20 min

Portfolio Optimization

Convex optimization for portfolio allocation with cvxpy

Replaces DGX Spark: Portfolio Optimization
data sciencefinance

Basic idea

Portfolio optimization finds the allocation of capital across assets that maximizes expected return for a given level of risk β€” or equivalently, minimizes risk for a given target return. This is the Markowitz mean-variance framework (1952), and it reduces to a quadratic program (QP): minimize **w**α΅€Ξ£**w** subject to **ΞΌ**α΅€**w** β‰₯ target, Ξ£wα΅’ = 1, and wα΅’ β‰₯ 0. cvxpy provides a clean Python interface to convex solvers (OSQP, SCS) that solve these QPs efficiently and reliably on your Mac β€” no GPU required.

What you'll accomplish

A working portfolio optimizer that downloads real historical stock data via yfinance, computes annualized returns and the covariance matrix, solves for the maximum Sharpe ratio portfolio and the minimum variance portfolio, plots the efficient frontier, and saves a matplotlib visualization β€” all running locally with no cloud API.

What to know before starting

Mean-variance optimization: β€” The Markowitz framework says a rational investor cares only about a portfolio's expected return and variance. Given those two numbers for every asset and every pair of assets, we can find the "best" portfolio mathematically.
Covariance matrix (Ξ£): β€” A square matrix where the diagonal entry for asset i is its variance (risk squared) and the off-diagonal entry for assets i,j is their covariance (how much they move together). Diversification works because negatively correlated assets reduce overall variance.
Sharpe ratio: β€” (Portfolio return βˆ’ Risk-free rate) / Portfolio volatility. The ratio measures return per unit of risk. The maximum-Sharpe portfolio is the one tangent to the efficient frontier from the risk-free rate.
Convex optimization: β€” A problem is convex if the objective and feasible set are both convex. The key property: any local minimum is the global minimum. `cvxpy` checks your problem is convex (DCP rules) before solving, so the solution is guaranteed optimal.
Efficient frontier: β€” The curve of portfolios that achieve maximum return for each level of risk. No portfolio above the frontier is feasible; any portfolio below is suboptimal (you could do better).
cvxpy DCP rules: β€” Disciplined Convex Programming requires your objective and constraints to be built from DCP-compliant expressions. `cp.quad_form(w, sigma)` is convex; `cp.sum(w) == 1` is affine. If `cvxpy` raises a DCP error, the problem as written is not recognized as convex.

Prerequisites

β€’ macOS (any version)
β€’ Python 3.9+
β€’ Internet connection for yfinance data download

Time & risk

Duration:: 20 minutes
Risk level:: None β€” pure Python, no system changes
Rollback:: Delete the virtual environment; nothing is installed system-wide