Module contents
Stage 6 of 9Advanced 110 min

Portfolio construction

Add a portfolio construction layer with volatility targeting, minimum variance using Ledoit-Wolf covariance, risk parity, and constrained optimization with turnover penalty. Compare the layers out of sample against an equal-weight portfolio.

After this lesson you can

  • Implement volatility targeting and measure realized risk stability.
  • Compare sample and shrinkage covariance in out-of-sample minimum-variance portfolios.
  • Formulate and solve a portfolio with weight, neutrality, and turnover constraints using cvxpy.
  • Calculate risk parity as a convex problem and verify equal contributions.

Before you start

Estimate, then optimize

The minimum-variance portfolio chooses weights that appear safe under an estimated covariance. When the number of assets approaches the number of observations, small eigenvalues are especially uncertain. Inverting the matrix amplifies their errors and can produce large weights and short positions that appear to reduce risk in sample, but not necessarily afterward.

Covariance shrinkage combines sample matrix SS with a structured target. This lesson uses F=μIF=\mu I, where μ=tr⁡(S)/p\mu=\operatorname{tr}(S)/p:

Σ^=(1−δ)S+δμI,0≤δ≤1.\widehat\Sigma=(1-\delta)S+\delta\mu I,\qquad 0\le\delta\le1.

Eigenvalues move toward their mean and eigenvectors are preserved. The target assumes equal variances and zero covariances at δ=1\delta=1; it is deliberately simple and may be far from reality. Ledoit and Wolf derive a well-conditioned estimator with estimated intensity; the identity-target variant used here belongs to that family, not the constant-correlation target of all its applications.

InteractiveShrink to stabilize

Synthetic three-asset matrix. Shrunk spectrum: 0.00010 · 0.00400 · 0.03000; mean eigenvalue 0.01137.

Unconstrained minimum-variance weights: A 1.76, B −0.77, C 0.02. Negative values represent shorts.

The three bars show eigenvalues in ascending order, on a shared scale from 0 to 0.03. At intensity 1 all three coincide.

0.00
Condition300.0
Gross exposure2.55
Sum of weights1.00
The matrix and its weights are synthetic; out-of-sample improvement is not guaranteed.

In the figure, the condition number is the ratio of largest to smallest positive eigenvalue. At zero intensity the lowest-variance direction dominates the inverse; increasing intensity reduces that amplification. A lower condition number does not prove that the matrix is closer to the true one or will earn more. Optimal intensity depends on the loss objective, horizon, and sample.

The sum-to-one minimum-variance solution is proportional to Σ−11\Sigma^{-1}\mathbf1. If an estimated eigenvalue is very small, its inverse is very large. The optimizer can rely on an asset combination that only appeared nearly risk-free in sample. Changing a few observations can then swing weights, generate turnover, and increase later risk. Solving the linear system avoids forming an explicit inverse but does not eliminate the statistical problem.

Shrinkage changes the estimator; constraints change the set of permitted portfolios. A weight limit can reduce an extreme position even with the original matrix, while shrinkage changes the covariances used to evaluate all portfolios. Both tools can be used, but their effects and rebalancing cost should be measured separately. A lower-volatility portfolio can also have lower expected return: comparing only Sharpe or only variance answers different questions.

For nn centered rows xtx_t, the lab calculates S=n−1∑txtxt⊤S=n^{-1}\sum_t x_tx_t^\top, F=μIF=\mu I, and

β^=1n2∑t∥xtxt⊤−S∥F2,δ^=min⁡(1,β^∥S−F∥F2).\widehat\beta=\frac{1}{n^2}\sum_t\|x_tx_t^\top-S\|_F^2,\quad \widehat\delta=\min\left(1,\frac{\widehat\beta}{\|S-F\|_F^2}\right).

If the denominator is numerically zero, intensity zero is used because SS already equals the target. This formulation uses divisor nn and centers data first. The test compares both matrix and intensity with scikit-learn. The experiment estimates covariance in training and evaluates frozen weights on another sample, avoiding inclusion of test returns in estimation.

The quantity β^\widehat\beta summarizes how much each observation’s outer products vary around their mean. If they are highly unstable relative to the distance between SS and FF, the coefficient approaches one. The formula uses the full training sample to estimate intensity; it does not choose the intensity with the best test result. It is clipped to the valid interval because a combination outside it would no longer be convex shrinkage.

The identity target affects all directions equally and preserves the trace. Thus the sum of eigenvalues does not change, though their dispersion does. For a nonzero positive semidefinite matrix, any positive intensity makes it positive definite if the mean eigenvalue is positive. This helps solve the numerical problem, but an incorrect target can introduce enough bias to worsen the estimate or portfolio.

Volatility targeting

Volatility targeting turns a causal forecast σ^t\hat\sigma_t into a scale at=min⁡(amax⁡,σ∗/σ^t)a_t=\min(a_{\max},\sigma^*/\hat\sigma_t). If annual forecast is 25%, target 10%, and cap two, scale is 0.4. If the forecast is very low, the cap prevents unlimited exposure, though it does not by itself control extreme losses.

