Module contents
Lesson 17 of 30Core 105 min

Risk measures: VaR, Expected Shortfall and their estimation

Define and estimate value at risk and expected shortfall, examine coherent risk and nonlinear positions, and allocate portfolio risk.

After this lesson you can

  • Define VaR and ES as loss-distribution functionals and calculate them for normal and Student distributions.
  • State coherent-risk axioms and construct a counterexample to VaR subadditivity.
  • Implement parametric, historical, filtered historical and Monte Carlo VaR and ES.
  • Approximate option-portfolio risk using delta-gamma and compare with full repricing.
  • Decompose VaR and ES into position contributions using Euler allocation.

Before you start

A threshold and what lies beyond

Two portfolios can have equal volatility and very different extreme losses. Defining risk requires stating portfolio, horizon, currency, factor set, available information and loss distribution. If VtV_t is value and there are no flows, take L=Vt−Vt+hL=V_t-V_{t+h}: loss is positive and gain negative. A short position or option means converting returns to losses requires repricing, not merely changing a sign.

Value at risk (VaR) at level α∈(0,1)\alpha\in(0,1) is the lower quantile qα(L)=inf⁡{x:FL(x)≥α}q_\alpha(L)=\inf\{x:F_L(x)\geq\alpha\}. It is not maximum loss: the tail can be much larger. Expected shortfall (ES) is the average of upper quantiles:

ES⁡α(L)=11−α∫α1qu(L) du.\operatorname{ES}_\alpha(L)=\frac{1}{1-\alpha}\int_\alpha^1q_u(L)\,du.

Assume integrable loss. For a continuous distribution with no mass at the threshold, this is conditional expected LL above VaR. With atoms that expression may be incorrect: take only the fraction of the atom needed to complete probability 1−α1-\alpha. This distinction is essential for credit portfolios; see Acerbi and Tasche.

InteractiveThreshold and tail center
  • Density
  • VaR
  • ES
95 %
Distribution
VaR1.645
ES2.063
Change confidence and model. Compare the threshold with the tail average.

Figure losses follow a standard normal, a Student-t with three or five degrees of freedom scaled to unit variance, or a mixture of 90% standard normal and 10% normal with standard deviation 3. The last is equivalent to adding an independent normal jump of variance 8 to a standard normal with 10% probability and no jump otherwise. The horizontal scale is clipped at 8 to show models; readings use the full tail. The mixture does not have unit variance and therefore does not isolate tail-shape effects.

Coherence and diversification

A coherent measure of losses satisfies monotonicity, cash translation, positive homogeneity and subadditivity. Under this convention, L≤ML\le M implies ρ(L)≤ρ(M)\rho(L)\le\rho(M); ρ(L+c)=ρ(L)+c\rho(L+c)=\rho(L)+c; ρ(λL)=λρ(L)\rho(\lambda L)=\lambda\rho(L) for λ≥0\lambda\ge0; and ρ(L+M)≤ρ(L)+ρ(M)\rho(L+M)\le\rho(L)+\rho(M). The last property says combining positions does not increase risk beyond the sum of their isolated risks.

Consider two independent bonds, each losing 1 on default and 0 otherwise, with default probability 4%. At 95%, each VaR is 0 because zero loss has probability 96%. For both bonds, no loss has probability 0.962=0.92160.96^2=0.9216, exactly one loss 2(0.04)(0.96)=0.07682(0.04)(0.96)=0.0768 and two losses 0.00160.0016. VaR of the sum is 1, greater than 0+0. Individual ES is 0.8 and combined ES is (2⋅0.0016+1⋅0.0484)/0.05=1.032(2\cdot0.0016+1\cdot0.0484)/0.05=1.032, less than 1.6. The tail includes a fraction of the one-loss scenario.

InteractiveTwo bonds and a quantile jump
00.20.40.60.81No default0.9216One default0.0768Two defaults0.0016
4.0 %
VaR for each bond0.00
VaR for both bonds1.00
Sum of individual ES1.60
ES for both bonds1.03
Change default probability and compare summed risks with joint risk.

For integrable losses, ES satisfies all four axioms. A subadditivity proof starts from the dual representation ES⁡α(L)=sup⁡ZE[ZL]\operatorname{ES}_\alpha(L)=\sup_Z \E[ZL], where 0≤Z≤(1−α)−10\le Z\le(1-\alpha)^{-1} and E[Z]=1\E[Z]=1. The same admissible family is used for L+ML+M, so the supremum of the sum cannot exceed the sum of suprema. VaR is subadditive in some families, such as linear Gaussian portfolios, but not generally.

