The Mathematics of Portfolio Allocation in Cutup

An engraving-style illustration of gears, arches and orbiting rings around a price chart and a pie chart

Every allocation method answers the same question: given nn assets, which weight vector w∈Rnw \in \mathbb{R}^n with 1⊀w=1\mathbf{1}^\top w = 1 should we hold? They differ in the risk they measure, the estimates they trust, and the constraints they respect. Those differences are larger in practice than in the textbook, because every method is fed estimates, and estimates are noisy.

Cutup is a Rust library that implements thirteen of these methods and solves the optimization problems among them with its own solvers, with no external dependency. The engineering story of its 1.0 release is on my personal blog. This post covers the mathematics: the programs behind each method, how the library solves them, and what one small dataset shows about how far apart the answers can land.

The inputs, and the trouble with them

Let rt∈Rnr_t \in \mathbb{R}^n be the vector of asset returns in period t=1,…,Tt = 1, \dots, T. Nearly every method starts from two estimates: a vector of expected returns ΞΌ\mu and a covariance matrix Ξ£\Sigma. The sample versions are

ΞΌ^=1Tβˆ‘t=1Trt,S=1Tβˆ’1βˆ‘t=1T(rtβˆ’ΞΌ^)(rtβˆ’ΞΌ^)⊀.\hat{\mu} = \frac{1}{T}\sum_{t=1}^{T} r_t, \qquad S = \frac{1}{T-1}\sum_{t=1}^{T} (r_t - \hat{\mu})(r_t - \hat{\mu})^\top .

Both are poor estimators in the settings practitioners care about. SS has n(n+1)/2n(n+1)/2 free parameters estimated from nTnT numbers, so when TT is not much larger than nn its smallest eigenvalues are biased toward zero and its inverse is unstable. When T≀nT \le n, SS is singular. Optimizers that invert SS put the most weight exactly where the estimate is worst. Michaud (1989) showed that mean-variance optimization tends to maximize the effects of errors in its inputs, and the sample mean is the worst of them: its standard error is Οƒ/T\sigma/\sqrt{T}, which for a year of daily equity returns is larger than the mean itself.

Cutup offers the standard corrections, selected per method.

Covariance shrinkage. The estimate is a convex combination of the sample covariance and a structured target FF:

Ξ£^=(1βˆ’Ξ΄)S+Ξ΄F.\hat{\Sigma} = (1 - \delta) S + \delta F .

With FF set to the average variance times the identity, this is the Ledoit and Wolf (2004a) well-conditioned estimator. With FF set to each asset's own variance and the average pairwise correlation, it is their constant-correlation estimator (Ledoit and Wolf, 2004b). In both, the intensity Ξ΄\delta can be fixed or estimated from the data as the value that minimizes the expected Frobenius loss. Exponentially weighted and downside (semi)covariances are available as alternatives to SS, and any externally estimated matrix, such as one from a factor model, can be passed in after a check that it is symmetric and positive semidefinite.

Mean shrinkage. The James-Stein estimator pulls each sample mean toward the cross-sectional average, and the Bayes-Stein estimator of Jorion (1986) pulls it toward the return of the minimum-variance portfolio:

ΞΌ^BS=(1βˆ’Ο•) μ^+ϕ μ01,ΞΌ0=1⊀Sβˆ’1ΞΌ^1⊀Sβˆ’11.\hat{\mu}_{\text{BS}} = (1 - \phi)\,\hat{\mu} + \phi\, \mu_0 \mathbf{1}, \qquad \mu_0 = \frac{\mathbf{1}^\top S^{-1} \hat{\mu}}{\mathbf{1}^\top S^{-1}\mathbf{1}} .

The intensity Ο•\phi is estimated from how far apart the means are relative to their noise: the less the data separates them, the more they are shrunk. CAPM expected returns, rf+Ξ²i(E[rm]βˆ’rf)r_f + \beta_i(\mathbb{E}[r_m] - r_f), and Black-Litterman posteriors (below) are the other alternatives to the sample mean.

Variance-based methods

