Module contents
Lesson 3 of 30Core 100 min

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.

InteractiveTwo assets and a correlation
  • Long-only combinations
  • Selected portfolio
0.20
50.0 %
Portfolio volatility19.6 %
Portfolio mean10.0 %
Drag the assets and change correlation. At correlation −1, find the weight that brings the curve to zero volatility.

For simple returns R1,R2R_1,R_2 over the same horizon, the portfolio Rp=wR1+(1−w)R2R_p=wR_1+(1-w)R_2 has mean wμ1+(1−w)μ2w\mu_1+(1-w)\mu_2 and variance

σp2=w2σ12+(1−w)2σ22+2w(1−w)ρσ1σ2.\sigma_p^2=w^2\sigma_1^2+(1-w)^2\sigma_2^2+2w(1-w)\rho\sigma_1\sigma_2.

This identity follows from the variance of a sum. If ρ=−1\rho=-1, σp=∣wσ1−(1−w)σ2∣\sigma_p=|w\sigma_1-(1-w)\sigma_2|. For positive volatilities, weight w=σ2/(σ1+σ2)w=\sigma_2/(\sigma_1+\sigma_2) eliminates variance. This requires exactly negative and stable correlation, an idealized assumption. If ρ=1\rho=1, 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 R∈Rn\vb{R}\in\R^n be the simple-return vector, μ=E[R]\vb{\mu}=\E[\vb{R}] and Σ=Cov⁡(R)\mat{\Sigma}=\Cov(\vb{R}). Weights w\vb{w} are fractions of initial wealth, with 1⊤w=1\vb{1}\T\vb{w}=1. The mean is μ⊤w\vb{\mu}\T\vb{w} and variance is the quadratic form w⊤Σw\vb{w}\T\mat{\Sigma}\vb{w}. 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 mm:

min⁡w w⊤Σw,1⊤w=1,μ⊤w=m.\min_{\vb{w}}\ \vb{w}\T\mat{\Sigma}\vb{w},\qquad \vb{1}\T\vb{w}=1,\quad \vb{\mu}\T\vb{w}=m.

Another formulation maximizes μ⊤w−γw⊤Σw/2\vb{\mu}\T\vb{w}-\gamma\vb{w}\T\mat{\Sigma}\vb{w}/2 with γ>0\gamma>0, 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 Σ\mat{\Sigma} is symmetric positive definite and μ\vb{\mu} is not proportional to 1\vb{1}. Define

A=1⊤Σ−11,B=1⊤Σ−1μ,C=μ⊤Σ−1μ,D=AC−B2.A=\vb{1}\T\mat{\Sigma}\inv\vb{1},\quad B=\vb{1}\T\mat{\Sigma}\inv\vb{\mu},\quad C=\vb{\mu}\T\mat{\Sigma}\inv\vb{\mu},\quad D=AC-B^2.

The Cauchy-Schwarz inequality in the inner product induced by Σ−1\mat{\Sigma}\inv gives D>0D>0 under these assumptions. Applying Lagrange multipliers to half the variance, the stationarity condition is Σw=λ1+ημ\mat{\Sigma}\vb{w}=\lambda\vb{1}+\eta\vb{\mu}. The two constraints give Aλ+Bη=1A\lambda+B\eta=1 and Bλ+Cη=mB\lambda+C\eta=m. Solving,

w(m)=Σ−1[C−BmD1+Am−BDμ].\vb{w}(m)=\mat{\Sigma}\inv\left[\frac{C-Bm}{D}\vb{1}+\frac{Am-B}{D}\vb{\mu}\right].

The solution is unique: the objective is strictly convex and the constraints are affine. Substituting or using w⊤Σw=λ+ηm\vb{w}\T\mat{\Sigma}\vb{w}=\lambda+\eta m,

σ2(m)=Am2−2Bm+CD=1A+AD(m−BA)2.\sigma^2(m)=\frac{Am^2-2Bm+C}{D}=\frac1A+\frac{A}{D}\left(m-\frac BA\right)^2.

In the (σ,μ)(\sigma,\mu) plane this equation is a hyperbola; in (σ2,μ)(\sigma^2,\mu) it is a parabola. The efficient frontier is only the branch with m≥B/Am\ge B/A: for a given risk, the lower branch offers a lower mean.