The integral definition also presents ES as a spectral measure: it assigns constant weight 1/(1−α)1/(1-\alpha) to quantiles between α\alpha and 1, and zero weight elsewhere. The weight function is nonnegative, integrates to one and is nondecreasing in quantile level. Higher losses thus receive at least equal importance. Coherence does not make a particular estimate precise: it is a property of the functional on the distribution, not a guarantee of data or forecast quality.

Normal, Student and moment approximation

For L=μ+σZL=\mu+\sigma Z, with σ>0\sigma>0 and standard normal ZZ, zα=Φ−1(α)z_\alpha=\Phi^{-1}(\alpha) gives

VaR⁡α=μ+σzα,ES⁡α=μ+σϕ(zα)1−α.\operatorname{VaR}_\alpha=\mu+\sigma z_\alpha,\qquad \operatorname{ES}_\alpha=\mu+\sigma\frac{\phi(z_\alpha)}{1-\alpha}.

For T∼tνT\sim t_\nu, ν>1\nu>1, and L=μ+sTL=\mu+sT with s>0s>0, let q=tν−1(α)q=t_\nu^{-1}(\alpha) and fνf_\nu be its density. Then VaR⁡=μ+sq\operatorname{VaR}=\mu+sq and ES⁡=μ+s(ν+q2)fν(q)/[(ν−1)(1−α)]\operatorname{ES}=\mu+s(\nu+q^2)f_\nu(q)/[(\nu-1)(1-\alpha)]. Here ss is scale, not standard deviation: for ν>2\nu>2 the latter is sν/(ν−2)s\sqrt{\nu/(\nu-2)}. The tail integral follows by integrating xfν(x)x f_\nu(x) using the derivative of (1+x2/ν)−(ν−1)/2(1+x^2/\nu)^{-(\nu-1)/2}.

Cornish-Fisher approximates the standardized quantile using skewness γ1\gamma_1 and excess kurtosis γ2\gamma_2: z+(z2−1)γ1/6+(z3−3z)γ2/24−(2z3−5z)γ12/36z+(z^2-1)\gamma_1/6+(z^3-3z)\gamma_2/24-(2z^3-5z)\gamma_1^2/36. It is an approximate expansion, not a guaranteed distribution or cure for short samples or very heavy tails. Noisy higher-moment estimates can worsen the result.

For a linear portfolio with multivariate-normal unit-loss vector X\vb{X}, L=w⊤XL=\vb{w}\T\vb{X} has mean w⊤μ\vb{w}\T\vb{\mu} and variance w⊤Σw\vb{w}\T\mat{\Sigma}\vb{w}. This reduction uses full covariance, not only individual volatilities. The mean can be negative, and loss VaR can also be negative: the selected quantile remains a gain under the stated convention. Replacing it with zero changes the measure. A nonlinear portfolio does not inherit a normal distribution merely because factors are normal.

Historical scenarios and conditional volatility

Historical simulation applies historical factor movements to the current portfolio, estimates losses and takes their empirical quantile and weighted tail average. Scenarios may be weighted by age, but effective weights and the window change precision and adaptation speed. A window need not contain the next crisis; using adjusted prices without checking conventions can also introduce errors.

With weights pi≥0p_i\geq0 summing to one, order losses from largest to smallest. ES integrates scenario masses until accumulating 1−α1-\alpha; if the final mass exceeds the remainder, only the required fraction is taken. For example, exponential weighting assigns an observation of age jj weight proportional to λj\lambda^j, with 0<λ≤10<\lambda\leq1. Smaller λ\lambda reduces the influence of old events but also reduces effective size 1/∑ipi21/\sum_i p_i^2. An old extreme event may cease to influence the estimate while remaining plausible. Do not confuse age weight with an estimated occurrence probability for each scenario.

Filtered historical simulation estimates a mean and conditional-volatility model, divides historical innovations by estimated volatilities and rescales them with the current volatility forecast. With GARCH(1,1), ht=ω+aϵt−12+bht−1h_t=\omega+a\epsilon_{t-1}^2+bh_{t-1} and ht+1h_{t+1} is calculated only with information available through tt. Multivariate residuals must be resampled jointly by date to preserve empirical dependence. A misspecified model or nonstationary residuals remain error sources: no method is always best. The original method applies GARCH filtering to historical scenarios for derivative portfolios (Barone-Adesi et al.).