Minimum variance

The global minimum-variance portfolio needs no expected returns at all:

min⁑w 12w⊀Σws.t.1⊀w=1.\min_{w}\ \tfrac{1}{2} w^\top \Sigma w \quad \text{s.t.} \quad \mathbf{1}^\top w = 1 .

Without bounds it has the closed form w⋆=Ξ£βˆ’11/1βŠ€Ξ£βˆ’11w^\star = \Sigma^{-1}\mathbf{1} / \mathbf{1}^\top \Sigma^{-1}\mathbf{1}. When Ξ£\Sigma is diagonal this reduces to inverse-variance weighting, wi∝1/Οƒi2w_i \propto 1/\sigma_i^2, so any gap between the two measures the effect of the correlations.

Real mandates add bounds β„“i≀wi≀ui\ell_i \le w_i \le u_i and group limits Lgβ‰€βˆ‘i∈gwi≀UgL_g \le \sum_{i \in g} w_i \le U_g, such as a cap on one sector or one ad platform. These turn the problem into a convex quadratic program with no closed form. Its Karush-Kuhn-Tucker conditions are worth reading closely, because they have a clean financial meaning. With multiplier Ξ»\lambda on the budget constraint and no groups,

(Ξ£w⋆)i=λ  ifΒ β„“i<wi⋆<ui,(Ξ£w⋆)iβ‰₯λ  ifΒ wi⋆=β„“i,(Ξ£w⋆)i≀λ  ifΒ wi⋆=ui.(\Sigma w^\star)_i = \lambda \ \text{ if } \ell_i < w^\star_i < u_i, \qquad (\Sigma w^\star)_i \ge \lambda \ \text{ if } w^\star_i = \ell_i, \qquad (\Sigma w^\star)_i \le \lambda \ \text{ if } w^\star_i = u_i .

(Ξ£w)i(\Sigma w)_i is half the marginal contribution of asset ii to portfolio variance, βˆ‚(w⊀Σw)/βˆ‚wi=2(Ξ£w)i\partial (w^\top \Sigma w) / \partial w_i = 2(\Sigma w)_i. At the optimum, every asset held strictly between its bounds has the same marginal risk. An asset pinned at its floor already has marginal risk at or above that common level, so moving weight into it from the others would raise the variance. An asset pinned at its cap has marginal risk at or below it: you would hold more of it if the cap allowed.

Cutup solves this program with a primal active-set method (Nocedal and Wright, 2006, ch. 16). It guesses which bounds bind, solves the equality-constrained problem on the free assets by the null-space method, and then either steps toward that solution until a new bound binds or releases a bound whose multiplier has the wrong sign. Because binding bounds are fixed rather than approached, long-only weights come out at exactly zero instead of 10βˆ’910^{-9}, and binding caps hold exactly.

Mean-variance and the efficient frontier

Markowitz (1952) mean-variance adds expected returns with a risk aversion Ξ³\gamma:

max⁑w μ⊀wβˆ’Ξ³2 w⊀Σws.t.1⊀w=1, ℓ≀w≀u.\max_{w}\ \mu^\top w - \tfrac{\gamma}{2}\, w^\top \Sigma w \quad \text{s.t.} \quad \mathbf{1}^\top w = 1,\ \ell \le w \le u .

Two other forms of the question are common. Minimizing variance subject to μ⊀wβ‰₯ΞΌtarget\mu^\top w \ge \mu_{\text{target}} is again a quadratic program, and sweeping the target traces the efficient frontier. Maximizing return subject to w⊀Σw≀σtarget2w^\top \Sigma w \le \sigma_{\text{target}}^2 has a quadratic constraint instead. With bounds, cutup solves it by bisecting along the frontier of target-return programs, since the answer is the frontier portfolio at that volatility.

