Skip to content
LeetQuant
E05 Advanced Optimisation

E05 · Advanced Optimisation · Lesson 3 of 4

Quadratic Programming

Portfolio construction with budget, long-only, position-cap and turnover constraints as a quadratic programme, active-set intuition worked by hand, and a scipy solution whose KKT conditions are checked numerically.

20 min

Portfolio construction is a QP

A quadratic programme is

min⁡x 12x⊤Px+q⊤xs.t.Gx≤h,  Ax=b,\min_x\ \tfrac12 x^\top Px + q^\top x \quad \text{s.t.}\quad Gx \le h,\ \ Ax = b,

convex when P⪰0P \succeq 0, with a unique solution when P≻0P \succ 0. Mean–variance portfolio choice, maximising μ⊤w−γ2w⊤Σw\mu^\top w - \tfrac\gamma2 w^\top\Sigma w, is the QP with P=γΣP = \gamma\Sigma and q=−μq = -\mu. Almost every constraint a desk imposes is linear:

ConstraintLinear form
Fully invested1⊤w=1\mathbf 1^\top w = 1
Long-only, position caps0≤wi≤ci0 \le w_i \le c_i
Sector or country limits∑i∈Swi≤s\sum_{i \in S} w_i \le s
Factor neutralityB⊤w=0B^\top w = 0 (betas, sector loadings)
Turnover ∥w−w0∥1≤T\|w - w_0\|_1 \le Tw−w0=u−vw - w_0 = u - v, u,v≥0u, v \ge 0, 1⊤(u+v)≤T\mathbf 1^\top(u + v) \le T
Gross leverage ∥w∥1≤ℓ\|w\|_1 \le \ellsame split applied to ww
Linear costs κ⊤∥w−w0∥\kappa^\top\|w - w_0\|add κ⊤(u+v)\kappa^\top(u + v) to the objective

The split turns a nonsmooth absolute value into linear constraints. It needs no condition uivi=0u_i v_i = 0: if both were positive, reducing each by min⁡(ui,vi)\min(u_i, v_i) keeps ww unchanged and only loosens the turnover constraint (or lowers the cost), so some optimal solution never trades both ways. The price is 3n3n variables instead of nn, which QP solvers handle easily because the extra structure is sparse.

Constraints that are not QP: a tracking-error or volatility limit is a second-order cone constraint (use an SOCP solver, or put it in the objective with a multiplier, which by duality gives the same solution for the right multiplier); market-impact costs proportional to ∣Δw∣3/2|\Delta w|^{3/2} are convex but not quadratic; cardinality and minimum lot sizes need integer variables.

Active-set intuition

If you knew which inequalities bind at the optimum, the QP would reduce to an equality-constrained QP, whose KKT conditions are one linear system:

(PAW⊤AW0)(xλ)=(−qbW),\begin{pmatrix} P & A_{\mathcal W}^\top \\ A_{\mathcal W} & 0 \end{pmatrix}\begin{pmatrix} x \\ \lambda \end{pmatrix} = \begin{pmatrix} -q \\ b_{\mathcal W} \end{pmatrix},

where W\mathcal W (the working set) is the equalities plus the inequalities treated as active. An active-set method guesses W\mathcal W, solves this system, and repairs the guess:

  1. If xx violates an inequality not in W\mathcal W, move towards xx only as far as feasibility allows and add the blocking constraint to W\mathcal W.
  2. If xx is feasible but some inequality in W\mathcal W has a multiplier with the wrong sign, that constraint is pulling the solution rather than pushing it: drop it from W\mathcal W.
  3. If xx is feasible and every multiplier has the right sign, KKT holds: stop.

Each change of W\mathcal W strictly improves the objective, so no working set repeats and the method terminates (degenerate cases need anti-cycling rules). Its great practical strength is warm-starting: a daily rebalance usually has almost the same active set as yesterday's, so a few iterations suffice. Interior-point methods instead keep all inequalities strictly satisfied and follow a central path; they take a predictable 10 to 50 iterations regardless of the number of active constraints and suit large, cold-started problems. First-order splitting methods (ADMM, as in OSQP) trade accuracy for cheap iterations on very large sparse problems.

