Skip to content

Portfolio Optimisation and Risk Modelling

Building an investment portfolio is never merely about hunting for the single highest-returning asset, because an asset that soars one year can wipe out a decade of savings the next. This file unpacks how diversification tames uncertainty, why Harry Markowitz's classic mean-variance optimisation breaks down on noisy financial data, how practitioners stabilise allocations with covariance shrinkage, Black-Litterman priors, and Hierarchical Risk Parity, and why modern risk desks measure crashes through Expected Shortfall rather than Value at Risk alone.

  • Imagine running a small seaside stall that sells only sunglasses. On sunny August afternoons you make a handsome profit, yet whenever rain clouds roll in for a fortnight your takings collapse to zero. Now suppose you share the stall with a partner selling umbrellas. Your combined average daily income stays just as healthy, while your worst-case weeks vanish almost overnight because rain boosts one product whenever it hurts the other.

  • That simple seaside stall captures the single most celebrated "free lunch" in financial mathematics, diversification. When you blend assets whose day-to-day swings do not move in lockstep, their ups and downs partially cancel out, shrinking overall portfolio volatility without forcing you to accept a lower expected return.

Diversification and Mean-Variance Optimisation

  • Let a portfolio hold \(N\) risky assets with portfolio weights \(\mathbf{w} = (w_1, \dots, w_N)^T \in \mathbb{R}^N\) summing to one (\(\mathbf{1}^T \mathbf{w} = 1\)). Suppose asset \(i\) has expected return \(\mu_i\), collected in the mean vector \(\boldsymbol{\mu} \in \mathbb{R}^N\), and asset returns share a symmetric positive-definite covariance matrix \(\Sigma \in \mathbb{R}^{N \times N}\) (Chapter 04), where diagonal entries \(\Sigma_{ii} = \sigma_i^2\) give individual variances and off-diagonal entries \(\Sigma_{ij} = \rho_{ij} \sigma_i \sigma_j\) encode pairwise correlations \(\rho_{ij} \in [-1, 1]\).

  • By linearity of expectation and the quadratic form of variance (Chapters 02 and 05), the portfolio's expected return \(\mu_p\) and variance \(\sigma_p^2\) are

\[\mu_p = \mathbf{w}^T \boldsymbol{\mu}, \qquad \sigma_p^2 = \mathbf{w}^T \Sigma \mathbf{w} = \sum_{i=1}^{N} w_i^2 \sigma_i^2 + \sum_{i \ne j} w_i w_j \rho_{ij} \sigma_i \sigma_j\]
  • Look at that second sum for just two assets with equal weights \(w_1 = w_2 = 0.5\) and identical volatility \(\sigma\). The portfolio standard deviation simplifies to \(\sigma_p = \sigma \sqrt{(1 + \rho)/2}\). Whenever correlation \(\rho < 1\), portfolio risk drops strictly below \(\sigma\), and if two assets happen to be perfectly negatively correlated (\(\rho = -1\)), risk disappears completely.

Markowitz Mean-Variance Optimisation and the Efficient Frontier

  • In 1952, Harry Markowitz formalised portfolio construction as a convex quadratic programme (Nobel Prize in Economics, 1990). Given a risk-tolerance parameter \(\gamma \ge 0\) (equivalently a risk-aversion coefficient \(\lambda = 1/\gamma\)), an investor trades off portfolio variance against expected return by solving
\[\min_{\mathbf{w} \in \mathbb{R}^N} \; \frac{1}{2} \mathbf{w}^T \Sigma \mathbf{w} - \gamma \, \boldsymbol{\mu}^T \mathbf{w} \qquad \text{subject to} \quad \mathbf{1}^T \mathbf{w} = 1\]
  • Most institutional funds also enforce long-only constraints (\(w_i \ge 0\)) so the optimiser cannot place unbounded short bets against assets, alongside position caps (\(w_i \le w_{\max}\)) to keep portfolios sensible.

  • Sweeping \(\gamma\) from \(0\) upward traces a graceful sideways parabola in risk-return space known as the Markowitz bullet. Its leftmost nose is the Minimum Variance Portfolio (the lowest volatility achievable from risky assets alone). Every portfolio on the upper rim above that nose forms the Efficient Frontier, because no other mix offers higher expected return for the same level of risk. Any portfolio sitting inside or along the lower rim is dominated, meaning you could move strictly upward for more return or strictly leftward for less risk.

