Module contents
Lesson 19 of 30Advanced 110 min

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

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.

InteractiveWeights and contributions

The synthetic covariance has common correlation 0.15, plus 0.5 times the intensity for assets in the same block (A-B and C-D-E). GMV is long only and HRP uses the displayed block order.

  • A
  • B
  • C
  • D
  • E
1/N
Weights A through E (%): 20.0 / 20.0 / 20.0 / 20.0 / 20.0
Risk contributions A through E (%): 5.2 / 8.5 / 19.3 / 25.2 / 41.8
Long-only GMV
Weights A through E (%): 73.3 / 10.5 / 12.8 / 3.3 / 0.0
Risk contributions A through E (%): 73.3 / 10.5 / 12.8 / 3.3 / 0.0
ERC
Weights A through E (%): 36.7 / 24.5 / 16.6 / 13.3 / 8.9
Risk contributions A through E (%): 20.0 / 20.0 / 20.0 / 20.0 / 20.0
HRP
Weights A through E (%): 55.2 / 24.5 / 12.4 / 5.4 / 2.4
Risk contributions A through E (%): 47.8 / 28.3 / 13.3 / 6.5 / 4.1
30 %
0.70
Volatility 1/N12.09 %
Volatility Long-only GMV7.43 %
Volatility ERC9.08 %
Volatility HRP7.72 %
Increase E's volatility and compare capital allocation with risk allocation.

Equalizing contributions, not weights

For portfolio weights w\vb{w} and covariance matrix Σ\mat{\Sigma}, volatility is σp=w⊤Σw\sigma_p=\sqrt{\vb{w}\T\mat{\Sigma}\vb{w}}. Its Euler contribution is RCi=wi(Σw)i/σpRC_i=w_i(\mat{\Sigma}\vb{w})_i/\sigma_p and contributions sum to σp\sigma_p. Equal-risk-contribution (ERC) risk parity requires RCi=σp/nRC_i=\sigma_p/n 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 Σ\mat{\Sigma} is positive definite and c>0c>0, minimize over x>0\vb{x}>0

f(x)=12x⊤Σx−c∑ilog⁡xi.f(\vb{x})=\tfrac12\vb{x}\T\mat{\Sigma}\vb{x}-c\sum_i\log x_i.

The Hessian Σ+cdiag⁡(xi−2)\mat{\Sigma}+c\operatorname{diag}(x_i^{-2}) is positive definite. The objective diverges near the boundary or at infinity, so a unique interior minimum exists. Condition Σx−c/x=0\mat{\Sigma}\vb{x}-c/\vb{x}=0 implies xi(Σx)i=cx_i(\mat{\Sigma}\vb{x})_i=c for all ii. Normalizing w=x/∑ixi\vb{w}=\vb{x}/\sum_i x_i preserves equal contributions. For two uncorrelated assets, w1σ1=w2σ2w_1\sigma_1=w_2\sigma_2, 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 Π=δΣwm\vb{\Pi}=\delta\mat{\Sigma}\vb{w}_{m}, with risk aversion δ>0\delta>0 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 μ∼N(Π,τΣ)\vb{\mu}\sim N(\vb{\Pi},\tau\mat{\Sigma}) and a view as Q=Pμ+ϵ\vb{Q}=\mat{P}\vb{\mu}+\vb{\epsilon}, with independent ϵ∼N(0,Ω)\vb{\epsilon}\sim N(0,\mat{\Omega}). Assume τ>0\tau>0 and positive-definite Σ\mat{\Sigma} and Ω\mat{\Omega}; P\mat{P} has one row per view and one column per asset. The normal update is

μBL=Π+τΣP⊤(PτΣP⊤+Ω)−1(Q−PΠ).\vb{\mu}_{BL}=\vb{\Pi}+\tau\mat{\Sigma}\mat{P}\T(\mat{P}\tau\mat{\Sigma}\mat{P}\T+\mat{\Omega})^{-1}(\vb{Q}-\mat{P}\vb{\Pi}).

The posterior uncertainty matrix for the mean is τΣ−τΣP⊤(PτΣP⊤+Ω)−1PτΣ\tau\mat{\Sigma}-\tau\mat{\Sigma}\mat{P}\T(\mat{P}\tau\mat{\Sigma}\mat{P}\T+\mat{\Omega})^{-1}\mat{P}\tau\mat{\Sigma}. Do not confuse it with predictive return covariance, which under the normal model adds Σ\mat{\Sigma} to that matrix. As Ω\mat{\Omega} grows, the view receives less weight; if it and τ\tau are multiplied by the same factor, only their ratio matters for posterior mean. Confidence choice is an assumption, not error-free observed data.

InteractiveA view and its confidence

Annual model with five assets, risk aversion 3, prior uncertainty 0.05Σ, and equilibrium weights 25/25/20/15/15%. Confidence sets the share of the shift toward the view, with Ω = prior variance of the view × (1−confidence)/confidence. The unconstrained weights use Σ, so the remainder can stay in cash.

  • Black-Litterman
  • Direct substitution of the view
A
55.4 %
113.5 %
B
−5.4 %
−29.7 %
C
20.0 %
19.4 %
D
15.0 %
14.1 %
E
15.0 %
14.5 %
View
4.0 %
50 %
Posterior means A / B3.58 / 2.46 %
View error variance0.001580
Switch between absolute and relative views, change magnitude and compare unconstrained positions.

