AnyLearn
All lessons
Businessintermediate

Mean-Variance Optimization: The Mathematics of Diversification

Portfolio risk is not the average of the risks inside it. Learn Markowitz's mean-variance framework, how correlation sets the limit of diversification, how the minimum-variance and tangency portfolios are computed, and what the model quietly assumes about its inputs.

Updated · AI-authored, review-gated · how lessons are made

Not signed in: your progress and quiz score won't be saved.
Progress1 / 10

The question Markowitz asked

Before 1952, investment advice mostly meant finding the best individual securities. Harry Markowitz's paper "Portfolio Selection" (Journal of Finance, 1952) changed the unit of analysis: judge a holding by what it does to the whole portfolio, and judge the portfolio by two numbers together, its expected return and its variance.

The insight that follows is arithmetic, not opinion. The risk of a portfolio depends on how its holdings move together, so two risky assets can combine into something less risky than either one. A security that looks mediocre alone can be valuable if it tends to rise when the rest of the portfolio falls.

Key idea: Expected returns average linearly: a 50/50 mix of a 5% asset and a 9% asset expects 7%. Risk does not. Unless the assets move in perfect lockstep, the mix is less volatile than the weighted average of their volatilities. That gap is the only free lunch the framework offers, and the rest of this course is about how much of it survives contact with real data.

Full lesson text

All 10 steps on one page, for reading, reference, and search.

Show

1. The question Markowitz asked

Before 1952, investment advice mostly meant finding the best individual securities. Harry Markowitz's paper "Portfolio Selection" (Journal of Finance, 1952) changed the unit of analysis: judge a holding by what it does to the whole portfolio, and judge the portfolio by two numbers together, its expected return and its variance.

The insight that follows is arithmetic, not opinion. The risk of a portfolio depends on how its holdings move together, so two risky assets can combine into something less risky than either one. A security that looks mediocre alone can be valuable if it tends to rise when the rest of the portfolio falls.

Key idea: Expected returns average linearly: a 50/50 mix of a 5% asset and a 9% asset expects 7%. Risk does not. Unless the assets move in perfect lockstep, the mix is less volatile than the weighted average of their volatilities. That gap is the only free lunch the framework offers, and the rest of this course is about how much of it survives contact with real data.

2. Portfolio return and variance

Write the portfolio as a weight vector ww over nn assets, with expected returns μ\mu and covariance matrix Σ\Sigma. Then:

μp=w⊤μ,σp2=w⊤Σ w\mu_p = w^\top \mu, \qquad \sigma_p^2 = w^\top \Sigma \, w

For two assets the variance expands into three terms:

σp2=w12σ12+w22σ22+2 w1w2 ρ12 σ1σ2\sigma_p^2 = w_1^2\sigma_1^2 + w_2^2\sigma_2^2 + 2\,w_1 w_2\,\rho_{12}\,\sigma_1\sigma_2

The last term is where diversification lives. The correlation ρ12\rho_{12} runs from −1-1 to +1+1. At +1+1 the formula collapses to (w1σ1+w2σ2)2(w_1\sigma_1 + w_2\sigma_2)^2, a plain weighted average of volatilities, and there is no benefit at all. Anything below +1+1 shrinks the cross term and pulls portfolio volatility below the average.

Definition: The covariance matrix Σ\Sigma holds every asset's variance on its diagonal and every pair's covariance, ρijσiσj\rho_{ij}\sigma_i\sigma_j, off it. With nn assets it has n(n+1)/2n(n+1)/2 distinct entries: 55 for 10 assets, 1,275 for 50. Every one of them is an estimate, a fact the next lesson makes central.

3. Correlation sets the benefit

Take two assets that each have 20% annual volatility and hold them 50/50. The only thing that changes below is the correlation between them.

Volatility of a 50/50 mix of two 20%-volatility assets
Portfolio volatility (annual) (%)05101520-1.0-0.500.51.0
Source: Computed from the two-asset variance formula: sigma 20% each, weights 0.5 each

At a correlation of 1 the mix is exactly as risky as each asset, 20%. At 0.5 it falls to 17.3%, at zero to 14.1%, and at minus 0.5 to 10%. At minus 1 the two assets cancel perfectly and the portfolio has no volatility at all.

Gotcha: Correlations are not constant. Longin and Solnik (Journal of Finance, 2001) found that correlations between international equity markets rise in bear markets but not in bull markets, so diversification can weaken exactly when it was supposed to help. The formula is right; the input is the fragile part.

4. How many assets is enough?