Markowitz efficient frontier showing individual assets inside the feasible region, the minimum variance portfolio, the tangency maximum Sharpe portfolio on the Capital Market Line, and practical stabilisers including Ledoit-Wolf shrinkage, Black-Litterman, and Risk Parity

Sharpe Ratio, Capital Market Line, and Sortino Ratio

  • How should you compare two portfolios sitting at different points along the frontier? Introduce a risk-free asset such as a short-term government Treasury bill paying guaranteed return \(r_f\). Drawing a straight line from \((0, r_f)\) tangent to the Efficient Frontier yields the Capital Market Line (CML), and the exact point where that line kisses the frontier is the Tangency Portfolio.

  • The slope of any line drawn from \((0, r_f)\) to a portfolio \((\sigma_p, \mu_p)\) is William Sharpe's famous Sharpe Ratio, measuring excess return earned per unit of total volatility.

\[\text{Sharpe} = \frac{\mu_p - r_f}{\sigma_p}\]
  • The Tangency Portfolio maximises the Sharpe ratio over all risky combinations. Every rational investor who can lend or borrow at \(r_f\) simply holds a blend of cash and this single Tangency Portfolio, dialling risk up or down along the CML.

  • Standard deviation treats wild upside rallies as just as "risky" as painful crashes, which feels strange to real investors who happily welcome a surprise +8% gain. The Sortino Ratio fixes this symmetry by replacing total volatility \(\sigma_p\) with downside deviation \(\sigma_d\), computed only over returns falling below a target threshold \(r_{\text{target}}\) (often \(r_f\) or \(0\)).

\[\text{Sortino} = \frac{\mu_p - r_{\text{target}}}{\sigma_d}, \qquad \sigma_d = \sqrt{\mathbb{E}\!\left[\min\!\left(0,\, R_p - r_{\text{target}}\right)^2\right]}\]

Why Vanilla Markowitz Blows Up in Practice

  • Hand an unconstrained Markowitz solver a historical spreadsheet of 50 stocks and something alarming happens. Instead of crafting a balanced, diversified portfolio, the optimiser dumps 85% of your wealth into two obscure mining companies, shorts three blue-chip firms, and completely flips those bets next month when a single week of new data arrives. Richard Michaud famously nicknamed vanilla mean-variance optimisation an "error maximiser".

  • Two deep mathematical culprits cause this instability.

  • Extreme sensitivity to noisy expected returns (\(\hat{\boldsymbol{\mu}}\)). Estimating a stock's true future mean return from finite noisy returns is notoriously hard (requiring decades of stationary data to pin down even one percentage point reliably, Chapter 04). Because the unconstrained solution scales with \(\Sigma^{-1} \hat{\boldsymbol{\mu}}\), the optimiser eagerly hunts for whichever assets happened to enjoy lucky sample noise in \(\hat{\boldsymbol{\mu}}\) and piles massive leverage onto them.

  • Ill-conditioned covariance matrices (\(\hat{\Sigma}\)). Recall the condition number \(\kappa(\Sigma) = \lambda_{\max} / \lambda_{\min}\) from Chapter 02, which measures how violently matrix inversion amplifies tiny measurement errors. Whenever the number of assets \(N\) approaches or exceeds the number of historical observations \(T\), the sample covariance matrix \(S\) develops tiny spurious eigenvalues (\(\lambda_{\min} \approx 0\), or exact zero when \(N > T\)). Inverting \(S\) blows up \(1/\lambda_{\min}\) into enormous positive and negative weights chasing pure estimation noise rather than genuine diversification.