InteractiveA regime change

Independent normal returns have a standard deviation of 1% before period 150 and 3% afterward. The filter uses fixed GARCH parameters and cannot observe the regime change.

  • Loss
  • Historical
  • Normal
  • Filtered
80
Historical VaR exceptions19 / 220
Normal VaR exceptions18 / 220
Filtered VaR exceptions11 / 220
Change the window. How long do the three methods take to respond to higher volatility?

A Monte Carlo simulation generates factors jointly using a multivariate distribution or a copula with stated marginals. Tail dependence and linear correlation are not equivalent. Reprice the whole portfolio in every scenario, including time, rates, volatility and other changing factors. Delta-gamma uses ΔV≈Δ ΔS+12Γ(ΔS)2\Delta V\approx\Delta\,\Delta S+\tfrac12\Gamma(\Delta S)^2 with other variables fixed. Near strike and maturity, curvature changes rapidly and large movements can break the approximation; a short position reverses error sign. For many factors include the full Hessian with cross terms.

Full repricing handles nonlinearity of the pricing function within the chosen model. It does not guarantee correct specification of factor distribution, volatility smile or liquidity. A local approximation with finite time step also includes theta and sensitivities to volatility and rates; the comparison below fixes those factors and deliberately omits theta to show the difference between the two calculations.

InteractiveRepricing versus approximation

Black–Scholes with S = K = 100, zero interest and dividends, 30% annual volatility, and a one-day horizon. The 4,000 lognormal scenarios use a fixed seed. The histogram shows the fraction in each bin. The short-position loss is the change in the call price.

  • Repricing
  • Delta-gamma
10
1
99% VaR from repricing2.685
99% delta–gamma VaR2.818
Reduce maturity and compare distributions and their loss quantiles.

The square-root-of-time rule is not a general identity for quantiles. It is exact for the standard deviation of a sum of uncorrelated constant-variance increments, and for centered VaR of an independent Gaussian sum; the mean scales linearly. Volatility clustering, jumps, dependence and nonlinearity require modeling the horizon directly. A longer liquidity horizon may require closing costs and changing exposures.

Allocating risk

For L(w)=∑iwiLiL(\vb{w})=\sum_iw_iL_i, if ρ(w)\rho(\vb{w}) is homogeneous of degree one and differentiable, Euler’s theorem gives

ρ(w)=∑iwi∂ρ∂wi.\rho(\vb{w})=\sum_iw_i\frac{\partial\rho}{\partial w_i}.

The Euler contribution of position ii is wi∂iρw_i\partial_i\rho. With a continuous distribution and sufficient regularity, the ES derivative is E[Li∣L(w)≥VaR⁡α]\E[L_i\mid L(\vb{w})\geq\operatorname{VaR}_\alpha]. The contribution can be negative if the position hedges portfolio losses. With discrete scenarios or ties, the derivative may not be unique and consistent fractional weights at the threshold are needed.

To understand the sum, fix w\vb{w} and define g(t)=ρ(tw)g(t)=\rho(t\vb{w}). Homogeneity gives g(t)=tρ(w)g(t)=t\rho(\vb{w}), while the chain rule gives g′(1)=∑iwi∂iρ(w)g'(1)=\sum_iw_i\partial_i\rho(\vb{w}). These expressions are equal. The marginal measures the effect of increasing one exposure with others fixed; the component incorporates position size. Neither generally equals isolated position risk, because it depends on behavior in the portfolio tail. For VaR, under density and regularity conditions, the marginal is conditional expectation at the threshold, E[Li∣L=VaR⁡α]\E[L_i\mid L=\operatorname{VaR}_\alpha]; this differs from ES’s full-tail average. Conditioning on a point value of a continuous variable means using a regular conditional distribution or limit of bands around the threshold, not dividing by the event’s zero probability.

Lab: quantiles with mass at the threshold

The following function calculates exactly the mean of the worst 1−α1-\alpha of equally likely scenarios, with a fraction of the last. It does not average every value greater than or equal to the quantile, which can include too much mass.

[ ]Empirical VaR and ESBrowser
import numpy as np
from scipy.stats import norm, t