Two structural facts the active-set view makes obvious:

  • Optimal portfolios are corner solutions: with nn assets and many binding bounds, a large share of names sit exactly at 00 or at their cap. That is the KKT geometry, not a bug.
  • Because the solution is piecewise linear in μ\mu between changes of active set, a small change in expected returns can switch the active set and move weights a lot. Unstable inputs, not the QP, are usually the problem; shrinkage of μ\mu and Σ\Sigma, position caps and turnover penalties all help.

Worked example

long-only mean–variance by active set

Three uncorrelated assets have μ=(8%,6%,0%)\mu = (8\%, 6\%, 0\%) and volatilities (20%,20%,10%)(20\%, 20\%, 10\%); risk aversion γ=2\gamma = 2. Maximise μ⊤w−γ2w⊤Σw\mu^\top w - \tfrac\gamma2 w^\top\Sigma w subject to 1⊤w=1\mathbf 1^\top w = 1, first without and then with w≥0w \ge 0. Give the multipliers and interpret the budget multiplier.

Show solution

Minimise γ2w⊤Σw−μ⊤w\tfrac\gamma2 w^\top\Sigma w - \mu^\top w with Lagrangian …+ν(1⊤w−1)−λ⊤w\ldots + \nu(\mathbf 1^\top w - 1) - \lambda^\top w. With Σ\Sigma diagonal, stationarity row by row is

γσi2wi=μi−ν+λi,γσi2=(0.08, 0.08, 0.02).\gamma\sigma_i^2 w_i = \mu_i - \nu + \lambda_i, \qquad \gamma\sigma_i^2 = (0.08,\ 0.08,\ 0.02) .

Working set {budget}. wi=(μi−ν)/(γσi2)w_i = (\mu_i - \nu)/(\gamma\sigma_i^2), and the budget gives 0.08−ν0.08+0.06−ν0.08+−ν0.02=1.75−75ν=1\tfrac{0.08 - \nu}{0.08} + \tfrac{0.06 - \nu}{0.08} + \tfrac{-\nu}{0.02} = 1.75 - 75\nu = 1, so ν=0.01\nu = 0.01 and w=(0.875, 0.625, −0.5)w = (0.875,\ 0.625,\ -0.5). Utility 0.1075−0.04875=0.058750.1075 - 0.04875 = 0.05875. The low-risk, zero-return asset is shorted to fund leverage in the others.

Repair. w3<0w_3 < 0 violates long-only: add w3≥0w_3 \ge 0 to the working set. Now w3=0w_3 = 0 and the budget over assets 1 and 2 gives 1.75−25ν=11.75 - 25\nu = 1, so ν=0.03\nu = 0.03 and w=(0.625, 0.375, 0)w = (0.625,\ 0.375,\ 0). The multiplier from row 3 is λ3=ν−μ3=0.03≥0\lambda_3 = \nu - \mu_3 = 0.03 \ge 0, and w1,w2>0w_1, w_2 > 0 so λ1=λ2=0\lambda_1 = \lambda_2 = 0. All KKT conditions hold: this is optimal, with utility 0.0725−0.02125=0.051250.0725 - 0.02125 = 0.05125.

Interpretation. The rule wi=max⁡(0,(μi−ν)/(γσi2))w_i = \max\big(0, (\mu_i - \nu)/(\gamma\sigma_i^2)\big) is "water-filling": ν\nu is a hurdle, and an asset is held only if its expected return beats it. Asset 3 would enter only if μ3>0.03\mu_3 > 0.03; λ3=0.03\lambda_3 = 0.03 is exactly its shortfall. The budget multiplier is the marginal utility of capital: with budget 1.011.01 the optimum rises by 0.0002980.000298, i.e. 0.02980.0298 per unit, matching ν=0.03\nu = 0.03 to first order. Long-only cost 0.00750.0075 of utility here.

A realistic rebalance with scipy, and a KKT audit

Four assets, current holdings equal-weighted, risk aversion γ=2\gamma = 2, long-only, a 40% cap per name and one-way turnover ∑i∣wi−w0,i∣≤0.40\sum_i|w_i - w_{0,i}| \le 0.40. Every inequality, including the sign constraints, is passed as a constraint rather than a bound so that the solver reports a multiplier for each.

import numpy as np
from scipy.optimize import minimize

mu = np.array([0.07, 0.05, 0.09, 0.03])   # expected returns
vol = np.array([0.15, 0.12, 0.25, 0.08])
corr = np.array([[1.0, 0.3, 0.5, 0.1],
                 [0.3, 1.0, 0.4, 0.2],
                 [0.5, 0.4, 1.0, 0.0],
                 [0.1, 0.2, 0.0, 1.0]])