Now hold NN assets in equal weights, each with 20% volatility and a pairwise correlation of 0.3. The portfolio variance simplifies to

σp2=σ2(1N+(1−1N)ρ)\sigma_p^2 = \sigma^2\left(\frac{1}{N} + \Big(1 - \frac{1}{N}\Big)\rho\right)
Assets NNPortfolio volatility
120.00%
216.12%
513.27%
1012.17%
3011.37%
10011.08%
Predict first

As N grows without limit, what volatility does this portfolio approach?

Most of the benefit arrives early: going from 1 to 10 assets cuts volatility from 20% to 12.2%, while going from 10 to 100 cuts it only another 1.1 points.

5. The efficient frontier

Markowitz posed portfolio choice as an optimisation. For each target return, find the weights with the smallest variance:

min⁡w  w⊤Σwsubject tow⊤μ=μ∗,w⊤1=1\min_{w} \; w^\top \Sigma w \quad \text{subject to} \quad w^\top \mu = \mu^{*}, \quad w^\top \mathbf{1} = 1

Solving this for every target μ∗\mu^{*} traces the efficient frontier: the set of portfolios for which no other portfolio offers more expected return at the same risk. Two points on it get names.

  • Global minimum-variance portfolio: the lowest-risk point on the frontier. Without further constraints it has a closed form, wmv=Σ−11/(1⊤Σ−11)w_{\text{mv}} = \Sigma^{-1}\mathbf{1} / (\mathbf{1}^\top \Sigma^{-1}\mathbf{1}), and notably it uses no expected returns at all.
  • Tangency portfolio: the frontier point with the highest ratio of expected excess return to volatility, wtan=Σ−1μ/(1⊤Σ−1μ)w_{\text{tan}} = \Sigma^{-1}\mu / (\mathbf{1}^\top \Sigma^{-1}\mu), where μ\mu is measured in excess of the risk-free rate.

Definition: The Sharpe ratio, introduced by William Sharpe in 1966, is expected excess return divided by volatility. The tangency portfolio is the fully invested portfolio that maximises it.

6. A three-asset example: the inputs

Here is a small, fully specified problem you can reproduce. Expected returns are annual and in excess of the risk-free rate.

AssetExpected excess returnVolatility
A5%10%
B7%15%
C9%20%
CorrelationABC
A10.30.2
B0.310.5
C0.20.51

Notice what these inputs imply before any optimisation. Asset A has the lowest return but also the lowest volatility and the weakest correlations with the others, so it is the natural diversifier. Asset C pays the most but is the riskiest and is fairly correlated with B. Every asset here offers between 0.45 and 0.5 units of excess return per unit of its own volatility, so on its own no asset stands out. The optimiser's job is to exploit how they combine.

Try it: Before reading on, guess which asset gets the largest weight in the minimum-variance portfolio, and whether the equally weighted portfolio is far from the best Sharpe ratio.

7. Three portfolios, side by side

Solving the closed forms from the previous steps on these inputs gives:

PortfolioWeights A / B / CExpected returnVolatilitySharpe ratio
Minimum variance74.5% / 18.5% / 7.0%5.65%9.25%0.611
Tangency57.8% / 22.3% / 20.0%6.24%9.73%0.642
Equal weight (1/N)33.3% / 33.3% / 33.3%7.00%11.52%0.607

Three things stand out. The minimum-variance portfolio is less volatile, at 9.25%, than the least volatile asset, A at 10%: diversification doing its job. The optimiser leans heavily on A, because low volatility combined with low correlation is exactly what the variance formula rewards.

And the headline: with the inputs known exactly, the best achievable Sharpe ratio is 0.642, while simply splitting the money three ways gives 0.607. The whole value of optimising here is a gain of 0.035 in Sharpe ratio. Hold on to that number: the next lesson asks what happens to it once the inputs are estimated rather than known.

8. Computing it in numpy

Both named portfolios are one linear solve each. Solving is preferable to forming Σ−1\Sigma^{-1} explicitly, which is slower and less numerically stable.

import numpy as np

mu  = np.array([0.05, 0.07, 0.09])            # expected excess returns
vol = np.array([0.10, 0.15, 0.20])
corr = np.array([[1.0, 0.3, 0.2],
                 [0.3, 1.0, 0.5],
                 [0.2, 0.5, 1.0]])
Sigma = np.outer(vol, vol) * corr              # covariance matrix

def normalise(x):
    return x / x.sum()

w_minvar  = normalise(np.linalg.solve(Sigma, np.ones(3)))
w_tangent = normalise(np.linalg.solve(Sigma, mu))