Rebalancing from current weights w0w_0 adds a cost to trading away from them. Proportional transaction costs βˆ‘ici∣wiβˆ’w0,i∣\sum_i c_i |w_i - w_{0,i}| and a cap on turnover βˆ‘i∣wiβˆ’w0,i∣\sum_i |w_i - w_{0,i}| are not differentiable. The standard reformulation splits each trade into buys and sells, wβˆ’w0=bβˆ’sw - w_0 = b - s with b,sβ‰₯0b, s \ge 0, which turns the costs into a linear term in the objective and the cap into a linear constraint. A quadratic penalty ΞΊβˆ₯wβˆ’w0βˆ₯2\kappa \lVert w - w_0 \rVert^2 adds a multiple of the identity to the Hessian. In every case the problem remains a convex quadratic program.

Maximum Sharpe ratio

The tangency portfolio maximizes (ΞΌβˆ’rf1)⊀w/w⊀Σw(\mu - r_f\mathbf{1})^\top w / \sqrt{w^\top \Sigma w}, a ratio that is not concave in ww. Because the ratio is invariant to positive scaling of ww, and provided some portfolio has a positive excess return, the substitution y=w/(ΞΌβˆ’rf1)⊀wy = w / (\mu - r_f\mathbf{1})^\top w, a variant of the Charnes-Cooper transformation for fractional programs, turns the long-only problem into a convex quadratic program (CornuΓ©jols and TΓΌtΓΌncΓΌ, 2007, Β§8.2):

min⁑yΒ y⊀Σys.t.(ΞΌβˆ’rf1)⊀y=1,Β yβ‰₯0,w⋆=y⋆1⊀y⋆.\min_{y}\ y^\top \Sigma y \quad \text{s.t.} \quad (\mu - r_f\mathbf{1})^\top y = 1,\ y \ge 0, \qquad w^\star = \frac{y^\star}{\mathbf{1}^\top y^\star} .

Maximum diversification (Choueifaty and Coignard, 2008), which maximizes ΟƒβŠ€w/w⊀Σw\sigma^\top w / \sqrt{w^\top \Sigma w} with Οƒ\sigma the vector of asset volatilities, is the same problem with Οƒ\sigma in place of the excess returns. Both run on the active-set solver.

Risk-based methods

Risk-based methods use no expected returns and target how risk is distributed rather than how much of it there is. Write the risk contribution of asset ii as RCi=wi(Ξ£w)iRC_i = w_i (\Sigma w)_i. By Euler's theorem the contributions sum to the portfolio variance.

Risk parity and risk budgeting

Risk parity, or equal risk contribution (Maillard, Roncalli and TeΓ―letche, 2010), asks for RCi=RCjRC_i = RC_j for all i,ji, j. Risk budgeting generalizes this to RCi∝biRC_i \propto b_i for budgets bi>0b_i > 0. As a system of equations in ww this is nonconvex, but it has convex formulations. Maillard, Roncalli and TeΓ―letche showed that the ERC weights are the solution of min⁑yy⊀Σy\min_y \sqrt{y^\top \Sigma y} subject to βˆ‘iln⁑yiβ‰₯c\sum_i \ln y_i \ge c, rescaled to sum to one. Spinu (2013) gave an unconstrained form, which is the one cutup uses:

min⁑y>0Β 12y⊀Σyβˆ’βˆ‘i=1nbiln⁑yi,w⋆=y⋆1⊀y⋆.\min_{y > 0}\ \tfrac{1}{2} y^\top \Sigma y - \sum_{i=1}^n b_i \ln y_i, \qquad w^\star = \frac{y^\star}{\mathbf{1}^\top y^\star} .

Setting the gradient to zero gives yi(Ξ£y)i=biy_i (\Sigma y)_i = b_i, which is the budget condition up to scale. Cutup minimizes this function with Newton's method and a backtracking line search, working on the correlation matrix to make the iteration independent of the scale of the returns. The log terms make the objective strictly convex, so its minimizer is unique when it exists, and it exists whenever every long-only portfolio has positive variance.

Hierarchical risk parity