Sigma = np.outer(vol, vol) * corr
gamma, cap, max_turnover = 2.0, 0.40, 0.40
w0 = np.full(4, 0.25)                      # current holdings
n = len(mu)

# Variables x = (w, u, v): w - w0 = u - v with u, v >= 0, so sum(u + v) bounds turnover.
def objective(x):
    w = x[:n]
    return 0.5 * gamma * w @ Sigma @ w - mu @ w

def gradient(x):
    w = x[:n]
    return np.concatenate([gamma * Sigma @ w - mu, np.zeros(2 * n)])

I, Z, z, o = np.eye(n), np.zeros((n, n)), np.zeros(n), np.ones(n)
A_eq = np.vstack([np.concatenate([o, z, z]),               # budget: sum w = 1
                  np.hstack([I, -I, I])])                  # w - u + v = w0
b_eq = np.concatenate([[1.0], w0])
A_in = np.vstack([np.concatenate([z, -o, -o]),             # T - sum(u + v) >= 0
                  np.hstack([-I, Z, Z]),                   # cap - w >= 0
                  np.eye(3 * n)])                          # w, u, v >= 0
b_in = np.concatenate([[max_turnover], cap * o, np.zeros(3 * n)])

cons = [{"type": "eq", "fun": lambda x: A_eq @ x - b_eq, "jac": lambda x: A_eq},
        {"type": "ineq", "fun": lambda x: A_in @ x + b_in, "jac": lambda x: A_in}]
x0 = np.concatenate([w0, z, z])
res = minimize(objective, x0, jac=gradient, method="SLSQP", constraints=cons,
               options={"ftol": 1e-12, "maxiter": 500})
w = res.x[:n]
print(res.message)
print("weights: ", np.round(w, 4))
print("trades:  ", np.round(w - w0, 4) + 0.0, "turnover", round(np.abs(w - w0).sum(), 4))
print("utility: ", round(-res.fun, 5))

# KKT check. SLSQP's Lagrangian is f - nu.(A_eq x - b_eq) - lam.(A_in x + b_in).
nu, lam = res.multipliers[:1 + n], res.multipliers[1 + n:]
slack = A_in @ res.x + b_in
stationarity = gradient(res.x) - A_eq.T @ nu - A_in.T @ lam
print("budget multiplier:   ", round(nu[0], 5))
print("turnover multiplier: ", round(lam[0], 5))
print("cap multipliers:     ", np.round(lam[1:1 + n], 5))
print("long-only mults:     ", np.round(lam[1 + n:1 + 2 * n], 5))
print(f"max |stationarity|:   {np.abs(stationarity).max():.1e}")
print(f"min slack:            {slack.min():.1e}")
print(f"min multiplier:       {lam.min():.1e}")
print(f"max |mult * slack|:   {np.abs(lam * slack).max():.1e}")
Optimization terminated successfully
weights:  [0.4  0.25 0.3  0.05]
trades:   [ 0.15  0.    0.05 -0.2 ] turnover 0.4
utility:  0.05138
budget multiplier:    -0.02947
turnover multiplier:  0.00203
cap multipliers:      [0.00643 0.      0.      0.     ]
long-only mults:      [0. 0. 0. 0.]
max |stationarity|:   4.0e-17
min slack:            -5.0e-17
min multiplier:       0.0e+00
max |mult * slack|:   2.3e-19

The last four lines are the KKT audit: stationarity holds to machine precision, every inequality is satisfied (a slack of −5×10−17-5 \times 10^{-17} is rounding), every inequality multiplier is non-negative, and complementary slackness holds. For a convex QP that is a proof of optimality, independent of how much you trust the solver.

Peeling the constraints back shows what each one costs (same data, re-solved):

ConstraintsWeightsUtility
Budget only(0.642, 0.298, 0.234, −0.174)(0.642,\ 0.298,\ 0.234,\ -0.174)0.052610.05261
+ long-only(0.576, 0.172, 0.252, 0)(0.576,\ 0.172,\ 0.252,\ 0)0.052190.05219
+ 40% cap(0.400, 0.296, 0.304, 0)(0.400,\ 0.296,\ 0.304,\ 0), turnover 0.500.500.051520.05152
+ turnover ≤0.40\le 0.40(0.400, 0.250, 0.300, 0.050)(0.400,\ 0.250,\ 0.300,\ 0.050)0.051380.05138