Practical Stabilisers Used by Modern Quant Desks

  • Practitioners rarely abandon diversification principles altogether. Instead, they repair the fragile inputs \(\hat{\Sigma}\) and \(\hat{\boldsymbol{\mu}}\), or sidestep matrix inversion completely.

Ledoit-Wolf Covariance Shrinkage

  • Think of asking a friend who has only watched three tennis matches to estimate the exact win rates of twenty players. Rather than trusting those wildly noisy sample numbers blindly, a sensible statistician pulls every extreme estimate gently toward a calm baseline average.

  • Ledoit-Wolf shrinkage applies this exact bias-variance trade-off (Chapter 06) to the sample covariance matrix \(S\). It forms a convex combination of \(S\) and a clean, well-conditioned target matrix \(F\) (such as a scaled identity matrix \(\bar{v} I\) or a constant-correlation matrix), governed by an analytically derived optimal shrinkage intensity \(\delta \in [0, 1]\).

\[\hat{\Sigma}_{\text{LW}} = (1 - \delta) S + \delta F\]
  • Adding \(\delta F\) lifts all tiny noise eigenvalues safely away from zero without distorting the dominant market factors. The condition number \(\kappa(\hat{\Sigma}_{\text{LW}})\) plunges dramatically, \(\hat{\Sigma}_{\text{LW}}^{-1}\) stays well-behaved even when \(N > T\), and out-of-sample portfolio volatility drops sharply.

Black-Litterman Bayesian Allocation

  • What if you do not trust historical average returns at all, yet your research team holds two specific convictions, such as believing European utilities will outperform energy stocks by 2% next year? Fischer Black and Robert Litterman solved this in 1992 using pure Gaussian Bayesian updating from Chapter 05.

  • First, instead of estimating \(\boldsymbol{\mu}\) from noisy past averages, they reverse-engineer the implied market-equilibrium returns \(\boldsymbol{\pi}\) that would make today's capitalisation-weighted market portfolio \(\mathbf{w}_{\text{mkt}}\) optimal under Markowitz theory, written \(\boldsymbol{\pi} = \lambda \Sigma \mathbf{w}_{\text{mkt}}\). That equilibrium vector serves as a calm, diversified prior distribution \(\boldsymbol{\mu} \sim \mathcal{N}(\boldsymbol{\pi}, \tau \Sigma)\), where small scalar \(\tau\) sets prior uncertainty.

  • Next, an analyst expresses \(K\) subjective views as linear statements \(P \boldsymbol{\mu} = \mathbf{q} + \boldsymbol{\varepsilon}\) with view-uncertainty covariance \(\Omega = \operatorname{Cov}(\boldsymbol{\varepsilon})\). Combining prior and views via Bayes' rule yields the Black-Litterman posterior expected returns.

\[\boldsymbol{\mu}_{\text{BL}} = \left[(\tau \Sigma)^{-1} + P^T \Omega^{-1} P\right]^{-1}\left[(\tau \Sigma)^{-1} \boldsymbol{\pi} + P^T \Omega^{-1} \mathbf{q}\right]\]
  • If you hold zero views, Black-Litterman cleanly hands you back the market portfolio. When you add a confident view on one sector, weights tilt smoothly toward that conviction while leaving the rest of the portfolio undisturbed.

Risk Parity and Hierarchical Risk Parity (HRP)

  • Notice a curious flaw in a classic 60% equities and 40% government bonds portfolio. Because equities are roughly three times as volatile as bonds, equities actually generate nearly 90% of the portfolio's total risk. Dollar balance is not risk balance.

  • Risk Parity (Equal Risk Contribution) abandons noisy return forecasts \(\boldsymbol{\mu}\) altogether and chooses weights so every asset contributes the exact same share of total portfolio variance. Since portfolio risk decomposes via Euler's theorem as \(\sigma_p^2 = \sum_{i=1}^{N} w_i (\Sigma \mathbf{w})_i\), Risk Parity solves for weights satisfying