def var_es(losses, alpha):
    x=np.asarray(losses,dtype=float)
    if x.ndim!=1 or len(x)==0 or not np.isfinite(x).all() or not 0<alpha<1:
        raise ValueError('Escenarios finitos y nivel entre cero y uno')
    x=np.sort(x)
    n=len(x)
    var=float(x[int(np.ceil(alpha*n))-1])
    masa=(1-alpha)*n
    completos=int(np.floor(masa+1e-12))
    fraccion=masa-completos
    suma=float(x[n-completos:].sum()) if completos else 0.
    if fraccion>1e-12:
        suma+=fraccion*x[n-completos-1]
    return var,suma/masa

def riesgo_normal(mu, sigma, alpha):
    if not np.isfinite([mu,sigma,alpha]).all() or sigma<=0 or not 0<alpha<1:
        raise ValueError('Parámetros inválidos')
    z=norm.ppf(alpha)
    return mu+sigma*z,mu+sigma*norm.pdf(z)/(1-alpha)

def riesgo_t(mu, escala, nu, alpha):
    if not np.isfinite([mu,escala,nu,alpha]).all() or escala<=0 or nu<=1 or not 0<alpha<1:
        raise ValueError('Parámetros inválidos')
    q=t.ppf(alpha,nu)
    return mu+escala*q,mu+escala*(nu+q*q)*t.pdf(q,nu)/((nu-1)*(1-alpha))

print('Normal, millón: VaR y ES',riesgo_normal(0,1,.99))
escenarios=np.r_[np.zeros(9216),np.ones(768),np.full(16,2)]
print('Dos bonos:',var_es(escenarios,.95))
print('t5, escala unidad: VaR y ES',riesgo_t(0,1,5,.99))
[ ]Age-weighted scenariosBrowser
def var_es_ponderado(losses, weights, alpha):
    x=np.asarray(losses,dtype=float); p=np.asarray(weights,dtype=float)
    if (x.ndim!=1 or p.shape!=x.shape or len(x)==0 or not np.isfinite(x).all()
            or not np.isfinite(p).all() or np.any(p<0) or p.sum()<=0 or not 0<alpha<1):
        raise ValueError('Escenarios, pesos o nivel inválidos')
    p=p/p.sum(); orden=np.argsort(x); x=x[orden]; p=p[orden]
    q=float(x[np.searchsorted(np.cumsum(p),alpha,side='left')])
    restante=1-alpha; suma=0.
    for valor,masa in zip(x[::-1],p[::-1]):
        tomar=min(restante,masa)
        suma+=tomar*valor; restante-=tomar
        if restante<=1e-14: break
    return q,suma/(1-alpha)

perdidas=np.array([3.,0.,1.,0.,2.])
lambda_=0.8
pesos_antiguedad=lambda_**np.arange(len(perdidas)-1,-1,-1)
pesos_antiguedad=pesos_antiguedad/pesos_antiguedad.sum()
print('Iguales:',var_es(perdidas,.8))
print('Recientes más pesados:',var_es_ponderado(perdidas,pesos_antiguedad,.8))
print('Tamaño efectivo:',1/np.sum(pesos_antiguedad**2))

The losses in this example are hypothetical data from five periods ordered oldest to newest; the extreme value is the oldest. Effective size summarizes weight concentration, not a replacement for the number of independent observations or a quantification of quantile error by itself.

Filter and estimate

The following fit uses normal quasi-likelihood on portfolio return with positivity and persistence-below-one constraints. The training sample is not out-of-sample evaluation. The optimizer can fail or reach a boundary; we do not hide it. Returns are expressed in percent for numerical scaling and converted back to original units on return. This version estimates GARCH on the linear portfolio, not a multivariate factor model for repricing options.

The function minimizes, up to constants, ∑t(log⁡ht+ϵt2/ht)\sum_t(\log h_t+\epsilon_t^2/h_t). This is a quasi-likelihood when innovations are not normal; its interpretation requires further conditions and parameter uncertainty is absent from the point forecast. Initial variance is mean squared training residual. When forecasting the next date, the filter uses the last already observed residual, never the return it predicts. To evaluate a sequence, repeat the fit or update at each date using a past window and compare each subsequent loss with its prior forecast.

[ ]FHS with estimated GARCHBrowser
from scipy.optimize import minimize