To see why, fix a variance greater than 1/A1/A. The equation permits two means equidistant from B/AB/A. 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 wGMV=Σ−11/A\vb{w}_{\rm GMV}=\mat{\Sigma}\inv\vb{1}/A, with mean B/AB/A and variance 1/A1/A. 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 w=wGMV+h\vb{w}=\vb{w}_{\rm GMV}+\vb{h}, with 1⊤h=0\vb{1}\T\vb{h}=0. Then

w⊤Σw=1A+2h⊤ΣwGMV+h⊤Σh=1A+h⊤Σh.\vb{w}\T\mat{\Sigma}\vb{w}=\frac1A+2\vb{h}\T\mat{\Sigma}\vb{w}_{\rm GMV}+\vb{h}\T\mat{\Sigma}\vb{h} =\frac1A+\vb{h}\T\mat{\Sigma}\vb{h}.

The cross term vanishes because ΣwGMV=1/A\mat{\Sigma}\vb{w}_{\rm GMV}=\vb{1}/A. Positive definiteness makes the last term strictly positive except when h=0\vb{h}=0, proving uniqueness. If Σ\mat{\Sigma} 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 Σ=Qdiag⁡(λi)Q⊤\mat{\Sigma}=\mat{Q}\diag(\lambda_i)\mat{Q}\T, solving with it multiplies the component along each eigenvector by 1/λi1/\lambda_i. 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.

InteractiveBuild a frontier
  • Long-only portfolios
  • Unconstrained frontier
  • Unconstrained GMV
  • Unconstrained tangency portfolio and line
5.0 %
10.0 %
2.0 %
Correlation matrix
Unconstrained GMV: volatility8.5 %
Unconstrained tangency: mean8.9 %
Edit means, volatilities and correlations for five hypothetical assets. The curve shows targets between the smallest and largest individual means and changes when shorting is prohibited; the GMV and tangency points and the line are unconstrained solutions. To retain a valid correlation, edit both symmetric entries and keep the diagonal at one.

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 w(m)\vb{w}(m) is affine in mm, if m1≠m2m_1\ne m_2, any portfolio on this frontier can be written w(m)=tw(m1)+(1−t)w(m2)\vb{w}(m)=t\vb{w}(m_1)+(1-t)\vb{w}(m_2) with t=(m−m2)/(m1−m2)t=(m-m_2)/(m_1-m_2). 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 m−γσ2(m)/2m-\gamma\sigma^2(m)/2 clarifies its relationship to the fixed target. The derivative with respect to mm is 1−γA(m−B/A)/D1-\gamma A(m-B/A)/D, which is zero at m=B/A+D/(Aγ)m=B/A+D/(A\gamma). Because the second derivative is negative, this is the unique solution for γ>0\gamma>0. As γ\gamma 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 rfr_f over the same horizon and premium vector a=μ−rf1\vb{a}=\vb{\mu}-r_f\vb{1}, the direction of maximum positive Sharpe is proportional to Σ−1a\mat{\Sigma}\inv\vb{a}. If 1⊤Σ−1a>0\vb{1}\T\mat{\Sigma}\inv\vb{a}>0, normalize it to budget one:

wT=Σ−1(μ−rf1)1⊤Σ−1(μ−rf1).\vb{w}_T=\frac{\mat{\Sigma}\inv(\vb{\mu}-r_f\vb{1})}{\vb{1}\T\mat{\Sigma}\inv(\vb{\mu}-r_f\vb{1})}.

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: w⊤a≤w⊤Σwa⊤Σ−1a\vb{w}\T\vb{a}\le\sqrt{\vb{w}\T\mat{\Sigma}\vb{w}}\sqrt{\vb{a}\T\mat{\Sigma}\inv\vb{a}}, with equality when w\vb{w} is a positive multiple of Σ−1a\mat{\Sigma}\inv\vb{a}.