Worked example

reading the multipliers

Using the output above, interpret the budget, turnover and cap multipliers, and explain why asset 2 is not traded at all.

Show solution

Signs first. SLSQP writes the Lagrangian as f−ν⊤(equalities)−λ⊤(inequalities≥0)f - \nu^\top(\text{equalities}) - \lambda^\top(\text{inequalities} \ge 0), and ff is minus utility. So utility rises at rate λ\lambda per unit of loosening of an inequality, and the budget's marginal utility is −ν=0.02947-\nu = 0.02947.

Turnover: 0.002030.00203 utility per unit of extra turnover. Re-solving with T=0.4001T = 0.4001 raises utility at 0.002030.00203 per unit, confirming it. Equivalently, by duality, the turnover limit acts exactly like a linear trading cost of 0.002030.00203 (about 20 bp) per unit traded: replacing the constraint by that penalty and re-solving gives the same weights. That is the bridge between "turnover budget" and "transaction-cost model" conversations.

Cap on asset 1: 0.006430.00643 per unit: the cap is the more expensive constraint per unit, and lifting it to 40.01%40.01\% adds utility at that rate (checked by re-solving). Asset 1 wants more weight than it is allowed.

No-trade band. Write gi=μi−γ(Σw)ig_i = \mu_i - \gamma(\Sigma w)_i for the marginal utility of asset ii. Stationarity in (w,u,v)(w, u, v) says that at the optimum:

  • an asset being bought has gi=0.02947+0.00203g_i = 0.02947 + 0.00203 (plus its cap multiplier if capped);
  • an asset being sold has gi=0.02947−0.00203g_i = 0.02947 - 0.00203;
  • an asset not traded has gig_i anywhere in [0.02744, 0.03150][0.02744,\ 0.03150].

Computing gg at the solution gives (0.03793, 0.03109, 0.03150, 0.02744)(0.03793,\ 0.03109,\ 0.03150,\ 0.02744). Asset 1: 0.03793=0.02947+0.00203+0.006430.03793 = 0.02947 + 0.00203 + 0.00643 (bought, capped). Asset 3: upper edge (bought). Asset 4: lower edge (sold). Asset 2: 0.031090.03109 lies strictly inside the band, so it is not worth paying the turnover price to trade it. The ℓ1\ell_1 turnover term creates a band of inaction around each holding: the optimisation-theoretic origin of no-trade regions.

Knowledge check

To write max⁡w μ⊤w−γ2w⊤Σw\max_w\ \mu^\top w - \tfrac\gamma2 w^\top\Sigma w in the standard QP form min⁡x 12x⊤Px+q⊤x\min_x\ \tfrac12 x^\top Px + q^\top x, what are PP and qq?

Knowledge check

In an active-set iteration you solve the equality-constrained QP for the current working set and find a feasible point, but the multiplier of one active long-only constraint w_i ≥ 0 has the wrong sign. What should happen next?

Knowledge check

A rebalance QP with a turnover limit reports a budget marginal utility of 0.0295 and a turnover multiplier of 0.0020. An asset sits strictly between 0 and its cap. If it is not traded at the optimum, what range must its marginal utility μ_i − γ(Σw)_i lie in?

Knowledge check

Why does the split formulation of turnover (w − w0 = u − v, u, v ≥ 0, sum of u + v ≤ T) not need the nonconvex condition u_i v_i = 0?

Key takeaways

  • Mean–variance with budget, long-only, caps, sector, factor and turnover constraints is a convex QP: P=γΣP = \gamma\Sigma, q=−μq = -\mu, and absolute values become linear through the u−vu - v split.
  • Active-set methods solve a KKT linear system for a guessed set of binding constraints, add violated constraints, drop wrong-signed multipliers, and warm-start well across rebalances; interior-point methods suit large cold starts.
  • Always audit a solution with the KKT conditions: stationarity residual, feasibility, multiplier signs, complementary slackness. For a convex QP that proves optimality.
  • Multipliers price constraints: a turnover multiplier is an implied cost per unit traded, it creates a no-trade band of width ±κ\pm\kappa around each holding, and a cap multiplier says how badly a name wants more weight. Check a solver's sign convention with a small re-solve.

Practice problems

Finished reading?

Answer the 4 knowledge checks to complete this lesson (0 done).