def ajustar_garch(x):
    x=np.asarray(x,dtype=float)
    if x.ndim!=1 or len(x)<40 or not np.isfinite(x).all() or x.std()==0:
        raise ValueError('Se necesitan al menos 40 rendimientos finitos con variación')
    mu=float(x.mean()); e=(x-mu)*100
    var=float(np.mean(e*e))
    def filtrar(theta):
        omega,a,b=theta
        h=np.empty(len(e)); h[0]=var
        for i in range(1,len(e)):
            h[i]=omega+a*e[i-1]**2+b*h[i-1]
        return h
    def objetivo(theta):
        h=filtrar(theta)
        return float(np.sum(np.log(h)+e*e/h))
    ajuste=minimize(objetivo,[var*.05,.08,.87],method='SLSQP',
        bounds=[(var*1e-7,var*10),(.000001,.999),(.000001,.999)],
        constraints=[{'type':'ineq','fun':lambda p:.999-p[1]-p[2]}],
        options={'maxiter':250,'ftol':1e-8})
    if not ajuste.success:
        raise RuntimeError('GARCH no convergió: '+ajuste.message)
    h=filtrar(ajuste.x)
    omega,a,b=ajuste.x
    proxima=omega+a*e[-1]**2+b*h[-1]
    return mu, e/np.sqrt(h), np.sqrt(proxima)/100, ajuste.x

def fhs_var_es(returns, weights, alpha):
    r=np.asarray(returns,dtype=float); w=np.asarray(weights,dtype=float)
    if r.ndim!=2 or w.ndim!=1 or r.shape[1]!=len(w) or not np.isfinite(w).all():
        raise ValueError('Dimensiones incompatibles')
    mu,z,sigma,parametros=ajustar_garch(r@w)
    return var_es(-(mu+sigma*z),alpha),parametros

rng=np.random.default_rng(281703)
datos=rng.normal(size=(450,2))*np.array([.012,.018])
estimacion,parametros=fhs_var_es(datos,[.6,.4],.95)
print('FHS: VaR, ES',estimacion)
print('GARCH omega, a, b (escala porcentual):',parametros)
print('Persistencia:',parametros[1]+parametros[2])

The next experiment reuses the current m28-l01 generator: its returns are logarithmic and converted to simple returns before constructing the portfolio. Output describes one synthetic sample, not an estimate of a real market. As that lesson explains, an untruncated Student-t log return has no finite positive exponential moment. Do not treat the sample mean of simulated simple returns as a stable estimate of a finite model expectation.

[ ]Apply FHS to the module generatorBrowser
def mercado_sintetico(n, caminos=1, semilla=280101, burn=1000,
                      mu=.0002, var_base=.0001, alpha=.055,
                      beta=.75, gamma=.2, nu=8., intensidad=.01,
                      media_salto=0., escala_salto=.025):
    """Rendimientos logarítmicos con mecanismos explícitos y semillas fijas."""
    if (not isinstance(n, int) or not isinstance(caminos, int)
            or not isinstance(burn, int) or n < 1 or caminos < 1 or burn < 0):
        raise ValueError('Dimensiones y burn deben ser enteros válidos')
    valores = (mu,var_base,alpha,beta,gamma,nu,intensidad,media_salto,escala_salto)
    if not np.isfinite(valores).all() or min(alpha,beta,gamma,intensidad,escala_salto)<0:
        raise ValueError('Parámetros no finitos o negativos')
    persistencia=alpha+beta+gamma/2
    if var_base<=0 or nu<=2 or persistencia>=1:
        raise ValueError('Se necesita varianza positiva, nu>2 y persistencia<1')
    omega=var_base*(1-persistencia)
    transicion=np.array([[.985,.015],[.05,.95]])
    multiplicadores=np.array([.75,1.5])
    rng=np.random.default_rng(semilla)
    forma=(n+burn,caminos)
    uniformes=rng.random(forma)
    innovaciones=rng.standard_t(nu,size=forma)*np.sqrt((nu-2)/nu)
    cuentas=rng.poisson(intensidad,size=forma)
    saltos_generados=(cuentas*media_salto+
                       np.sqrt(cuentas)*escala_salto*rng.normal(size=forma))
    varianza=np.full(caminos,var_base)
    anterior=np.zeros(caminos)
    estado=np.zeros(caminos,dtype=int)
    rend=np.empty((n,caminos))
    volatilidad=np.empty_like(rend)
    regimen=np.empty((n,caminos),dtype=int)
    saltos=np.empty_like(rend)
    for instante in range(n+burn):
        varianza=omega+(alpha+gamma*(anterior<0))*anterior**2+beta*varianza
        estado=(uniformes[instante]<transicion[estado,1]).astype(int)
        innovacion=np.sqrt(varianza)*innovaciones[instante]
        salto=saltos_generados[instante]
        if instante>=burn:
            indice=instante-burn
            rend[indice]=mu+multiplicadores[estado]*innovacion+salto
            volatilidad[indice]=np.sqrt(varianza)
            regimen[indice]=estado
            saltos[indice]=salto
        anterior=innovacion
    return {'r':rend,'sigma_base':volatilidad,'regimen':regimen,
            'salto':saltos,'transicion':transicion,'omega':omega,
            'persistencia':persistencia,'nu':nu}