\[w_i (\Sigma \mathbf{w})_i = \frac{1}{N} \mathbf{w}^T \Sigma \mathbf{w} \qquad \text{for every } i = 1, \dots, N\]
  • Even Risk Parity still interacts with the full covariance matrix when assets are tightly correlated. Marcos Lopez de Prado's Hierarchical Risk Parity (HRP) goes one step further by eliminating covariance inversion entirely through a three-stage graph and clustering pipeline.

  • Tree clustering. Convert pairwise correlations \(\rho_{ij}\) into proper metric distances \(d_{ij} = \sqrt{\frac{1}{2}(1 - \rho_{ij})}\) and run hierarchical agglomerative clustering to group closely related assets (say tech stocks in one branch, sovereign bonds in another) into a dendrogram tree.

  • Quasi-diagonalisation. Reorder the rows and columns of \(\Sigma\) along the leaves of that tree so strongly correlated assets sit right next to each other near the diagonal.

  • Recursive bisection. Split the ordered list repeatedly into left and right clusters and allocate capital across each split in inverse proportion to cluster variance, \(w_{\text{left}} \propto 1/V_{\text{left}}\) and \(w_{\text{right}} \propto 1/V_{\text{right}}\). Because HRP never computes \(\Sigma^{-1}\), small estimation errors remain strictly local inside their branch rather than exploding across the entire portfolio.

Tail Risk Modelling Beyond Volatility

  • Imagine driving along a winding mountain cliff road in thick fog. Knowing your average steering wobble over the last ten miles (standard deviation) tells you almost nothing about how close your front tyres are to dropping 400 metres over the edge. Financial returns behave just like that mountain road because they exhibit fat tails (leptokurtosis) and negative skewness, meaning market crashes arrive far more often and strike far harder than a Gaussian bell curve ever predicts.

Value at Risk and Why It Can Mislead

  • In the 1990s, J.P. Morgan popularised Value at Risk (\(\text{VaR}_\alpha\)) to summarise downside danger in a single number. Let \(L = -R_p\) denote portfolio loss over a fixed horizon (such as one day or ten days). At confidence level \(\alpha \in (0, 1)\) (commonly 95% or 99%), \(\text{VaR}_\alpha\) is the smallest loss threshold exceeded with probability at most \(1 - \alpha\).
\[\text{VaR}_\alpha(L) = \inf \left\{ \ell \in \mathbb{R} \;\middle|\; \mathbb{P}(L > \ell) \le 1 - \alpha \right\}\]
  • Saying a desk has a one-day 99% VaR of £5 million means that on 99 trading days out of 100, losses should stay below £5 million. While wonderfully easy to communicate to executives, VaR hides two dangerous mathematical defects.

  • VaR is blind to tail severity. It marks only the cliff edge and ignores how deep the drop goes once you cross it. Two portfolios can share an identical 99% VaR of £5 million while one loses £5.1 million on bad days and the other loses £500 million and bankrupts the bank.

  • VaR fails subadditivity. Artzner et al. (1999) defined coherent risk measures around four sensible axioms, the most famous being subadditivity, \(\rho(L_A + L_B) \le \rho(L_A) + \rho(L_B)\), which guarantees that merging two portfolios never looks riskier than holding them separately. Surprisingly, VaR breaks this rule. Suppose Bond A and Bond B each default independently with 4% probability, losing £100 upon default and £0 otherwise. Individually, each bond's 95% VaR is £0 because default happens less than 5% of the time. Hold both bonds together, however, and the chance that at least one defaults jumps to \(1 - 0.96^2 = 7.84\% > 5\%\), causing the combined 95% VaR to leap from £0 to £100! Under VaR, diversification falsely looks more dangerous than concentration.