Hierarchical risk parity (LΓ³pez de Prado, 2016) never inverts Ξ£\Sigma, which makes it a natural choice when TT is short relative to nn. It works in two stages:

  1. Cluster the assets on the correlation distance dij=(1βˆ’Οij)/2d_{ij} = \sqrt{(1 - \rho_{ij})/2} and order them so that correlated assets sit next to each other.
  2. Recursive bisection. Split the ordered list in half, repeatedly. At each split the two halves divide their parent's weight in inverse proportion to their variance, with each half's variance taken as that of its own inverse-variance portfolio w~\tilde{w}:
Vk=w~k⊀Σkw~k,Ξ±=1βˆ’V1V1+V2.V_k = \tilde{w}_k^\top \Sigma_k \tilde{w}_k, \qquad \alpha = 1 - \frac{V_1}{V_1 + V_2} .

The first half receives Ξ±\alpha of the parent's weight and the second receives 1βˆ’Ξ±1 - \alpha.

The midpoint split makes the result depend on column order, because reordering the input can move a cut between two correlated assets. Hierarchical equal risk contribution (Raffinot, 2018) instead cuts the dendrogram into kk clusters, chosen by a gap statistic, splits weight at the tree's actual branches, and shares weight by inverse variance within each cluster. Cutup implements both. Its HRP matches PyPortfolioOpt's HRPOpt, down to the clustering's tie-breaking rule, and its HERC matches Riskfolio-Lib's HCPortfolio.

Tail and path risk

Variance penalizes upside and downside deviations alike and summarizes a distribution by its second moment. Three methods in cutup instead measure risk directly on the historical scenarios. All three are linear programs, which cutup solves with a bounded two-phase revised simplex method.

Conditional value at risk

The CVaR, or expected shortfall, at confidence Ξ²\beta is the average loss over the worst 1βˆ’Ξ²1 - \beta of outcomes. Rockafellar and Uryasev (2000) showed that minimizing it over ww is a linear program in ww, an auxiliary threshold ΞΆ\zeta (at the optimum, a value at risk), and one excess-loss variable per scenario:

min⁑w,Β ΞΆ,Β uΒ ΞΆ+1(1βˆ’Ξ²) Tβˆ‘t=1Tuts.t.utβ‰₯βˆ’rt⊀wβˆ’ΞΆ,Β Β utβ‰₯0.\min_{w,\ \zeta,\ u}\ \zeta + \frac{1}{(1-\beta)\,T}\sum_{t=1}^{T} u_t \quad \text{s.t.} \quad u_t \ge -r_t^\top w - \zeta,\ \ u_t \ge 0 .

Because the objective looks at the losses themselves, the method responds to skew and fat tails that a covariance cannot see. The cost is data: at Ξ²=0.95\beta = 0.95, T=20T = 20 scenarios leave a tail of a single observation.

Mean absolute deviation

Konno and Yamazaki (1991) replaced variance with the mean absolute deviation of portfolio returns, 1Tβˆ‘t∣rt⊀wβˆ’rΛ‰βŠ€w∣\frac{1}{T}\sum_t |r_t^\top w - \bar{r}^\top w|. The absolute value becomes linear by bounding it above and below with dtβ‰₯Β±(rtβˆ’rΛ‰)⊀wd_t \ge \pm (r_t - \bar{r})^\top w. Large deviations count linearly rather than quadratically, so a few outliers move the answer less. The downside variant counts only shortfalls below a fixed threshold Ο„\tau, 1Tβˆ‘tmax⁑(Ο„βˆ’rt⊀w,0)\frac{1}{T}\sum_t \max(\tau - r_t^\top w, 0).

Conditional drawdown at risk

With the sample estimators, every method so far treats the TT periods as an unordered sample: shuffle the rows and the weights do not change. Drawdown does not have that property. Let St=βˆ‘k≀trk⊀wS_t = \sum_{k \le t} r_k^\top w be the cumulative (summed, not compounded) portfolio return with S0=0S_0 = 0, and define the drawdown

Dt=max⁑0≀s≀tSsβˆ’St.D_t = \max_{0 \le s \le t} S_s - S_t .