generado=mercado_sintetico(500,caminos=2,semilla=281705,burn=200)
r_sim=np.expm1(generado['r'])
resultado_sim,param_sim=fhs_var_es(r_sim,[.6,.4],.95)
print('FHS del generador: VaR y ES',resultado_sim)
print('Parámetros GARCH:',param_sim)

For public factors use the daily file downloaded from the French library, recording download date and version. Mkt-RF is market excess and RF a daily rate, both in percent: simple market return is (Mkt-RF + RF)/100. The cell reproduces m28-l01’s literal excerpt from January 2 to April 30, 2024, accessed November 2, 2026. The version is retrospective and does not establish historical availability. We fit the whole window only to illustrate estimators; this is not a backtest. With so few days the tail is highly uncertain. For a real forecast load the full file, check dates and select only the window available before the decision date.

[ ]A public excerpt and its unitsBrowser
import csv, io
extracto=''',Mkt-RF,SMB,HML,RF
20240102,   -0.70,   -0.55,    0.79,    0.02
20240103,   -1.01,   -1.94,   -0.10,    0.02
20240104,   -0.33,    0.21,    0.09,    0.02
20240105,    0.15,   -0.81,    0.63,    0.02
20240108,    1.49,    0.90,   -1.27,    0.02
20240109,   -0.21,   -0.44,   -0.89,    0.02
20240110,    0.51,   -0.10,   -0.44,    0.02
20240111,   -0.14,   -0.45,   -0.51,    0.02
20240112,   -0.01,   -0.10,   -0.48,    0.02
20240116,   -0.47,   -0.76,   -0.61,    0.02
20240117,   -0.59,   -0.08,   -0.24,    0.02
20240118,    0.87,   -0.10,   -0.35,    0.02
20240119,    1.19,   -0.47,    0.67,    0.02
20240122,    0.38,    1.74,    0.58,    0.02
20240123,    0.22,   -0.65,   -0.55,    0.02
20240124,   -0.01,   -0.74,    0.06,    0.02
20240125,    0.46,    0.04,    0.57,    0.02
20240126,   -0.02,    0.41,   -0.28,    0.02
20240129,    0.85,    1.07,   -0.58,    0.02
20240130,   -0.12,   -1.27,    0.85,    0.02
20240131,   -1.74,   -0.92,   -0.29,    0.02
20240201,    1.22,    0.63,   -1.35,    0.02
20240202,    0.99,   -1.43,   -0.51,    0.02
20240205,   -0.42,   -0.73,   -0.66,    0.02
20240206,    0.27,    0.85,   -0.47,    0.02
20240207,    0.77,   -0.90,   -0.61,    0.02
20240208,    0.21,    1.49,    0.02,    0.02
20240209,    0.65,    1.00,   -0.42,    0.02
20240212,    0.04,    1.29,    1.11,    0.02
20240213,   -1.60,   -2.41,   -0.65,    0.02
20240214,    1.14,    1.57,   -0.22,    0.02
20240215,    0.67,    0.85,    1.04,    0.02
20240216,   -0.53,   -0.66,   -0.18,    0.02
20240220,   -0.73,   -0.87,    0.33,    0.02
20240221,   -0.02,   -0.82,    0.14,    0.02
20240222,    2.02,   -1.20,   -1.29,    0.02
20240223,    0.02,    0.28,    0.00,    0.02
20240226,   -0.26,    1.00,   -0.12,    0.02
20240227,    0.26,    1.20,   -0.44,    0.02
20240228,   -0.26,   -0.86,   -0.01,    0.02
20240229,    0.53,   -0.36,    0.98,    0.02
20240301,    0.76,    0.09,   -0.55,    0.02
20240304,   -0.18,   -0.79,    0.34,    0.02
20240305,   -1.07,   -0.32,    1.17,    0.02
20240306,    0.53,   -0.16,   -0.03,    0.02
20240307,    1.02,   -0.47,    0.03,    0.02
20240308,   -0.66,    0.50,    0.57,    0.02
20240311,   -0.20,   -0.72,    0.40,    0.02
20240312,    1.04,   -0.97,   -0.68,    0.02
20240313,   -0.14,    0.30,   -0.02,    0.02
20240314,   -0.42,   -1.31,   -1.04,    0.02
20240315,   -0.58,    0.75,    0.79,    0.02
20240318,    0.53,   -1.02,   -0.25,    0.02
20240319,    0.54,    0.53,   -0.27,    0.02
20240320,    1.02,    0.90,    1.01,    0.02
20240321,    0.42,    0.05,    0.95,    0.02
20240322,   -0.23,   -0.86,   -0.53,    0.02
20240325,   -0.27,   -0.24,    0.86,    0.02
20240326,   -0.26,    0.09,   -0.13,    0.02
20240327,    0.88,    1.04,    0.91,    0.02
20240328,    0.11,    0.29,    0.48,    0.02
20240401,   -0.26,   -0.89,   -0.28,    0.02
20240402,   -0.85,   -1.10,    0.04,    0.02
20240403,    0.17,    0.31,   -0.03,    0.02
20240404,   -1.22,    0.16,    0.15,    0.02
20240405,    1.06,   -0.32,   -0.68,    0.02
20240408,    0.01,    0.52,    0.14,    0.02
20240409,    0.13,    0.37,   -0.32,    0.02
20240410,   -1.00,   -1.37,   -1.04,    0.02
20240411,    0.73,    0.24,   -0.62,    0.02
20240412,   -1.53,   -0.33,    0.11,    0.02
20240415,   -1.29,   -0.48,    0.76,    0.02
20240416,   -0.23,   -0.03,   -0.82,    0.02
20240417,   -0.64,   -0.49,    0.56,    0.02
20240418,   -0.27,   -0.28,    0.87,    0.02
20240419,   -0.82,    0.82,    1.90,    0.02
20240422,    0.87,   -0.21,    0.54,    0.02
20240423,    1.27,    0.59,    0.00,    0.02
20240424,   -0.01,   -0.31,    0.28,    0.02
20240425,   -0.47,   -0.31,   -0.20,    0.02
20240426,    1.03,    0.46,   -1.07,    0.02
20240429,    0.33,    0.38,   -0.48,    0.02
20240430,   -1.67,   -0.19,   -0.25,    0.02'''
filas=list(csv.DictReader(io.StringIO(extracto)))
mercado=np.array([(float(f['Mkt-RF'])+float(f['RF']))/100 for f in filas])
print('Rendimientos simples de mercado:',mercado)
print('Número de sesiones:',len(mercado))
print('VaR y ES históricos al 95 %:',var_es(-mercado,.95))
estimacion_publica,param_publico=fhs_var_es(mercado[:,None],[1.],.95)
print('FHS al 95 %:',estimacion_publica,'| parámetros:',param_publico)