In that idealized case the same Σ\mat{\Sigma} is used for investment and there is no sum constraint: the weight correction is proportional to P⊤\mat{P}\T, 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 dij=(1−ρij)/2d_{ij}=\sqrt{(1-\rho_{ij})/2}, 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.

InteractiveFrom ordering to allocation

Matrix in shuffled order.

ACBDEA1.000.150.500.150.15C0.151.000.150.500.50B0.500.151.000.150.15D0.150.500.151.000.50E0.150.500.150.501.00
0
First group
0.70
Advance from the shuffled matrix to bisection and change block strength.

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: at=min⁡(amax⁡,σ∗/σ^t)a_t=\min(a_{\max},\sigma_* /\widehat\sigma_t) 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 1/σ1/\sigma targets approximately constant volatility; scaling by 1/σ21/\sigma^2 addresses another objective and can produce different leverage.

Cost-aware optimization incorporates cost in the decision. With current portfolio w0\vb{w}_0, linear cost c∥w−w0∥1c\norm{\vb{w}-\vb{w}_0}_1 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.

InteractiveNo-trade region and adjustment

This dimensionless example starts from a zero position and minimizes ½‖w−a‖² + c‖w‖₁ + κ‖w‖²/2. The target a is a discounted sum with persistence ρ and discount factor 0.8, so a = signal/(1−0.8ρ). The rule illustrates the direction of dynamic trading in this simplified example.

  • No-trade region
  • Target a
  • Selected position
0.35
0.20
0.25
0.5
0.30
Approximate target A / B0.46 / 0.26
Selected position A / B0.14 / 0.01
Move signals and costs. The square applies only to the separable example described in the figure.

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.

[ ]ERC by Newton's method and Black-LittermanBrowser
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.

[ ]HRP and long-only GMVBrowser
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.

[ ]Separate training and evaluationBrowser
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.

[ ]HRP versus GMV in many dimensionsBrowser
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))
[ ]Comparison, block 2Browser
repetir_dim(5)
print('Repeticiones:',len(resultados))
[ ]Comparison, block 3Browser
repetir_dim(5)
print('Repeticiones:',len(resultados))
[ ]Complete the out-of-sample comparisonBrowser
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.

[ ]Volatility targeting without looking aheadBrowser
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 wtw_t after observing a signal sts_t with E[st+1∣st]=ρstE[s_{t+1}\mid s_t]=\rho s_t. Maximize the discounted sum of stwt−12rwt2−12λ(wt−wt−1)2s_tw_t-\tfrac12 r w_t^2-\tfrac12\lambda(w_t-w_{t-1})^2, with r,λ>0r,\lambda>0 and discount factor 0<β<10<\beta<1. The quadratic Bellman equation has solution A=λ−λ2/(r+λ+βA)A=\lambda-\lambda^2/(r+\lambda+\beta A), with a nonnegative root. If D=r+λ+βAD=r+\lambda+\beta A and B=λ/(D−βρλ)B=\lambda/(D-\beta\rho\lambda), the policy is

wt=λDwt−1+1+βρBDst.w_t=\frac{\lambda}{D}w_{t-1}+\frac{1+\beta\rho B}{D}s_t.

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 V(x,s)=12Ax2−Bxs+C(s)V(x,s)=\tfrac12Ax^2-Bxs+C(s), where xx is the previous position. The Bellman first-order condition is Dwt=λx+(1+βρB)stDw_t=\lambda x+(1+\beta\rho B)s_t. Substituting the minimum and comparing the coefficients of x2x^2 and xsxs yields the equation for AA and B=λ(1+βρB)/DB=\lambda(1+\beta\rho B)/D. The nonnegative root selects the stabilizing solution. The constants depend on the model, so there is no universal trading rate.

[ ]Signals and scalar dynamic ruleBrowser
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)
[ ]Compare policies under the same costsBrowser
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

NumericTwo equal risks
Two uncorrelated assets have volatilities of 10% and 30%. If weights are positive and sum to one, what weight does the first receive in the ERC portfolio?
ProofFrom a minimum to ERC
Prove: Let Σ be positive definite and c>0. Show that the positive solution minimizing ½xᵀΣx−c∑log xᵢ, normalized to sum to one, has equal contributions.
The proof will appear here as you work.

Step 1 of 3. What is the first-order condition?

ProofUpdating views
Prove: Derive the Black-Litterman posterior mean with a normal prior and independent linear Gaussian views.
The proof will appear here as you work.

Step 1 of 3. What is added in the negative exponent of the posterior density?

QuizEqual risk and financing
Why might a risk parity portfolio of bonds and equities use leverage to reach a volatility target?
CodeHierarchy and allocation
Implement hrp_weights(cov) for a symmetric positive definite matrix of at least two assets. Convert correlation to distance sqrt((1−ρ)/2), apply single linkage to condensed distances, order the leaves and allocate recursively by bisection using variances of internal inverse-variance portfolios. Return long-only weights that sum to one. Then use the lab simulation to compare test variance with sample and shrunk GMV.
def hrp_weights(cov):
  raise NotImplementedError()
Shift+Enter to run

Key takeaways

Key idea
Building a portfolio means choosing an exposure rule under uncertain estimation, constraints and costs. A model’s optimal solution is no guarantee out of sample.

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.