Comparison of Value at Risk and Expected Shortfall on a fat-tailed portfolio return distribution showing VaR stopping at the 5 percent tail boundary while CVaR averages all severe losses inside the shaded crash region

Expected Shortfall (Conditional Value at Risk)

  • Expected Shortfall, also called Conditional Value at Risk (\(\text{CVaR}_\alpha\)), repairs both flaws at once by asking the question every risk manager truly cares about. "Assuming we land in the worst \((1-\alpha)\) fraction of days, how much do we lose on average?"
\[\text{CVaR}_\alpha(L) = \mathbb{E}\!\left[L \;\middle|\; L \ge \text{VaR}_\alpha(L)\right] = \frac{1}{1 - \alpha} \int_{\alpha}^{1} \text{VaR}_u(L)\,du\]
  • Because CVaR integrates across the entire extreme tail, it immediately penalises catastrophic crash scenarios that VaR overlooks. Better still, CVaR is provably a coherent risk measure (always obeying subadditivity) and, thanks to the Rockafellar-Uryasev (2000) variational identity, it is convex in portfolio weights \(\mathbf{w}\), allowing quant desks to minimise CVaR directly with gradient or linear programming solvers. Following the 2008 financial crisis, global banking regulators under Basel III officially shifted market-risk capital rules from 99% VaR to 97.5% Expected Shortfall.

Monte Carlo Simulation and Historical Stress Testing

  • Computing reliable VaR and CVaR requires a realistic distribution of future joint market moves, which risk engines construct through two complementary lenses.

  • Fat-tailed Monte Carlo simulation. Rather than assuming thin-tailed multivariate Gaussians, desks simulate tens of thousands of correlated market paths drawn from heavy-tailed Student-\(t\) distributions or copula models, using the Cholesky factorisation \(\Sigma = L L^T\) (Chapter 02) to inject cross-asset correlation while preserving joint crash behaviour.

  • Historical stress testing and crisis replay. Statistical models fitted during calm years quietly assume historical correlations hold steady, yet during genuine panics (such as the September 2008 Lehman collapse or the March 2020 liquidity freeze) correlations across risky assets violently spike toward \(+1\) right when you need diversification most. Stress testing replays exact historical crisis shocks and hypothetical macroeconomic disasters directly across today's book to verify the institution can survive when normal statistical assumptions break.

Take-Home

  • Diversification lowers risk through imperfect correlation, bowing the Markowitz Efficient Frontier leftward so a blended portfolio achieves a higher Sharpe ratio than its individual components, while the Sortino ratio refines performance measurement by penalising only downside volatility.
  • Vanilla mean-variance optimisation is an error maximiser because small sampling errors in expected returns \(\hat{\boldsymbol{\mu}}\) and near-singular eigenvalues in an ill-conditioned sample covariance \(\hat{\Sigma}\) explode upon matrix inversion.
  • Modern allocators tame estimation noise cleanly, using Ledoit-Wolf covariance shrinkage to improve conditioning, Black-Litterman Bayesian updating to blend market equilibrium with explicit views, and Risk Parity or Hierarchical Risk Parity to balance risk without brittle covariance inversion.
  • Value at Risk stops at the cliff edge and fails subadditivity, whereas Expected Shortfall (CVaR) averages losses across the entire extreme tail, obeys every coherence axiom, and remains convex for direct portfolio optimisation.
  • Robust risk management pairs fat-tailed Monte Carlo with crisis stress testing, guarding against regime shifts where correlations suddenly converge toward one during market panics.