In this run the squared-innovation coefficient reaches the optimizer’s imposed lower bound. The fit is nearly constant-volatility and the two risk figures are very similar; this reflects the window and constraints, not evidence of constant market volatility. A short window, parameters near the boundary and lack of out-of-sample checking prevent treating this fit as an operational risk system.

Euler components with scenarios

If there are no ties at the threshold, the same fraction of the boundary scenario applies to each component. In this sample contributions sum exactly to empirical ES. Finite differences are compared only when sufficiently small perturbations do not change scenario order.

[ ]Tail contributions and finite differencesBrowser
def euler_es(escenarios, pesos, alpha):
    x=np.asarray(escenarios,dtype=float); w=np.asarray(pesos,dtype=float)
    if x.ndim!=2 or w.shape!=(x.shape[1],) or not np.isfinite(x).all() or not np.isfinite(w).all() or not 0<alpha<1:
        raise ValueError('Entradas incompatibles')
    total=x@w
    orden=np.argsort(total)[::-1]
    masa=(1-alpha)*len(total)
    coef=np.clip(masa-np.arange(len(total)),0,1)/masa
    return w*(coef@x[orden])

riesgos=-datos
pesos=np.array([.6,.4]); alpha=.95
aportacion=euler_es(riesgos,pesos,alpha)
paso=1e-6
diferencias=[]
for i in range(len(pesos)):
    eje=np.zeros_like(pesos); eje[i]=paso
    diferencias.append(pesos[i]*(var_es(riesgos@(pesos+eje),alpha)[1]-var_es(riesgos@(pesos-eje),alpha)[1])/(2*paso))