CDaR (Chekhlov, Uryasev and Zabarankin, 2005) is the CVaR of the drawdowns D1,…,DTD_1, \dots, D_T: the average of the worst 1βˆ’Ξ²1 - \beta of them. As Ξ²β†’1\beta \to 1 it becomes the maximum drawdown. It is a natural measure for a mandate that must not fall far behind its own high-water mark, whether that is a fund with a drawdown limit or a marketing budget whose results arrive in streaks.

The linear program has a running-maximum variable and constraints for every period, and at T=1,000T = 1{,}000 the direct formulation takes over a minute on the library's simplex solver. Cutup solves it instead with Kelley's cutting-plane method. It starts from a small master program and adds one cut per round, each a linear lower bound on CDaR, until the bound meets the best portfolio found. Each round's simplex starts where the last one ended, and in-out stabilization (Ben-Ameur and Neto, 2007) places each cut between the master's minimizer and the best point so far, which roughly halves the number of rounds at 500 assets. The same problem at T=1,000T = 1{,}000 with 20 assets then solves in a few milliseconds.

Black-Litterman

Black and Litterman (1992) start from the expected returns implied by market weights under the assumption that the market portfolio is mean-variance optimal for risk aversion Ξ΄\delta, Ξ =δΣwmkt\Pi = \delta\Sigma w_{\text{mkt}}. They then treat Ξ \Pi as a prior for the expected returns ΞΌ\mu, with uncertainty τΣ\tau\Sigma, and blend in kk views of the form PΞΌ=q+Ξ΅P\mu = q + \varepsilon, with Ρ∼N(0,Ξ©)\varepsilon \sim N(0, \Omega):

ΞΌBL=[(τΣ)βˆ’1+PβŠ€Ξ©βˆ’1P]βˆ’1[(τΣ)βˆ’1Ξ +PβŠ€Ξ©βˆ’1q].\mu_{\text{BL}} = \left[(\tau\Sigma)^{-1} + P^\top \Omega^{-1} P\right]^{-1} \left[(\tau\Sigma)^{-1}\Pi + P^\top \Omega^{-1} q\right] .

The posterior covariance of returns is Ξ£+M\Sigma + M, where M=[(τΣ)βˆ’1+PβŠ€Ξ©βˆ’1P]βˆ’1M = \left[(\tau\Sigma)^{-1} + P^\top\Omega^{-1}P\right]^{-1} is what remains of the prior's uncertainty τΣ\tau\Sigma after the views. Each view's uncertainty can be given directly as a variance or through Idzorek's (2007) intuitive confidence level. Black-Litterman produces inputs rather than weights. Its posterior mean and covariance feed mean-variance or maximum Sharpe.

One dataset, thirteen answers

The library ships an example that runs every method on the same short price history of four assets, twelve periods in all. Twelve periods is far too few to support any investment conclusion. The point is to see how the methods behave relative to one another when they are given identical, and noisy, inputs.

MethodAsset 0Asset 1Asset 2Asset 3
Equal weight0.2500.2500.2500.250
Inverse variance0.0890.5540.2010.156
Min variance, long-short0.2600.611βˆ’0.0090.137
Min variance, long-only0.2590.6020.0000.140
Min variance, long-short, 20% shrinkage0.2430.4160.1320.210
Min variance, ≀ 30% each0.2440.3000.1950.260
Max Sharpe, rf=0r_f = 00.2590.5920.0050.145
Mean-variance, Ξ³=100\gamma = 1000.2190.0600.3750.345
Risk parity0.2460.5140.0710.168
HRP0.1500.4310.1560.263
Min CVaR, worst 25%0.2530.5550.0610.131
Min MAD0.2610.6230.0000.116
Min CDaR, worst 25%0.0000.0000.4100.590

A few things stand out.

The correlations matter. Inverse variance and minimum variance would agree if the assets were uncorrelated. Here assets 0 and 1 have a sample correlation of βˆ’0.88, so asset 0, the most volatile of the four, is a strong hedge for asset 1. Minimum variance nearly triples asset 0's weight relative to inverse variance, from 8.9% to 26%. It also goes slightly short asset 2, which is positively correlated (0.41) with asset 1, the largest holding.