The inequality follows by applying Cauchy-Schwarz to Σ1/2w\mat{\Sigma}^{1/2}\vb{w} and Σ−1/2a\mat{\Sigma}^{-1/2}\vb{a}. Their inner product is w⊤a\vb{w}\T\vb{a}, and their norms are volatility and the square root of a⊤Σ−1a\vb{a}\T\mat{\Sigma}\inv\vb{a}, 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 μp=rf+STσp\mu_p=r_f+S_T\sigma_p for positive exposure to the tangency portfolio. Its slope is maximum Sharpe ST=a⊤Σ−1aS_T=\sqrt{\vb{a}\T\mat{\Sigma}\inv\vb{a}}. 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 μw\mu_w and variance σw2>0\sigma_w^2>0. With exposure α∈[0,1]\alpha\in[0,1], invest the remainder at rate rlr_l and its mean is rl+α(μw−rl)r_l+\alpha(\mu_w-r_l). For α≥1\alpha\ge1, finance the excess at rate rb≥rlr_b\ge r_l, and the mean is rb+α(μw−rb)r_b+\alpha(\mu_w-r_b). The expressions agree at α=1\alpha=1 but have different slopes. Under mean-variance utility, stationary exposure within each regime is (μw−rj)/(γσw2)(\mu_w-r_j)/(\gamma\sigma_w^2), with j=lj=l or bb; restrict it to the corresponding interval and also compare α=1\alpha=1. Then optimize the risky composition. Extending the lending line beyond the borrowing point is insufficient.

InteractiveRotate toward tangency
  • Two-asset frontier
  • Selected line
  • Tangent
2.0 %
100.0 %
Selected Sharpe ratio0.300
Maximum Sharpe ratio0.410
Tangency weight in asset 156.1 %
Vary the portfolio weight to rotate its line from the risk-free rate. Compare its slope with the tangent and change the rate. The model uses the same two hypothetical assets as the first figure in its initial state, with correlation 0.2.

Practical constraints

The closed-form solution can contain short positions or large gross leverage ∑i∣wi∣\sum_i|w_i|. Long-only portfolios add wi≥0w_i\ge0; per-asset limits add wi≤uiw_i\le u_i. To limit gross leverage, introduce auxiliary variables zi≥wiz_i\ge w_i, zi≥−wiz_i\ge-w_i and ∑izi≤L\sum_i z_i\le L. A market-neutral portfolio may impose β⊤w=0\vb{\beta}\T\vb{w}=0 if exposures β\vb{\beta} 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 wi≥0w_i\ge0 and an imposed mean target, write the Lagrangian as L=12w⊤Σw−λ(1⊤w−1)−η(μ⊤w−m)−α⊤wL=\tfrac12\vb{w}\T\mat{\Sigma}\vb{w}-\lambda(\vb{1}\T\vb{w}-1)-\eta(\vb{\mu}\T\vb{w}-m)-\vb{\alpha}\T\vb{w}. The conditions are Σw−λ1−ημ−α=0\mat{\Sigma}\vb{w}-\lambda\vb{1}-\eta\vb{\mu}-\vb{\alpha}=0, w≥0\vb{w}\ge0, α≥0\vb{\alpha}\ge0 and αiwi=0\alpha_iw_i=0, 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.

[ ]Closed-form frontierBrowser
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 0≤wi≤10\le w_i\le1 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.

[ ]SLSQP and comparisonBrowser
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 12\sqrt{12}: 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.

[ ]Sectors: training versus evaluationLocal GPU
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))
This cell needs the local lab (PyTorch with your GPU). Start it with 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

NumericMinimum-variance weight
Two assets have volatilities of 20% and 30% and correlation 0.2. Calculate the first asset's weight in the unconstrained minimum-variance portfolio.
QuizTwo sources of error
Why can the global minimum-variance portfolio be more stable out of sample than the tangency portfolio?
ProofTwo funds
Prove: Prove that each minimum-variance portfolio for a target mean is an affine combination of two frontier portfolios with distinct means.
0
Assume Σ\mat{\Sigma} is positive definite and D>0D>0, and take m1≠m2m_1\ne m_2.

Step 1 of 3. Which property of the closed-form solution do you need?

ProofDerive the frontier
Prove: Obtain the minimum variance for mean mm under the assumptions in the text.
The proof will appear here as you work.

Step 1 of 3. What stationarity condition does half the variance give with two multipliers?

CodeTangency portfolio
Implement tangency_weights(mu, cov, rf). Solve a linear system and normalize the weights; raise ValueError if the denominator is not positive. Tests use positive-definite covariances.
def tangency_weights(mu, cov, rf):
  raise NotImplementedError()
Shift+Enter to run

Summary

Key idea
The frontier turns covariances into a choice between mean and risk. Its geometry is exact for the assumed parameters; actual portfolio quality depends on how those parameters are estimated and constrained.
  • 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.