print('ES total:',var_es(riesgos@pesos,alpha)[1])
print('Contribuciones de cola:',aportacion,'| suma:',sum(aportacion))
print('Diferencias finitas:',diferencias)

Reprice an option in Monte Carlo

Here the model uses a lognormal asset with fixed volatility and zero rate, a short call and a one-day horizon. Current and future prices use Black-Scholes; this is full repricing only within that fixed-volatility and fixed-rate model. It excludes smiles, jumps and volatility changes. Delta-gamma is calculated initially and omits theta, so the difference includes passage of time as well as Taylor remainder in underlying movement.

[ ]Short call: repricing and delta-gammaBrowser
from scipy.special import ndtr

def call_bs(s,k,t,sigma):
    s=np.asarray(s,dtype=float)
    if t<=0:
        return np.maximum(s-k,0.)
    d1=(np.log(s/k)+.5*sigma**2*t)/(sigma*np.sqrt(t))
    return s*ndtr(d1)-k*ndtr(d1-sigma*np.sqrt(t))

s=k=100.; sigma=.3; plazo=10/252; dt=1/252
d1=.5*sigma*np.sqrt(plazo)
delta=ndtr(d1); gamma=norm.pdf(d1)/(s*sigma*np.sqrt(plazo))
rng_op=np.random.default_rng(281704)
sn=s*np.exp(-.5*sigma**2*dt+sigma*np.sqrt(dt)*rng_op.normal(size=30000))
ds=sn-s
perdida_call=call_bs(sn,k,plazo-dt,sigma)-call_bs(s,k,plazo,sigma)
perdida_dg=delta*ds+.5*gamma*ds**2
print('VaR y ES, call corta revalorada:',var_es(perdida_call,.99))
print('VaR y ES, delta-gamma sin theta:',var_es(perdida_dg,.99))
print('Media de error absoluto:',np.mean(np.abs(perdida_call-perdida_dg)))

Sampling has Monte Carlo error. Repeat with different seeds and sizes before attributing small differences to the method. For portfolios with multiple factors, simulate them jointly and revalue each instrument with its respective variables.

Exercises

NumericThe normal threshold
A normal loss has zero mean and standard deviation 1 million. Calculate its 99% VaR in millions.
NumericInside the tail
For the same normal loss with zero mean and standard deviation 1 million, calculate 99% ES in millions.
ProofES subadditivity
Prove: Use the dual representation of ES to prove subadditivity for integrable losses.
The proof will appear here as you work.

Step 1 of 2. Which set of densities is used for L and M?

ProofSum contributions
Prove: Let ρ be differentiable and homogeneous of degree one. Prove Euler's formula.
The proof will appear here as you work.

Step 1 of 2. What identity holds for positive t?

QuizTen days
Why can multiplying daily VaR by √10 fail when volatility clusters?
CodeFilter a portfolio
Implement fhs_var_es(returns, weights, alpha). Returns is a date-by-asset return matrix; weights are fixed exposures. Fit stationary GARCH(1,1) by normal quasi-likelihood to centered portfolio returns, standardize innovations by each date's volatility, rescale with the next forecast and return empirical loss VaR and ES. Use the lab initializer, bounds and tolerance. Reject nonfinite input, wrong dimensions, invalid level, fewer than 40 dates or zero variance. ES must include fractional mass.
def fhs_var_es(returns, weights, alpha):
  raise NotImplementedError()
Shift+Enter to run

What to retain

Key idea
VaR identifies a loss threshold; ES averages the full tail with correct treatment of mass at the threshold. Neither replaces model specification and validation.

The parametric distribution reduces the problem to parameters and can extrapolate beyond data, at the cost of its assumptions. Historical simulation retains observed scenarios but cannot invent crises absent from the window. Filtered simulation adapts scale to forecast volatility and depends on stability of residuals and filter. Monte Carlo can construct dependence and reprice nonlinear positions, but needs a factor model and enough tail scenarios. For all four, compare forecasts with later losses, examine uncertainty and supplement with stress scenarios.

Euler allocation explains how positions contribute to the joint portfolio tail. It attributes observed risk under a model and weights, not a guarantee that each position will behave the same way in the next crisis.