Coding Tasks (use CoLab or notebook)

  1. Trace the Markowitz Efficient Frontier for four correlated assets by comparing random feasible portfolios against long-only frontier portfolios solved with jax.grad. Identify the Minimum Variance and Maximum Sharpe portfolios and compute both Sharpe and Sortino ratios.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    # 4 assets: Bonds, Global Equity, Tech Equity, Gold
    mu = jnp.array([0.04, 0.08, 0.12, 0.055])
    vols = jnp.array([0.05, 0.15, 0.24, 0.14])
    corr = jnp.array([
        [1.00, 0.10, 0.05, 0.20], [0.10, 1.00, 0.78, -0.05],
        [0.05, 0.78, 1.00, -0.10], [0.20, -0.05, -0.10, 1.00],
    ])
    Sigma = jnp.outer(vols, vols) * corr
    rf = 0.025
    
    # Sample 4,000 random long-only portfolios on the simplex
    k1, k2 = jax.random.split(jax.random.PRNGKey(42))
    raw = -jnp.log(jax.random.uniform(k1, (4000, 4), minval=1e-6, maxval=1.0))
    W_rand = raw / jnp.sum(raw, axis=1, keepdims=True)
    ret_rand = W_rand @ mu
    vol_rand = jnp.sqrt(jnp.sum((W_rand @ Sigma) * W_rand, axis=1))
    
    # Trace long-only efficient frontier via softmax parametrisation + jax.grad
    def solve_frontier(gamma, steps=250, lr=0.35):
        def obj(logits):
            w = jax.nn.softmax(logits)
            return 0.5 * (w @ Sigma @ w) - gamma * (w @ mu)
        grad_fn, logits = jax.grad(obj), jnp.zeros(4)
        for _ in range(steps):
            logits = logits - lr * grad_fn(logits)
        w = jax.nn.softmax(logits)
        return w, float(w @ mu), float(jnp.sqrt(w @ Sigma @ w))
    
    gammas = [0.0, 0.05, 0.12, 0.22, 0.35, 0.55, 0.85, 1.3, 2.2, 4.0]
    ef_weights, ef_rets, ef_vols = zip(*[solve_frontier(g) for g in gammas])
    ef_sharpes = [(r - rf) / v for r, v in zip(ef_rets, ef_vols)]
    idx_min = int(jnp.argmin(jnp.array(ef_vols)))
    idx_max = int(jnp.argmax(jnp.array(ef_sharpes)))
    w_star = ef_weights[idx_max]
    
    # Compute Sortino ratio via Monte Carlo draws from N(mu, Sigma)
    sim_port = (mu + jax.random.normal(k2, (10000, 4)) @ jnp.linalg.cholesky(Sigma).T) @ w_star
    sortino = (ef_rets[idx_max] - rf) / float(jnp.sqrt(jnp.mean(jnp.minimum(0.0, sim_port - rf) ** 2)))
    
    print(f"Min-Var    -> Return: {ef_rets[idx_min]:.2%}, Vol: {ef_vols[idx_min]:.2%}")
    print(f"Max-Sharpe -> Return: {ef_rets[idx_max]:.2%}, Vol: {ef_vols[idx_max]:.2%}, Sharpe: {ef_sharpes[idx_max]:.2f}, Sortino: {sortino:.2f}")
    print("Max-Sharpe weights [Bonds, Global, Tech, Gold]:", [round(float(x), 3) for x in w_star])
    
    plt.figure(figsize=(8, 4.2))
    sc = plt.scatter(vol_rand, ret_rand, c=(ret_rand - rf) / vol_rand, cmap="viridis", s=10, alpha=0.45)
    plt.colorbar(sc, label="Sharpe Ratio")
    plt.plot(ef_vols, ef_rets, color="#27ae60", lw=3, label="Efficient Frontier")
    plt.scatter(vols, mu, color="#f39c12", s=80, edgecolor="#333", zorder=5, label="Single Assets")
    plt.scatter([ef_vols[idx_min]], [ef_rets[idx_min]], color="#9b59b6", s=100, zorder=6, label="Min Variance")
    plt.scatter([ef_vols[idx_max]], [ef_rets[idx_max]], color="#e74c3c", s=120, marker="*", zorder=6, label="Max Sharpe")
    plt.xlabel("Annual Volatility (sigma)"); plt.ylabel("Expected Return (mu)")
    plt.title("Markowitz Efficient Frontier in Risk-Return Space")
    plt.legend(); plt.grid(alpha=0.3); plt.tight_layout(); plt.show()
    

  2. Observe covariance ill-conditioning with \(N=15\) assets and only \(T=25\) noisy periods. Compare condition numbers, weight extremity, and true out-of-sample volatility for Vanilla Markowitz, Ledoit-Wolf Shrinkage, and Risk Parity solved via jax.grad.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    k1, k2, k3 = jax.random.split(jax.random.PRNGKey(7), 3)
    N, T = 15, 25
    beta = jax.random.uniform(k1, (N, 1), minval=0.4, maxval=1.4)
    idio = jax.random.uniform(k2, (N,), minval=0.08, maxval=0.20)
    Sigma_true = (0.14 ** 2) * (beta @ beta.T) + jnp.diag(idio ** 2)
    
    # Short noisy sample covariance S vs Ledoit-Wolf shrinkage towards scaled identity
    R = jax.random.normal(k3, (T, N)) @ jnp.linalg.cholesky(Sigma_true).T
    R_c = R - jnp.mean(R, axis=0, keepdims=True)
    S = (R_c.T @ R_c) / (T - 1)
    Sigma_lw = 0.55 * S + 0.45 * (jnp.trace(S) / N) * jnp.eye(N)
    
    ones = jnp.ones(N)
    w_vanilla = jnp.linalg.solve(S + 1e-6 * jnp.eye(N), ones)
    w_vanilla = w_vanilla / jnp.sum(w_vanilla)
    w_shrunk = jnp.linalg.solve(Sigma_lw, ones)
    w_shrunk = w_shrunk / jnp.sum(w_shrunk)
    
    # Risk Parity (Equal Risk Contribution) on Sigma_lw via JAX autodiff
    def rp_loss(logits):
        w = jax.nn.softmax(logits)
        rc = w * (Sigma_lw @ w)
        return jnp.sum((rc - (w @ Sigma_lw @ w) / N) ** 2)
    
    grad_rp, logits = jax.grad(rp_loss), jnp.zeros(N)
    for _ in range(300):
        logits = logits - 30.0 * grad_rp(logits)
    w_rp = jax.nn.softmax(logits)
    
    vols_oos = [float(jnp.sqrt(w @ Sigma_true @ w)) for w in (w_vanilla, w_shrunk, w_rp)]
    print(f"Cond numbers -> True: {float(jnp.linalg.cond(Sigma_true)):.1f} | Sample S: {float(jnp.linalg.cond(S)):.1f} | Shrunk: {float(jnp.linalg.cond(Sigma_lw)):.1f}")
    print(f"True OOS Vol -> Vanilla: {vols_oos[0]:.2%} | Shrunk: {vols_oos[1]:.2%} | Risk Parity: {vols_oos[2]:.2%}")
    
    fig, axes = plt.subplots(1, 2, figsize=(10.5, 4))
    x = jnp.arange(N)
    axes[0].bar(x - 0.25, w_vanilla, width=0.25, color="#e74c3c", label="Vanilla Markowitz")
    axes[0].bar(x,        w_shrunk,  width=0.25, color="#3498db", label="Ledoit-Wolf Shrunk")
    axes[0].bar(x + 0.25, w_rp,      width=0.25, color="#27ae60", label="Risk Parity")
    axes[0].axhline(0, color="#333", lw=0.8)
    axes[0].set_xlabel("Asset Index"); axes[0].set_ylabel("Weight")
    axes[0].set_title("Weight Stability (N=15, T=25)"); axes[0].legend(); axes[0].grid(alpha=0.3)
    
    axes[1].bar(["Vanilla\nMarkowitz", "Ledoit-Wolf\nShrunk", "Risk\nParity"], [v * 100 for v in vols_oos], color=["#e74c3c", "#3498db", "#27ae60"], alpha=0.85)
    axes[1].set_ylabel("True Out-of-Sample Volatility (%)")
    axes[1].set_title("Realised Risk Against True Covariance"); axes[1].grid(axis="y", alpha=0.3)
    plt.tight_layout(); plt.show()
    

  3. Simulate Gaussian vs fat-tailed Student-\(t\) daily losses to compare VaR against Expected Shortfall (CVaR), and verify on two independent 4%-default bonds how 95% VaR breaks subadditivity while 95% CVaR obeys it.

    import jax
    import jax.numpy as jnp
    import matplotlib.pyplot as plt
    
    def var_and_cvar(losses, alpha=0.95):
        sorted_l = jnp.sort(losses)
        idx = int(jnp.ceil(alpha * sorted_l.shape[0])) - 1
        return float(sorted_l[idx]), float(jnp.mean(sorted_l[idx:]))
    
    k1, k2, k3, k4 = jax.random.split(jax.random.PRNGKey(101), 4)
    M, sigma_daily, df = 30000, 0.015, 3.0
    loss_gauss = jax.random.normal(k1, (M,)) * sigma_daily
    chi2 = jnp.sum(jax.random.normal(k3, (M, 3)) ** 2, axis=1)
    loss_fat = (jax.random.normal(k2, (M,)) / jnp.sqrt(chi2 / df)) * (sigma_daily / jnp.sqrt(df / (df - 2.0)))
    
    for name, arr in [("Gaussian", loss_gauss), ("Fat-Tailed (t, df=3)", loss_fat)]:
        v95, c95 = var_and_cvar(arr, 0.95)
        v99, c99 = var_and_cvar(arr, 0.99)
        print(f"{name:21s} -> 95% VaR/CVaR: {v95:.2%} / {c95:.2%} | 99% VaR/CVaR: {v99:.2%} / {c99:.2%}")
    
    # Subadditivity test: two independent 4%-default bonds (loss=100 on default)
    u = jax.random.uniform(k4, (M, 2))
    bond_A, bond_B = jnp.where(u[:, 0] < 0.04, 100.0, 0.0), jnp.where(u[:, 1] < 0.04, 100.0, 0.0)
    vA, cA = var_and_cvar(bond_A, 0.95)
    vB, cB = var_and_cvar(bond_B, 0.95)
    vAB, cAB = var_and_cvar(bond_A + bond_B, 0.95)
    print(f"VaR(A)+VaR(B)   = {vA+vB:.2f} vs VaR(A+B)  = {vAB:.2f} (Subadditivity BROKEN)")
    print(f"CVaR(A)+CVaR(B) = {cA+cB:.2f} vs CVaR(A+B) = {cAB:.2f} (Subadditivity OBEYED)")
    
    v95_f, c95_f = var_and_cvar(loss_fat, 0.95)
    plt.figure(figsize=(8.2, 4.0))
    plt.hist(jnp.clip(loss_gauss, -0.08, 0.09), bins=85, density=True, alpha=0.35, color="#999999", label="Gaussian losses")
    plt.hist(jnp.clip(loss_fat, -0.08, 0.09), bins=85, density=True, alpha=0.55, color="#3498db", label="Fat-tailed Student-t")
    plt.axvline(v95_f, color="#e74c3c", lw=2.2, ls="--", label=f"95% VaR ({v95_f:.2%})")
    plt.axvline(c95_f, color="#9b59b6", lw=2.5, label=f"95% CVaR ({c95_f:.2%})")
    plt.xlabel("Daily Portfolio Loss (+ = loss)"); plt.ylabel("Density")
    plt.title("Fat Tails Widen the Gap Between VaR and Expected Shortfall (CVaR)")
    plt.legend(); plt.grid(alpha=0.3); plt.tight_layout(); plt.show()