With EWMA, next variance is vt+1=λvt+(1−λ)rt2v_{t+1}=\lambda v_t+(1-\lambda)r_t^2. The position for period tt is calculated with vtv_t before observing rtr_t; after observing it, the forecast is updated. The choice λ=0,94\lambda=0,94 and initial volatility obtained from training are example assumptions. The forecast can become stale during a regime change, and leverage, fees, and financing affect real results.

If the forecast is below subsequent volatility, scaling increases risk just before a shock. Evaluation should show realized volatility by window, frequency of hitting the cap, and costs of changing scale. A target is an ex ante rule, not an ex post promise. Multiplication by 252\sqrt{252} also assumes the daily-return convention and does not automatically adjust for autocorrelation.

A causal update can be checked by perturbing a test return. If rtr_t changes, the scale applied to that same return must remain unchanged; the next day’s scale may change. A module test verifies exactly that relationship. For a multi-asset portfolio, forecast volatility can come from its historical return series or w⊤Σ^ww^\top\hat\Sigma w; both require weights and matrix calculated with information available before the period to which they apply.

Constraints and parity

Constrained optimization maximizes forecast return minus variance and turnover penalties:

max⁡w μ^⊤w−λw⊤Σ^w−c∥w−wanterior∥1.\max_w \ \hat\mu^\top w-\lambda w^\top\widehat\Sigma w-c\|w-w_{\rm anterior}\|_1.

We can require weights to sum to zero, zero exposure to beta and sector vectors, gross exposure ∥w∥1≤1\|w\|_1\le1, and individual limits. These constrain given estimates and labels: neutrality to an estimated beta does not imply neutrality to a future beta. The zero portfolio is feasible, so a high penalty can cause the optimizer not to trade. A numerical solution must check solver status and all constraint residuals against tolerance.

The turnover penalty compares the new target with the previous portfolio, making the decision state-dependent. If the signal changes little, paying to move may not be worthwhile; if it changes greatly, the solution can change despite cost. The one-norm is a convex approximation to changed notional. A real account would require weight drift, per-asset spreads, impact, and share rounding, and checking that the previous portfolio matches fills actually received.

Risk parity seeks to equalize contributions wi(Σw)iw_i(\Sigma w)_i to portfolio variance. With a positive-definite matrix and equal budgets, solve for xi>0x_i>0

min⁡x 12x⊤Σx−1p∑ilog⁡xi,wi=xi∑jxj.\min_x\ \frac12 x^\top\Sigma x-\frac1p\sum_i\log x_i, \qquad w_i=\frac{x_i}{\sum_j x_j}.

The first-order condition gives xi(Σx)i=1/px_i(\Sigma x)_i=1/p. Normalization changes all contributions by the same factor and preserves equality. This formulation is convex with positive weights; arbitrary added constraints can prevent exact parity. Contributions depend on estimated covariance and do not guarantee equal future contributions. The formulation relates to the CVX risk-budgeting exercise.

In the diagonal case without correlations, variance contributions are wi2σi2w_i^2\sigma_i^2. Equalizing them implies weights inversely proportional to volatilities, not variances. With correlations, a contribution also contains covariances with other positions, so that simple rule is no longer exact. Equality concerns estimated risk, not return contributions; an asset can contribute greatly to the mean and little to variance, or vice versa.

The exercise uses Newton’s method for the same problem: calculate gradient and Hessian, solve for a direction, and reduce the step until every coordinate remains positive and the objective does not increase. The logarithm prevents reaching zero at finite cost. Before trusting a solution, verify the sum, positivity, and approximate equality of contributions. Singular covariance, loose tolerance, or interrupted iteration can invalidate those checks.

Local laboratory

Download p01portfolio.py, p01portfolio_lab.py, and test_p01portfolio.py, together with p01vector.py. Install NumPy, pandas, scikit-learn, cvxpy, and pytest. Returns are synthetic normal with fixed covariance: 25 assets, 40 training observations, and 756 independent test observations. Weights are fixed from training and the variance comparison excludes costs and equalized risk budgets. The lab also passes weights to the vectorized engine with a prior signal row and verifies matching returns. This tests the implementation, not universal superiority.

[ ]Shrinkage, portfolio, and parityLocal GPU
import os,sys
from pathlib import Path
import pytest
lib=Path(os.environ.get('P01_LIB_DIR','.')).resolve()
if not (lib/'p01portfolio.py').exists(): raise FileNotFoundError('Descarga los módulos en P01_LIB_DIR')
sys.path.insert(0,str(lib))
from p01portfolio_lab import experiment
os.environ['PYTEST_DISABLE_PLUGIN_AUTOLOAD']='1'
status=pytest.main([str(lib/'test_p01portfolio.py'),'-q','-p','no:cacheprovider'])
assert status==0
experiment()
This cell needs the local lab (PyTorch with your GPU). Start it with npm run lab and open the connection link.

