Portfolio construction is a QP
A quadratic programme is
convex when , with a unique solution when . Mean–variance portfolio choice, maximising , is the QP with and . Almost every constraint a desk imposes is linear:
| Constraint | Linear form |
|---|---|
| Fully invested | |
| Long-only, position caps | |
| Sector or country limits | |
| Factor neutrality | (betas, sector loadings) |
| Turnover | , , |
| Gross leverage | same split applied to |
| Linear costs | add to the objective |
The split turns a nonsmooth absolute value into linear constraints. It needs no condition : if both were positive, reducing each by keeps unchanged and only loosens the turnover constraint (or lowers the cost), so some optimal solution never trades both ways. The price is variables instead of , 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 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:
where (the working set) is the equalities plus the inequalities treated as active. An active-set method guesses , solves this system, and repairs the guess:
- If violates an inequality not in , move towards only as far as feasibility allows and add the blocking constraint to .
- If is feasible but some inequality in has a multiplier with the wrong sign, that constraint is pulling the solution rather than pushing it: drop it from .
- If is feasible and every multiplier has the right sign, KKT holds: stop.
Each change of 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 assets and many binding bounds, a large share of names sit exactly at or at their cap. That is the KKT geometry, not a bug.
- Because the solution is piecewise linear in 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 and , position caps and turnover penalties all help.
Worked example
long-only mean–variance by active set
Three uncorrelated assets have and volatilities ; risk aversion . Maximise subject to , first without and then with . Give the multipliers and interpret the budget multiplier.
Show solutionHide solution
Minimise with Lagrangian . With diagonal, stationarity row by row is
Working set {budget}. , and the budget gives , so and . Utility . The low-risk, zero-return asset is shorted to fund leverage in the others.
Repair. violates long-only: add to the working set. Now and the budget over assets 1 and 2 gives , so and . The multiplier from row 3 is , and so . All KKT conditions hold: this is optimal, with utility .
Interpretation. The rule is "water-filling": is a hurdle, and an asset is held only if its expected return beats it. Asset 3 would enter only if ; is exactly its shortfall. The budget multiplier is the marginal utility of capital: with budget the optimum rises by , i.e. per unit, matching to first order. Long-only cost of utility here.
A realistic rebalance with scipy, and a KKT audit
Four assets, current holdings equal-weighted, risk aversion , long-only, a 40% cap per name and one-way turnover . 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 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):
| Constraints | Weights | Utility |
|---|---|---|
| Budget only | ||
| + long-only | ||
| + 40% cap | , turnover | |
| + turnover |
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 solutionHide solution
Signs first. SLSQP writes the Lagrangian as , and is minus utility. So utility rises at rate per unit of loosening of an inequality, and the budget's marginal utility is .
Turnover: utility per unit of extra turnover. Re-solving with raises utility at per unit, confirming it. Equivalently, by duality, the turnover limit acts exactly like a linear trading cost of (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: per unit: the cap is the more expensive constraint per unit, and lifting it to adds utility at that rate (checked by re-solving). Asset 1 wants more weight than it is allowed.
No-trade band. Write for the marginal utility of asset . Stationarity in says that at the optimum:
- an asset being bought has (plus its cap multiplier if capped);
- an asset being sold has ;
- an asset not traded has anywhere in .
Computing at the solution gives . Asset 1: (bought, capped). Asset 3: upper edge (bought). Asset 4: lower edge (sold). Asset 2: lies strictly inside the band, so it is not worth paying the turnover price to trade it. The turnover term creates a band of inaction around each holding: the optimisation-theoretic origin of no-trade regions.
Knowledge check
To write in the standard QP form , what are and ?
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: , , and absolute values become linear through the 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 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).