for name, w in [("min variance", w_minvar), ("tangency", w_tangent)]:
    ret, risk = w @ mu, np.sqrt(w @ Sigma @ w)
    print(f"{name:13s} {np.round(w, 3)}  ret {ret:.2%}  vol {risk:.2%}  SR {ret/risk:.3f}")
# min variance  [0.745 0.185 0.07 ]  ret 5.65%  vol 9.25%  SR 0.611
# tangency      [0.578 0.223 0.2  ]  ret 6.24%  vol 9.73%  SR 0.642

Nothing here restricts weights to be positive. With other inputs these formulas happily return large short positions, which is the first sign of the fragility the next lesson measures.

9. What goes in, what comes out

The optimiser is exact. Everything uncertain enters through its three inputs.

flowchart LR
  A["Expected returns: n estimates"] --> D["Mean-variance optimiser"]
  B["Volatilities: n estimates"] --> D
  C["Correlations: n(n-1)/2 estimates"] --> D
  E["Constraints: budget, limits"] --> D
  D --> F["Weights"]
  F --> G["Realised performance on future data"]

10. What the model assumes

Mean-variance optimisation is a clean answer to a precisely stated question. The question carries assumptions worth listing before using the answer:

  1. The inputs are known. The formulas treat μ\mu and Σ\Sigma as facts. In practice both are estimated from limited, noisy history.
  2. Variance is the right measure of risk. It penalises upside and downside surprises equally and says nothing about fat tails; the trading risk course on AnyLearn covers what variance hides.
  3. One period. The portfolio is chosen once for a single horizon, with no rebalancing and no path.
  4. No frictions. Trading is free, any position size is available, and shorting costs nothing.

Key idea: The optimiser does not know which of its inputs are reliable. It treats a noisy estimate of an expected return with the same confidence as a precise one, and it will build large positions on small differences between them. Whether that matters in practice, and by how much, is an empirical question with a well-documented answer, and it is the subject of the next lesson.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. Two assets each have 20% volatility and a correlation of 0. What is the volatility of a 50/50 mix?
    • 20%
    • 10%
    • About 14.1%
    • 0%
  2. In an equally weighted portfolio of many assets with 20% volatility and pairwise correlation 0.3, what does volatility approach as the number of assets grows?
    • About 10.95%, set by the correlation
    • 0%, because all risk diversifies away
    • 20%, because each asset keeps its risk
    • 6%, which is 20% times 0.3
  3. Which portfolio on the efficient frontier can be computed without any expected-return estimates?
    • The tangency portfolio
    • The maximum-return portfolio
    • Any portfolio with a Sharpe ratio above 0.5
    • The global minimum-variance portfolio
  4. In the lesson's three-asset example with inputs known exactly, how much Sharpe ratio does the tangency portfolio gain over equal weighting?
    • About 0.5
    • About 0.035
    • About 0.2
    • None, they are identical
  5. Why can the minimum-variance portfolio be less volatile than its least volatile asset?
    • Because it holds cash
    • Because it ignores correlations
    • Because imperfect correlation makes part of each asset's risk cancel in the mix
    • Because volatility is measured monthly instead of annually

Related lessons

Business
intermediate

Practical Portfolio Construction: Minimum Variance, Risk Parity and Rebalancing

When expected returns cannot be trusted, portfolios are built from risk instead. Learn how to measure each holding's risk contribution, how minimum variance and equal risk contribution portfolios work and differ, what leverage does to them, and how rebalancing and turnover turn a weight rule into a real strategy.

10 steps·~15 min
Business
intermediate

Estimation Error: Why Optimized Portfolios Disappoint

Mean-variance optimization treats its inputs as facts, and they are estimates. See why expected returns are nearly impossible to estimate, how optimizers magnify the noise, why simple 1/N weighting is so hard to beat out of sample, and how shrinkage and constraints recover much of the loss.

10 steps·~15 min
AI
advanced

Building Something That Holds Up

Given that the tradable-signal path is narrow and hard to evidence, the systems worth building are the ones the first lesson identified: extraction at scale. This lesson covers the engineering that makes them survive audit, the evaluation that does not depend on returns, and the governance obligations that apply once a model touches a regulated process.

8 steps·~12 min
AI
advanced

Where LLMs Actually Fit in a Trading Firm

The popular framing is a model that predicts prices. That is the one job the technology is worst suited to, and it obscures the one it is genuinely good at: turning unstructured text into structured data at a scale that was previously unaffordable. This lesson locates LLMs against the trading stack and rules out the places they cannot go.

8 steps·~12 min