Portfolio construction in practice
Construct portfolios with risk parity, Black-Litterman views, hierarchical allocation, volatility targeting and trading costs.
After this lesson you can
- Calculate equal risk contributions via convex optimization and compare with 1/N and GMV.
- Derive Black-Litterman as a Bayesian update of equilibrium with views and confidence.
- Implement hierarchical risk parity and explain its relationship to covariance inversion.
- Apply volatility targeting and measure its effect on Sharpe and tails.
- Formulate turnover- and cost-aware optimization and explain the Gârleanu-Pedersen aim portfolio.
Before you start
- 28Mean-variance optimizationLedoit-Wolf shrinkageRandom-matrix covariance cleaningThe 1/N benchmarkCapital Asset Pricing ModelEuler risk allocationFactor covariance structureMerton fraction and optimal leverage
- 12Agglomerative clusteringDendrogram and cophenetic distance
- 05Conjugate priorsSequential Bayesian updating
- 06Second-order cone programmingDisciplined convex programming
- 26Volatility forecasting and evaluationGARCH modelSimple exponential smoothing
A portfolio with uncertain estimates
The mean-variance frontier looks precise when parameters are known. In practice, small changes in estimated means or covariances can greatly change weights, and trading those changes costs money. A committee also needs to explain accepted exposure, incorporated views and what happens if assumptions fail.
Equalizing contributions, not weights
For portfolio weights and covariance matrix , volatility is . Its Euler contribution is and contributions sum to . Equal-risk-contribution (ERC) risk parity requires in a long portfolio. This differs from equal weights and, generally, individual inverse volatility: correlations matter. Maillard, Roncalli and Teïletche study properties of these portfolios.
If is positive definite and , minimize over
The Hessian is positive definite. The objective diverges near the boundary or at infinity, so a unique interior minimum exists. Condition implies for all . Normalizing preserves equal contributions. For two uncorrelated assets, , with weights inversely proportional to volatilities.
ERC depends on forecast covariance. An allocation with low-volatility bonds can have low total volatility and require leverage to reach a risk target. Debt introduces financing costs, margin, margin calls and vulnerability if correlations or volatilities change.
Combining equilibrium and views
The Black-Litterman model starts from reverse equilibrium , with risk aversion and a market portfolio assumed optimal in an unconstrained quadratic problem. Black and Litterman combine equilibrium with investor views. The following Bayesian formulation treats unknown mean as and a view as , with independent . Assume and positive-definite and ; has one row per view and one column per asset. The normal update is
The posterior uncertainty matrix for the mean is . Do not confuse it with predictive return covariance, which under the normal model adds to that matrix. As grows, the view receives less weight; if it and are multiplied by the same factor, only their ratio matters for posterior mean. Confidence choice is an assumption, not error-free observed data.
In that idealized case the same is used for investment and there is no sum constraint: the weight correction is proportional to , so a relative A-minus-B view changes only those two weights. Other assets’ posterior means can change through covariance. With bounds, a weight-sum constraint or predictive covariance, that weight property is no longer general.
Cluster before allocating
Hierarchical risk parity (HRP) transforms correlations into distances , clusters assets, orders dendrogram leaves and recursively allocates capital between halves. A common rule estimates each group’s variance with inverse-individual-variance weights and allocates a group the fraction proportional to the other group’s variance. It avoids inverting the full covariance matrix, but does not eliminate estimation uncertainty or guarantee outperforming shrunk GMV. The original proposal and evaluation appear in López de Prado.
In the figure the two-block structure is known and the displayed order is one possible single-linkage tie-break. Ties may produce another dendrogram; the lab computes order with scipy.cluster.hierarchy. Recursive allocation uses consecutive halves of that order and does not require equal risk contributions.
Volatility targeting and costs
Volatility targeting uses a forecast available before trading: scales a base portfolio. A limit prevents a near-zero forecast from implying unlimited leverage. Realized volatility can differ from target and costs and jumps affect the outcome.
Moreira and Muir study a different rule, proportional to inverse realized variance of the previous month. In table I, for the market factor in their 1926-2015 sample, they report annualized alpha 4.86% and estimated beta 0.61 versus the original factor; these are results for that sample and specification, not a guarantee for another strategy. Scaling by targets approximately constant volatility; scaling by addresses another objective and can produce different leverage.
Cost-aware optimization incorporates cost in the decision. With current portfolio , linear cost and quadratic risk, the subgradient condition creates a no-trade region. If the risk Hessian is not diagonal, that region is generally not a box in weight space. Quadratic cost produces partial adjustment and approximates impact, not a fixed spread.
The dynamic aim portfolio of Gârleanu and Pedersen weights the current Markowitz portfolio and its expected future values; under quadratic costs and their model assumptions, the policy trades partially toward that aim. A persistent signal receives more weight than one that soon disappears. The figure’s illustrative aim is not that exact solution. In multiperiod optimization, costs and risks are forecast over several steps, the problem is solved and only the first trade executed before updating; Boyd and coauthors develop this idea with convex constraints.
Lab: building portfolios
The following implementations start from symmetric positive-definite covariance. Newton calculates the direction by solving a system, not inverting the Hessian. Line search keeps weights positive and reduces the objective. Final normalization does not alter equal contributions.
import numpy as np
from scipy.optimize import minimize
from scipy.cluster.hierarchy import linkage, leaves_list
from scipy.spatial.distance import squareform
def erc_newton(cov,c=1.,tol=1e-10):
S=np.asarray(cov,dtype=float)
if S.ndim!=2 or S.shape[0]!=S.shape[1] or not np.allclose(S,S.T) or c<=0:
raise ValueError('Covarianza o escala inválida')
if np.min(np.linalg.eigvalsh(S))<=0: raise ValueError('Covarianza no definida positiva')
np.linalg.cholesky(S)
x=np.sqrt(c/np.diag(S))
def objetivo(z): return .5*z@S@z-c*np.log(z).sum()
for _ in range(100):
grad=S@x-c/x; hess=S+np.diag(c/x**2)
paso=np.linalg.solve(hess,grad)
if np.max(np.abs(grad))<tol: break
rate=1.
while np.any(x-rate*paso<=0) or objetivo(x-rate*paso)>objetivo(x)-1e-4*rate*(grad@paso):
rate*=.5
if rate<1e-14: raise RuntimeError('No se encontró paso')
x=x-rate*paso
else: raise RuntimeError('Newton no convergió')
return x/x.sum()
def black_litterman(cov,mercado,delta,tau,P,Q,Omega):
S=np.asarray(cov,dtype=float); w=np.asarray(mercado,dtype=float)
P=np.atleast_2d(P); Q=np.atleast_1d(Q); O=np.atleast_2d(Omega)
prior=delta*S@w; C=tau*S
K=np.linalg.solve(P@[email protected]+O,P@C).T
return prior+K@(Q-P@prior), C-K@P@C
S=np.diag([.1**2,.3**2])
w=erc_newton(S); rc=w*(S@w)/np.sqrt(w@S@w)
print('ERC dos activos:',w,'| contribuciones:',rc)Hierarchy and minimum-variance portfolio
linkage receives condensed distances, not the square matrix as an observation table. The diagonal is set to zero and numerical correlation errors clipped before forming distances. With ties, leaf order can depend on implementation. Each HRP group’s internal portfolio uses inverse variance, not its full minimum-variance portfolio.
def hrp_weights(cov):
S=np.asarray(cov,dtype=float)
if S.ndim!=2 or S.shape[0]!=S.shape[1] or len(S)<2 or not np.isfinite(S).all() or not np.allclose(S,S.T):
raise ValueError('Covarianza inválida')
if np.min(np.linalg.eigvalsh(S))<=0: raise ValueError('Covarianza no definida positiva')
np.linalg.cholesky(S)
vol=np.sqrt(np.diag(S)); corr=np.clip(S/np.outer(vol,vol),-1,1)
dist=np.sqrt(np.maximum(0,(1-corr)/2)); np.fill_diagonal(dist,0)
orden=leaves_list(linkage(squareform(dist,checks=False),method='single')).tolist()
w=np.ones(len(S))
def var_cluster(ids):
inv=1/np.diag(S)[ids]; inv=inv/inv.sum()
return float(inv@S[np.ix_(ids,ids)]@inv)
def repartir(ids):
if len(ids)<2: return
mitad=len(ids)//2; a,b=ids[:mitad],ids[mitad:]
va,vb=var_cluster(a),var_cluster(b)
w[a]*=vb/(va+vb); w[b]*=va/(va+vb)
repartir(a); repartir(b)
repartir(orden)
return w
def gmv_larga(cov):
S=np.asarray(cov,dtype=float); d=len(S)
result=minimize(lambda w:float(w@S@w),np.full(d,1/d),method='SLSQP',
bounds=[(0,1)]*d,constraints=[{'type':'eq','fun':lambda w:w.sum()-1}],
options={'ftol':1e-12,'maxiter':500})
if not result.success: raise RuntimeError(result.message)
return result.x
print('HRP diagonal:',hrp_weights(S),'| GMV larga:',gmv_larga(S))The comparison uses SciPy for clustering and optimization. PyPortfolioOpt provides HRP and Black-Litterman implementations where installed; these browser cells neither require nor download it. When comparing results, match linkage, leaf order, covariance convention and constraints, since ties or different parameters can change weights.
Comparison with simulated data
We use a two-block correlation matrix and centered normal returns scaled by a volatility regime. Training and evaluation samples differ; truth is the generated model, not historical data. Shrinkage pulls sample covariance toward its diagonal with explicit intensity 0.25. BL uses the same risk estimator, equal equilibrium weights and a hypothetical relative view; it is not considered a validated prediction. The comparison does not show one method wins in every market.
rng=np.random.default_rng(281901)
n=5; T=700
vol=np.array([.008,.012,.016,.02,.03])
grupo=np.array([0,0,1,1,1])
corr=np.full((n,n),.15)
for i in range(n):
for j in range(n):
if i!=j and grupo[i]==grupo[j]: corr[i,j]+=.35
np.fill_diagonal(corr,1.)
L=np.linalg.cholesky(corr)
z=rng.normal(size=(T,n))@L.T
escala=np.where(np.arange(T)<500,1.,1.8)
R=z*vol*escala[:,None]+np.array([.0002,.0003,.0004,.00045,.0005])
train,test=R[:500],R[500:]
S_muestra=np.cov(train,rowvar=False,ddof=1)
S_shrink=.75*S_muestra+.25*np.diag(np.diag(S_muestra))
igual=np.ones(n)/n
P=np.array([[1.,-1.,0,0,0]])
mu_bl,C_bl=black_litterman(S_shrink,igual,3.,.05,P,[.0002],[[1e-5]])
res_bl=minimize(lambda w:float(1.5*w@S_shrink@w-mu_bl@w),igual,method='SLSQP',
bounds=[(0,1)]*n,constraints=[{'type':'eq','fun':lambda w:w.sum()-1}],
options={'ftol':1e-12,'maxiter':500})
if not res_bl.success: raise RuntimeError(res_bl.message)
pesos={'1/N':igual,'GMV muestral':gmv_larga(S_muestra),
'GMV contraída':gmv_larga(S_shrink),'ERC':erc_newton(S_shrink),
'HRP':hrp_weights(S_shrink),'BL':res_bl.x}
print('Media posterior BL:',mu_bl)
for nombre,w in pesos.items():
fuera=test@w
print(nombre,'| pesos:',np.round(w,3),'| desviación test:',round(float(fuera.std(ddof=1)),6))The test distribution has greater scale than training and contains only one realization. Test volatility measures that simulation, not a conclusive statistical comparison. BL solves a long-only mean-variance problem with weights summing to one, using posterior mean and shrunk covariance. To compare methods repeat the split with different seeds, control costs and consider alternative estimators.
Now increase the ratio of assets to training size. Each repetition generates independent training and test data with true two-block covariance. Besides unconstrained sample GMV, include long-only sample GMV and long-only shrunk GMV: comparing only against an unstable sample inverse would be a straw benchmark. Shrinkage 0.25 is fixed in this experiment, not an optimal estimate. Mean test variance measures this simulation; no universal ordering follows.
rng_dim=np.random.default_rng(281903)
d=16; ntrain=22; ntest=500; repeticiones=20
v=np.linspace(.008,.024,d)
C=np.full((d,d),.05)
for i in range(d):
for j in range(d):
if i!=j and i//8==j//8: C[i,j]=.6
np.fill_diagonal(C,1.)
raiz=np.linalg.cholesky(C)*v[:,None]
resultados=[]
def repetir_dim(cantidad):
for _ in range(cantidad):
entreno=rng_dim.normal(size=(ntrain,d))@raiz.T
prueba=rng_dim.normal(size=(ntest,d))@raiz.T
Sm=np.cov(entreno,rowvar=False,ddof=1)
Sc=.75*Sm+.25*np.diag(np.diag(Sm))
uno=np.ones(d); sin_restriccion=np.linalg.solve(Sm,uno)
sin_restriccion/=sin_restriccion.sum()
carteras=[sin_restriccion,gmv_larga(Sm),gmv_larga(Sc),hrp_weights(Sc)]
resultados.append([float(np.var(prueba@w,ddof=1)) for w in carteras])
repetir_dim(5)
print('Repeticiones:',len(resultados))repetir_dim(5)
print('Repeticiones:',len(resultados))repetir_dim(5)
print('Repeticiones:',len(resultados))repetir_dim(5)
matriz_res=np.asarray(resultados)
print('Varianzas medias test: GMV sin restricciones, GMV larga, contraída, HRP:',matriz_res.mean(axis=0))
print('Veces que HRP supera GMV sin restricciones:',int(np.sum(matriz_res[:,3]<matriz_res[:,0])),'de',len(matriz_res))In this run HRP has lower test variance than unconstrained GMV in all 20 repetitions. However, mean test variance of long-only shrunk GMV is lower than HRP’s. That distinction matters: beating an unstable sample inverse does not demonstrate superiority to a regularized benchmark. Twenty repetitions only illustrate the mechanism; vary sample sizes, structure and seed before a general conclusion.
Targeting with past information
The EWMA forecast is updated with the return observed at the end of each date. Leverage is fixed before observing the next return, capped at 2, and applied to a rebalanced equal-weight base portfolio. The scaled return omits financing and costs, so it illustrates the mechanism rather than providing a complete, implementable backtest.
base_train=train@igual; base_test=test@igual
var_est=float(np.var(base_train,ddof=1)); objetivo_vol=.01
control=[]; exposiciones=[]
for r in base_test:
exposicion=min(2.,objetivo_vol/np.sqrt(var_est))
exposiciones.append(exposicion); control.append(exposicion*r)
var_est=.94*var_est+.06*r*r
control=np.asarray(control)
def resumen(r):
r=np.asarray(r); orden=np.sort(-r); masa=.05*len(r); k=int(np.floor(masa))
es=(orden[-k:].sum()+(masa-k)*orden[-k-1])/masa if masa>k else orden[-k:].mean()
return float(r.mean()/r.std(ddof=1)*np.sqrt(252)),float(es)
print('Sin targeting: Sharpe anualizado convencional y ES 95 %:',resumen(base_test))
print('Con targeting:',resumen(control),'| apalancamiento medio:',np.mean(exposiciones))Annualized Sharpe uses square-root-of-time scaling by convention and does not adjust for dependence. ES is calculated on the test sample, not on a known future distribution. Both values can improve or worsen with the seed, limits and costs; one sample does not establish causality.
Lab: persistent signal and rebalancing
The following control problem is an explicit scalar case with an infinite horizon and quadratic costs. At each date, choose a position after observing a signal with . Maximize the discounted sum of , with and discount factor . The quadratic Bellman equation has solution , with a nonnegative root. If and , the policy is
This is a case of partial adjustment toward a dynamic target portfolio, not an implementation of every assumption and feature in the paper. We verify the Bellman identity and compare the quadratic rule with full rebalancing, a band and fixed partial adjustment. All also pay a linear cost in the evaluation; adding it changes the optimization problem, so the quadratic rule no longer has an optimality guarantee for that evaluation.
To derive it, express the equivalent problem of minimizing negative profit and write the relevant part of future cost as , where is the previous position. The Bellman first-order condition is . Substituting the minimum and comparing the coefficients of and yields the equation for and . The nonnegative root selects the stabilizing solution. The constants depend on the model, so there is no universal trading rate.
rng_trading=np.random.default_rng(281902)
N=1500; rho=.9; beta_disc=.98; riesgo=.0003; coste_q=.0005; coste_l=.0001
senal=np.empty(N); senal[0]=0.
innov=rng_trading.normal(size=N)*.0004
for i in range(1,N): senal[i]=rho*senal[i-1]+innov[i]
rend=senal+rng_trading.normal(0,.01,N)
coef=riesgo+coste_q-beta_disc*coste_q
A=(-coef+np.sqrt(coef**2+4*beta_disc*coste_q*riesgo))/(2*beta_disc)
D=riesgo+coste_q+beta_disc*A
B=coste_q/(D-beta_disc*rho*coste_q)
print('Residuo Bellman:',A-(coste_q-coste_q**2/D))
print('Residuo del coeficiente de señal:',B-coste_q*(1+beta_disc*rho*B)/D)
print('Fracción de ajuste:',1-coste_q/D,'| peso de señal:',(1+beta_disc*rho*B)/D)def ejecutar_politica(modo):
w=0.; pnl=[]; turnover=[]
for s,r in zip(senal,rend):
objetivo=s/riesgo
if modo=='completo': nuevo=objetivo
elif modo=='banda': nuevo=w if abs(objetivo-w)<.5 else objetivo-np.sign(objetivo-w)*.5
elif modo=='parcial': nuevo=w+.2*(objetivo-w)
elif modo=='dinamico': nuevo=coste_q/D*w+(1+beta_disc*rho*B)/D*s
else: raise ValueError('Política desconocida')
cambio=nuevo-w
pnl.append(nuevo*r-coste_l*abs(cambio)-.5*coste_q*cambio**2)
turnover.append(abs(cambio)); w=nuevo
return np.asarray(pnl),float(np.mean(turnover))
for modo in ('completo','banda','parcial','dinamico'):
pnl,rotacion=ejecutar_politica(modo)
print(modo,'| Sharpe convencional:',round(float(pnl.mean()/pnl.std(ddof=1)*np.sqrt(252)),3),
'| rotación media:',round(rotacion,4))These are P&L per unit of reference capital, not a compounded wealth path; no position or financing limit has been imposed. The same stream of signals and shocks allows rules to be compared in this simulation. The band parameter and fixed adjustment are demonstration choices, not parameters optimized out of sample.
Exercises
Step 1 of 3. What is the first-order condition?
Step 1 of 3. What is added in the negative exponent of the posterior density?
def hrp_weights(cov):
raise NotImplementedError()Key takeaways
ERC equalizes risk contributions under a covariance matrix; Black-Litterman expresses views and their uncertainty; HRP uses a hierarchy to allocate capital without inverting the full covariance matrix. Each choice needs comparison with reasonable benchmarks, including a shrunk GMV and an equal-weight portfolio. Volatility targeting changes the scale of exposure and must use past information. Costs also change the portfolio worth holding: a persistent signal and a fleeting one do not necessarily justify the same trading rate.