The KKT conditions are visible. Requiring long-only weights moves asset 2 from βˆ’0.9% to exactly zero. Its marginal variance at the long-only optimum is above the common level Ξ»\lambda, so it sits at its bound, and the other weights adjust to restore equal marginal risk among the assets still held.

Shrinkage and caps are regularizers. Shrinking the covariance 20% toward a scaled identity and capping each weight at 30% both pull the portfolio toward equal weight, reducing the concentration in asset 1 from about 60% to 42% and 30% respectively. Jagannathan and Ma (2003) showed that weight constraints act as an implicit form of covariance shrinkage, which is why the two adjustments move in the same direction.

Inverting Ξ£\Sigma amplifies its smallest eigenvalue. Maximum Sharpe lands almost on top of minimum variance even though the sample means differ by nearly a factor of two. The reason is the spectrum of the sample covariance. Its smallest eigenvalue, 5.8Γ—10βˆ’65.8 \times 10^{-6}, is about 19 times smaller than the next, and its eigenvector, normalized to sum to one, is roughly (0.26,0.65,βˆ’0.04,0.12)(0.26, 0.65, -0.04, 0.12). Both Ξ£βˆ’11\Sigma^{-1}\mathbf{1} and Ξ£βˆ’1ΞΌ\Sigma^{-1}\mu are dominated by the 1/Ξ»min⁑1/\lambda_{\min} term along that direction, so both optimizers find the same nearly riskless combination. Twelve observations cannot tell a genuine hedge from a sampling accident, and the optimizers trust it completely. This is the failure mode that shrinkage, and HRP's refusal to invert Ξ£\Sigma, exist to guard against.

Mean-variance is driven by the means. Per-period variances are of order 10βˆ’410^{-4}, so at Ξ³=100\gamma = 100 the variance penalty is small next to expected returns of about 1% per period. The optimizer moves out of asset 1, which has the lowest sample mean, cutting it from about 60% to 6%, and into assets 2 and 3, which have the highest. Yet those means are not reliably different. Asset 2's sample mean exceeds asset 1's by 0.54% per period, with a t-statistic of about 1.3 over twelve periods. The optimizer bets heavily on a difference the data cannot confirm, which is Michaud's point in a single row.

Linear programs can have many optima. Minimum CDaR puts all of its weight in assets 2 and 3, unlike every other method. The reason is not a deep insight about drawdowns. In twelve periods, equal weight, inverse variance and long-only minimum variance also never fall below their running high, so they too have a CDaR of exactly zero. The optimum is a whole set of portfolios, and the simplex method returns one vertex of it. The result is correct: no portfolio has a lower CDaR. But it is not unique, so the weights alone mean nothing without the objective value next to them. For the same reason, cutup's reference tests compare objective values rather than weights for its linear programs. With realistic history the drawdown tail is not empty, and the method separates assets that lose in streaks from those whose losses are spread out.

Why exactness

For allocation research, the solver is part of the model. A general-purpose numerical optimizer that stops at a tolerance can return weights of 3Γ—10βˆ’73 \times 10^{-7} instead of zero, or let a 40% cap read as 40.0001%. None of that matters for a single backtest. It does matter for audit trails, for compliance checks against hard limits, and for reproducing a past decision.

Cutup's solvers stop at a combinatorial certificate of optimality instead: an active set for quadratic programs, an optimal simplex basis for linear programs, and a finite set of cuts for CDaR. Binding bounds then hold exactly, and the optimality conditions hold to floating-point rounding. Each method is checked against an independent reference: closed forms and support enumeration in NumPy, SciPy's HiGHS for the linear programs, and PyPortfolioOpt, Riskfolio-Lib and scikit-learn where they implement the same estimator. The reference values are committed alongside the code, so these checks run without Python.

The library is MIT-licensed and available on crates.io, with full documentation on docs.rs. It also compiles to WebAssembly, so the same optimizer runs on a server or in the browser.


References