In the verified run intensity is 0.3678 and maximum difference from scikit-learn is approximately 1.36×10−201.36\times10^{-20}. The condition number falls from 151.35 to 11.02. Daily test variances are 5.97×10−65.97\times10^{-6} for sample minimum variance and 3.59×10−63.59\times10^{-6} for shrinkage; the equal-weight portfolio obtains 5.00×10−65.00\times10^{-6}. Gross exposures differ and no cost is charged: the comparison addresses this configuration, not an implementable portfolio.

The risk-parity portfolio’s 25 relative contributions lie between 0.039989 and 0.040005, close to the desired 4%. The constrained portfolio verifies approximately zero sum, beta, and sector exposure; gross exposure and maximum individual weight reach approximately 1 and 0.25. Small deviations are solver tolerances.

To illustrate the 10% target, the equal-weight stream is multiplied by two before EWMA. That factor was fixed after a separate pilot in which the cap of two prevented reaching the target; the displayed result uses another independent test seed. Realized volatilities in the three windows are 10.37%, 10.38%, and 10.06%. This controlled design meets the 20% margin in those windows without guaranteeing it in markets, other regimes, or with costs.

Independent evaluation avoids reusing pilot returns, but remains one synthetic configuration with stable volatility. It does not measure how often the target is missed across multiple paths. The matrix comparison also uses one generating covariance and one training window; repeating it under different correlations, crises, heavy tails, and costs could change the ranking. Comparing risk-adjusted return requires the same risk, execution, and period rules for each portfolio.

The lab also compares all layers over the same 756 test observations. It starts flat and charges 5 bp per sum of absolute weight changes. Static weights remain constant targets; cost excludes weight drift and the rebalancing required to correct it. EWMA changes scale daily and pays for those changes. The model also excludes impact, financing, short borrowing, and liquidity limits. Final capital compounds net returns and Sharpe uses a zero risk-free rate.

The “sample” and “shrinkage” rows are minimum-variance portfolios; “neutral” is constrained and “EWMA” scales the doubled equal-weight portfolio.

LayerAnnual vol.SharpeCapital
Equal weight3.55 %0.8121.0883
Sample3.88 %0.6651.0780
Shrinkage3.01 %0.7591.0695
Parity2.99 %0.7571.0688
Neutral8.50 %−0.1960.9409
EWMA10.26 %0.6931.2184
LayerTotal turnoverMean gross exposure
Equal weight1.0001.000
Sample1.1781.178
Shrinkage1.0071.007
Parity1.0001.000
Neutral1.0001.000
EWMA65.2832.857

Exposures and volatilities differ: the neutral portfolio does not have the same net exposure as the equal-weight portfolio, and EWMA uses greater leverage. Final capitals are therefore not a constant-risk comparison. Signals and returns have zero generating mean; observed gains or losses are fluctuations of this path. The 5 bp is a fixed assumption, not a calibration. Repeating with realistic costs, financing, constraints, and a common risk target is necessary before attributing improvement to a layer.

As an additional comparison, the code scales each static portfolio to forecast volatility of 10% using only the training window, without a leverage cap. It retains the same weight-change costs and recalculates the later result. This hypothetical scaling can violate the constrained portfolio’s weight and exposure limits; it is therefore not the earlier executable constrained solution.

Scaled layerFactorRealized vol.Gross exposure
Equal weight2.91410.35 %2.914
Sample5.84422.67 %6.884
Shrinkage4.61513.89 %4.646
Parity3.94411.79 %3.944
Neutral1.21510.33 %1.215

All had the same forecast target in training, but not the same realized risk: sample covariance particularly underestimated its portfolio’s risk. EWMA, which updates scale and applies a cap of two to the initially doubled stream, realized 10.26% and paid continuous turnover. The two scaling rules differ. High leverage in some rows makes omission of financing and constraints substantial.

Exercises

ProofSum-to-one minimum variance
Prove: With positive-definite Σ\Sigma, derive weights minimizing w⊤Σww^\top\Sigma w subject to 1⊤w=1\mathbf1^\top w=1.
The proof will appear here as you work.

Step 1 of 2. What condition follows from the Lagrangian gradient?

CodeParity with Newton's method
Implement risk_parity(cov), for a positive-definite matrix, returning positive weights that sum to one and equalize w_i (cov @ w)_i. You can solve the objective 0.5 xᵀcov x − mean(log x) with Newton's method and normalize.
import numpy as np
def risk_parity(cov):
  raise NotImplementedError()
Shift+Enter to run
NumericVolatility target
Forecast annual volatility is 25%, the target is 10%, and the leverage cap is 2. What is the scale factor?
QuizMany variables, few observations
What can happen to minimum-variance weights when there are nearly as many assets as observations?

What to remember

Key idea
Estimating from prior data, checking constraints, and evaluating risk after the cutoff are inseparable parts of constructing a portfolio.