Portfolio theory: mean-variance optimization
Derive the mean-variance frontier, global minimum-variance and tangency portfolios, two-fund separation and constrained portfolio optimization.
After this lesson you can
- Formulate the mean-variance problem and solve its related forms using Lagrange multipliers.
- Derive the efficient frontier using A, B and C and show that it is a hyperbola in the volatility-mean plane.
- Obtain closed-form global minimum-variance and tangency portfolios, and prove two-fund separation.
- Construct the capital market line and relate its slope to maximum Sharpe.
- Solve the problem with inequality constraints as a quadratic program and compare it with the closed-form solution.
Before you start
Diversification combines risks
A portfolio does not inherit the average volatility of its components. If two assets move in different directions, some fluctuations offset each other. This depends on covariance as well as individual volatilities. In the figure the weights sum to one and lie between zero and one: there are no short positions. Coordinates and correlation are hypothetical parameters, not market observations.
For simple returns over the same horizon, the portfolio has mean and variance
This identity follows from the variance of a sum. If , . For positive volatilities, weight eliminates variance. This requires exactly negative and stable correlation, an idealized assumption. If , the standard deviation of a long-only mix is the weighted average of the standard deviations: there is no additional offsetting reduction.
The general problem
Let be the simple-return vector, and . Weights are fractions of initial wealth, with . The mean is and variance is the quadratic form . Negative weights represent short positions. Simple returns are required for the portfolio return to be this sum; individual log returns do not aggregate this way.
Mean-variance optimization can seek minimum variance for a target mean :
Another formulation maximizes with , subject to the budget. Equivalence holds between efficient solutions associated with appropriate targets and risk aversions, not arbitrary parameter values. Maximum Sharpe requires a risk-free rate and additional conditions; we derive it separately. Mean-variance criteria do not represent all expected utility for general distributions: see risk aversion.
The frontier via multipliers
Suppose is symmetric positive definite and is not proportional to . Define
The Cauchy-Schwarz inequality in the inner product induced by gives under these assumptions. Applying Lagrange multipliers to half the variance, the stationarity condition is . The two constraints give and . Solving,
The solution is unique: the objective is strictly convex and the constraints are affine. Substituting or using ,
In the plane this equation is a hyperbola; in it is a parabola. The efficient frontier is only the branch with : for a given risk, the lower branch offers a lower mean.
To see why, fix a variance greater than . The equation permits two means equidistant from . Their portfolios have equal risk, but the one with the higher mean dominates the other. At the vertex they coincide. In the plane with volatility on the horizontal axis, portfolios to the right of the curve have more risk than the minimum for their mean. Such portfolios exist if there is a nonzero direction that is budget-neutral and orthogonal to the means; with only two assets and distinct means there is no such freedom.
The global minimum-variance portfolio (GMV) is , with mean and variance . It is also obtained by minimizing subject only to the budget constraint.
The direct proof reveals what is lost if covariance is singular. Write any budgeted portfolio as , with . Then
The cross term vanishes because . Positive definiteness makes the last term strictly positive except when , proving uniqueness. If is only positive semidefinite, risk-free combinations and non-unique minima may exist; the inverse and formulas above no longer apply without examining the null space and feasibility. Using a pseudoinverse without that analysis can hide a zero-risk solution.
The spectral interpretation also explains sensitivity. If , solving with it multiplies the component along each eigenvector by . A direction with very small estimated variance receives a large factor, and small errors in means or covariances can produce enormous weights. The matrix can be positive definite and still ill-conditioned. This concerns the data and model as well as solver precision.
The cloud is generated with normalized positive weights and a fixed seed; it illustrates portfolios, not market data. For each target shown, the builder solves the unconstrained problem or examines possible long-only active sets. The branch below GMV is drawn to show symmetry, although it is inefficient. The unconstrained solution may exist outside the displayed range of targets.
Because is affine in , if , any portfolio on this frontier can be written with . This is two-fund separation: coefficients can be negative when extrapolating. It concerns optimal portfolios of the unconstrained problem, not every feasible portfolio.
Substituting minimum variance into utility clarifies its relationship to the fixed target. The derivative with respect to is , which is zero at . Because the second derivative is negative, this is the unique solution for . As grows, the target mean approaches the GMV mean; as it falls, exposure increases and weights can become extreme. The lower branch cannot be optimal for this utility, which increases with mean. Position or borrowing limits change the feasible set and therefore this correspondence.
Risk-free asset
With simple risk-free rate over the same horizon and premium vector , the direction of maximum positive Sharpe is proportional to . If , normalize it to budget one:
This is the tangency portfolio. The denominator assumption matters: if it is zero, the direction cannot be normalized to sum to one; if negative, normalization reverses the positive-Sharpe direction. The proof uses Cauchy-Schwarz: , with equality when is a positive multiple of .
The inequality follows by applying Cauchy-Schwarz to and . Their inner product is , and their norms are volatility and the square root of , respectively. Dividing by positive volatility gives the Sharpe bound. Equality requires proportionality of the two transformed vectors, equivalent to the stated direction. If all premiums are zero, maximum Sharpe is zero and no unique tangency direction exists.
Combining the tangency portfolio with risk-free borrowing or lending at the same rate gives the capital allocation line for positive exposure to the tangency portfolio. Its slope is maximum Sharpe . When the tangency portfolio coincides with the market portfolio under the equilibrium assumptions studied in CAPM, this line is called the capital market line. Extrapolation beyond tangency requires borrowing. If the borrowing rate exceeds the lending rate, there is no single line: optimize the two regimes separately and check where each solution falls.
To make the last case precise, temporarily fix a risky portfolio with mean and variance . With exposure , invest the remainder at rate and its mean is . For , finance the excess at rate , and the mean is . The expressions agree at but have different slopes. Under mean-variance utility, stationary exposure within each regime is , with or ; restrict it to the corresponding interval and also compare . Then optimize the risky composition. Extending the lending line beyond the borrowing point is insufficient.
Practical constraints
The closed-form solution can contain short positions or large gross leverage . Long-only portfolios add ; per-asset limits add . To limit gross leverage, introduce auxiliary variables , and . A market-neutral portfolio may impose if exposures are defined: neutrality does not itself imply a unit budget.
These linear constraints and the quadratic objective form a convex quadratic program. The KKT conditions combine feasibility, stationarity, nonnegative multipliers and complementarity. If the unconstrained solution violates a constraint, it is no longer feasible; an active constraint at the optimum does not by itself imply the solution changed, since its multiplier can be zero. Check feasibility and solver residuals, especially for mean targets outside the attainable range.
For example, for lower bounds and an imposed mean target, write the Lagrangian as . The conditions are , , and , in addition to the two equalities. If a weight is positive, its multiplier is zero; if it is zero, its multiplier may be positive. With linear constraints and positive-definite covariance, a feasible point satisfying these conditions is the unique global minimum.
Without shorting, the target mean must lie between the smallest and largest individual means: it is their convex combination. If shorting is allowed and the means are not all equal, any real target is feasible, although reaching it may require enormous positions. Feasibility does not guarantee an economically practical portfolio.
Lab: closed-form solution and constraints
We start with hypothetical annual parameters, not observed data. Means, variances and rate correspond to the same period. In code we solve systems and check both constraints and objective value. SLSQP is a general numerical method: check its success status and residuals, not just its output vector.
import numpy as np
from scipy.optimize import minimize
mu = np.array([.05, .08, .12])
vol = np.array([.10, .18, .25])
corr = np.array([[1., .2, .1], [.2, 1., .3], [.1, .3, 1.]])
Sigma = np.outer(vol, vol) * corr
one = np.ones(len(mu))
assert np.linalg.eigvalsh(Sigma).min() > 0
def constants(mu, cov):
one = np.ones(len(mu))
x = np.linalg.solve(cov, one)
y = np.linalg.solve(cov, mu)
A, B, C = one @ x, one @ y, mu @ y
D = A*C-B*B
if D <= 0:
raise ValueError('Las medias deben ser distintas y la covarianza definida positiva')
return A, B, C, D, x, y
def frontier(mu, cov, target):
A, B, C, D, x, y = constants(mu, cov)
return ((C-B*target)*x+(A*target-B)*y)/D
def tangency(mu, cov, rf):
x = np.linalg.solve(cov, mu-rf)
if x.sum() <= 0:
raise ValueError('La dirección positiva no admite esta normalización')
return x/x.sum()
A,B,C,D,x,y = constants(mu,Sigma)
gmv = x/A
target = .09
closed = frontier(mu,Sigma,target)
tangent = tangency(mu,Sigma,.02)
print('GMV: pesos',np.round(gmv,5),'media',round(float(mu@gmv),5),
'volatilidad',round(float(np.sqrt(gmv@Sigma@gmv)),5))
print('Objetivo: pesos',np.round(closed,5),'media',round(float(mu@closed),5),
'varianza',round(float(closed@Sigma@closed),7))
print('Tangente: pesos',np.round(tangent,5),
'Sharpe',round(float(([email protected])/np.sqrt(tangent@Sigma@tangent)),5))First compare with the numerical minimum without bounds. Then impose and plot both frontiers in the long-only feasible range. The dominated part of each curve is also drawn so you can recognize the global minimum.
import matplotlib.pyplot as plt
def constrained(mu, cov, target, bounds=None):
n = len(mu)
result = minimize(lambda w: .5*w@cov@w, np.ones(n)/n,
jac=lambda w: cov@w, method='SLSQP', bounds=bounds,
constraints=[{'type':'eq','fun':lambda w: w.sum()-1,
'jac':lambda w: np.ones(n)},
{'type':'eq','fun':lambda w: mu@w-target,
'jac':lambda w: mu}],
options={'ftol':1e-12,'maxiter':500})
if not result.success or abs(result.x.sum()-1)>1e-7 or abs([email protected])>1e-7:
raise RuntimeError(result.message)
return result.x
numeric = constrained(mu,Sigma,target)
assert np.allclose(numeric,closed,atol=1e-6)
print('Máxima diferencia entre soluciones:',float(np.max(np.abs(numeric-closed))))
target_active = .11
libre = frontier(mu,Sigma,target_active)
limitada = constrained(mu,Sigma,target_active,[(0.,1.)]*len(mu))
print('Objetivo 11 %: libre',np.round(libre,5),'sin cortos',np.round(limitada,5))
print('Varianzas:',round(float(libre@Sigma@libre),8),round(float(limitada@Sigma@limitada),8))
targets = np.linspace(mu.min(),mu.max(),41)
free = np.array([frontier(mu,Sigma,m) for m in targets])
long = np.array([constrained(mu,Sigma,m,[(0.,1.)]*len(mu)) for m in targets])
std = lambda w: np.sqrt(np.einsum('ij,jk,ik->i',w,Sigma,w))
fig,ax=plt.subplots()
ax.plot(std(free),targets,label='Sin restricciones')
ax.plot(std(long),targets,label='Sin cortos')
ax.set_xlabel('Volatilidad anual'); ax.set_ylabel('Media anual')
ax.legend(); plt.show()The constrained frontier is not polygonal in the standard-deviation and mean plane: it changes regime when the active constraint set changes. For a feasible target, its variance cannot be lower than the unconstrained solution because it optimizes over a subset of portfolios.
At the 11% target, the first unconstrained position is negative: prohibiting it changes the optimal portfolio. The last two positions in the constrained solution are 0.25 and 0.75, since their 8% and 12% means must combine to reach 11%. Constrained variance exceeds unconstrained variance. This comparison is a calculation for the cell’s hypothetical parameters, not a market estimate.
Lab: ten sectors and a temporal split
The Kenneth French Data Library publishes ten industry portfolios; its description explains the industry classification. Download the monthly value-weighted series expressed in percentages. The following lab requires local Python and network access because the browser does not have a built-in copy of the data here. Use a fixed window from July 1926 to December 2024, split it chronologically into halves and estimate the long-only frontier using only the first. Apply fixed weights to the second half, rebalancing monthly. The second half is not used to select portfolios.
For comparability we show monthly mean multiplied by 12 and monthly volatility multiplied by : these are scaling conventions, not annual compounded return or an identity under temporal dependence. We do not subtract costs or assume the sample proves future profitability. The library may revise its history, so retain the date and downloaded ZIP if you need to reproduce a run exactly.
import io, zipfile, urllib.request
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.optimize import minimize
url = 'https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/ftp/10_Industry_Portfolios_CSV.zip'
with urllib.request.urlopen(url, timeout=30) as response:
archivo = response.read()
with zipfile.ZipFile(io.BytesIO(archivo)) as z:
texto = z.read(z.namelist()[0]).decode('latin1')
lineas = texto.splitlines()
cabecera = next(i for i,linea in enumerate(lineas) if 'Average Value Weighted Returns -- Monthly' in linea)
filas = []
for linea in lineas[cabecera+2:]:
partes = [p.strip() for p in linea.split(',')]
if len(partes) != 11 or len(partes[0]) != 6 or not partes[0].isdigit():
break
filas.append([int(partes[0])] + [float(x) for x in partes[1:]])
datos = np.array(filas)
datos = datos[(datos[:,0]>=192607)&(datos[:,0]<=202412)]
if len(datos)!=1182 or np.any(datos[:,1:]<=-99):
raise ValueError('Ventana incompleta o datos ausentes: revisa el archivo')
r = datos[:,1:]/100
mitad = len(r)//2
train, test = r[:mitad], r[mitad:]
mu1, cov1 = train.mean(axis=0), np.cov(train,rowvar=False,ddof=1)
mu2, cov2 = test.mean(axis=0), np.cov(test,rowvar=False,ddof=1)
n = len(mu1)
def optimize(target):
res = minimize(lambda w: .5*w@cov1@w,np.full(n,1/n),jac=lambda w: cov1@w,
bounds=[(0,1)]*n, method='SLSQP',
constraints=[{'type':'eq','fun':lambda w:w.sum()-1,'jac':lambda w:np.ones(n)},
{'type':'eq','fun':lambda w:mu1@w-target,'jac':lambda w:mu1}],
options={'ftol':1e-12,'maxiter':500})
if not res.success or abs(res.x.sum()-1)>1e-7 or abs([email protected])>1e-7:
raise RuntimeError(res.message)
return res.x
objetivos=np.linspace(mu1.min(),mu1.max(),21)
pesos=np.array([optimize(m) for m in objetivos])
def momentos(w,mu,cov):
return np.sqrt(12*np.einsum('ij,jk,ik->i',w,cov,w)), 12*(w@mu)
riesgo1,media1=momentos(pesos,mu1,cov1)
riesgo2,media2=momentos(pesos,mu2,cov2)
fig,ax=plt.subplots()
ax.plot(riesgo1,media1,'-o',ms=3,label='Ajuste: primera mitad')
ax.scatter(riesgo2,media2,s=20,label='Mismos pesos: segunda mitad')
ax.set_xlabel('Volatilidad anualizada'); ax.set_ylabel('Media anualizada')
ax.legend(); plt.show()
print('Meses entrenamiento y evaluación:',len(train),len(test))
print('Intervalos:',int(datos[0,0]),int(datos[mitad-1,0]),int(datos[mitad,0]),int(datos[-1,0]))
print('Máximo error presupuestario:',np.max(np.abs(pesos.sum(axis=1)-1)))
print('Cartera central: media y volatilidad anualizadas, ajuste:',
round(float(media1[10]),4),round(float(riesgo1[10]),4),
'| evaluación:',round(float(media2[10]),4),round(float(riesgo2[10]),4))npm run lab and open the connection link.Each evaluation point corresponds to a portfolio chosen before seeing that period. The shift between points incorporates changes in means and covariances as well as estimation error; this single split does not by itself identify the cause of each difference. The next lesson studies parameter sensitivity in greater detail.
Exercise: minimum with two assets
Step 1 of 3. Which property of the closed-form solution do you need?
Step 1 of 3. What stationarity condition does half the variance give with two multipliers?
def tangency_weights(mu, cov, rf):
raise NotImplementedError()Summary
- GMV depends on covariance, while the tangency portfolio also depends on expected premiums and the risk-free rate.
- Two-fund separation follows from the affine dependence of weights on target mean under the unconstrained solution’s assumptions.
- A constrained optimizer requires checking feasibility and optimality conditions; out-of-sample results must be evaluated without using future information.