Module contents
Lesson 18 of 30Advanced 105 min

Extreme tails, risk model backtesting and stress testing

Estimate extreme tails, backtest risk forecasts, compare VaR-ES predictions and optimize CVaR under scenarios.

After this lesson you can

  • Fit generalized Pareto excesses and estimate extreme VaR and ES with intervals.
  • Estimate the tail index with Hill and select thresholds using residual-life and stability diagnostics.
  • Implement Kupiec and Christoffersen tests and study power by simulation.
  • Explain elicitability and compare joint VaR-ES forecasts with scoring functions.
  • Formulate CVaR minimization as a linear program and design coherent stress scenarios.

Before you start

Few data where they matter most

A 99% ES summarizes the least observed part of the loss distribution. Fitting a distribution to the whole sample can represent the center well and the tail poorly. Extreme-value theory focuses the model on large observations, but does not remove the tradeoff: lowering the threshold adds data and raises bias risk; raising it reduces observations and increases uncertainty.

InteractiveThreshold, bias and scarcity

The 3,000 simulated losses use a fixed seed. The mixture is 80% uniform between 0 and 1, and 20% Pareto above 1 with tail index 0.4. The estimator averages log losses relative to a fixed threshold. The normal interval is meaningful when the Pareto approximation is good and there are enough exceedances.

1.00
Exceedances611
Pareto tail index0.421
Approximate normal interval0.388 to 0.455
99.9% extrapolated VaR9.39
Move the threshold from the body to the tail. Compare the estimated index with true value 0.4 and observe how many exceedances remain.

Maxima and exceedances

Block maxima fit a generalized extreme-value distribution (GEV) to maxima of sufficiently large blocks. Peaks over threshold (POT) uses all excesses Y=L−uY=L-u conditional on L>uL>u.

For normalized maxima, the limiting GEV family has distribution H(x)=exp⁡{−[1+ξ(x−μ)/σ]−1/ξ}H(x)=\exp\{-[1+\xi(x-\mu)/\sigma]^{-1/\xi}\} on its support, with σ>0\sigma>0 and 1+ξ(x−μ)/σ>01+\xi(x-\mu)/\sigma>0. The case ξ=0\xi=0 is the Gumbel limit, H(x)=exp⁡[−e−(x−μ)/σ]H(x)=\exp[-e^{-(x-\mu)/\sigma}]; ξ>0\xi>0 corresponds to a Fréchet-type tail and ξ<0\xi<0 to a finite Weibull-type upper endpoint. Convergence requires normalization and conditions on distribution and dependence, not merely large blocks. POT often uses more observations, though threshold choice introduces another tradeoff.

Under domain-of-attraction conditions and for high thresholds, the conditional excess distribution is approximated by the generalized Pareto (GPD):

Gξ,β(y)=1−(1+ξy/β)−1/ξ,y≥0,1+ξy/β>0,β>0.G_{\xi,\beta}(y)=1-\left(1+\xi y/\beta\right)^{-1/\xi},\quad y\ge0,\quad 1+\xi y/\beta>0,\quad \beta>0.

When ξ=0\xi=0 take the exponential limit 1−e−y/β1-e^{-y/\beta}. If ξ<0\xi<0 the tail has finite upper endpoint u−β/ξu-\beta/\xi; if ξ>0\xi>0 it is Pareto-like; if ξ≥1\xi\ge1 the model’s tail mean is not finite. The approximation is asymptotic and does not claim a GPD exactly describes every finite exceedance. Temporal dependence can invalidate intervals assuming independence.

With pu=P(L>u)p_u=\Pr(L>u) and α>1−pu\alpha>1-p_u, the approximation P(L>x)≈pu[1+ξ(x−u)/β]−1/ξ\Pr(L>x)\approx p_u[1+\xi(x-u)/\beta]^{-1/\xi} gives

qα≈u+βξ[(pu1−α)ξ−1],ES⁡α≈qα+β−ξu1−ξ(ξ<1).q_\alpha\approx u+\frac{\beta}{\xi}\left[\left(\frac{p_u}{1-\alpha}\right)^\xi-1\right],\qquad \operatorname{ES}_\alpha\approx\frac{q_\alpha+\beta-\xi u}{1-\xi}\quad(\xi<1).

For ξ=0\xi=0, qα=u+βlog⁡[pu/(1−α)]q_\alpha=u+\beta\log[p_u/(1-\alpha)] and ES⁡=qα+β\operatorname{ES}=q_\alpha+\beta. In data, estimate pup_u by the exceedance proportion and ξ,β\xi,\beta by maximum likelihood with the support constraint for each observation. Extrapolating to 99.9% with few exceedances can produce very wide intervals; uncertainty includes parameters and the exceedance rate.

The quantile formula follows by equating survival to 1−α1-\alpha and solving for qαq_\alpha. For ES, threshold stability gives scale β+ξ(qα−u)\beta+\xi(q_\alpha-u) at the new threshold; when ξ<1\xi<1, mean excess is that scale divided by 1−ξ1-\xi. Adding it to qαq_\alpha gives the expression above. If ξ≥1\xi\ge1, a finite sum of observations is not evidence that theoretical model ES is finite.

The mean residual-life plot shows e(u)=E[L−u∣L>u]e(u)=\E[L-u\mid L>u]. For a GPD valid from u0u_0 and ξ<1\xi<1, e(u)=[βu0+ξ(u−u0)]/(1−ξ)e(u)=[\beta_{u_0}+\xi(u-u_0)]/(1-\xi) for u≥u0u\ge u_0. Look for an approximately linear region alongside stability of tail index and quantiles. GPD scale changes with threshold, βu=βu0+ξ(u−u0)\beta_u=\beta_{u_0}+\xi(u-u_0), so requiring raw scale to be constant would be an incorrect diagnostic.

Hill and conditional risk

For ordered positive losses L(1)≤⋯≤L(n)L_{(1)}\le\cdots\le L_{(n)}, the Hill estimator with kk upper observations is

ξ^k=1k∑j=1klog⁡L(n−j+1)L(n−k).\widehat\xi_k=\frac1k\sum_{j=1}^k\log\frac{L_{(n-j+1)}}{L_{(n-k)}}.

If the tail is exactly Pareto with P(L>x)=(xm/x)1/ξ\Pr(L>x)=(x_m/x)^{1/\xi}, the log ratio above a tail threshold is exponential with mean ξ\xi. Hill averages those logarithms. For regularly varying tails, consistency requires an intermediate sequence k→∞k\to\infty and k/n→0k/n\to0, plus tail assumptions. A Hill plot against kk helps seek stability, but a flat stretch alone does not prove the threshold correct. The normal approximation with standard error ξ^/k\widehat\xi/\sqrt{k} is an asymptotic diagnostic, not an exact interval for arbitrary samples or thresholds chosen after viewing data.

The first figure uses the Pareto estimator with fixed threshold uu: it averages log⁡(Li/u)\log(L_i/u) over losses exceeding it. Hill instead uses the ordered observation immediately below the largest kk as threshold. These are related but need not be identical in a finite sample; the lab cell implements Hill’s formula with order statistics.

GARCH-EVT first filters volatility, fits the tail of standardized residuals and scales the resulting quantile by forecast volatility. McNeil and Frey combine GARCH quasi-likelihood and EVT to estimate conditional quantiles and ES. The m28-l17 fit uses only past information; if residuals retain dependence, uncertainty analysis must address it. Adding EVT does not fix a misspecified filter.

How many exceptions, and when?

VaR backtesting compares each forecast qtq_t issued before observing LtL_t with It=1{Lt>qt}I_t=\mathbf1_{\{L_t>q_t\}}. With a continuous conditional distribution and correct VaR at level α\alpha, conditional exception probability is p=1−αp=1-\alpha. For distributions with atoms, the strict rule can produce fewer exceptions than pp; state the convention.

Kupiec tests unconditional coverage with a Bernoulli likelihood ratio, comparing pp with p^=k/n\hat p=k/n. Christoffersen compares exception probability after a non-exception with that after an exception using a first-order Markov alternative. Its conditional-coverage test adds coverage and independence statistics under the same sample convention. A first-order test does not detect every form of dependence. Asymptotic chi-square limits may be poor with few exceptions; null simulation or an exact test may be preferable.

For coverage, if ℓ(p)=klog⁡p+(n−k)log⁡(1−p)\ell(p)=k\log p+(n-k)\log(1-p), the statistic is LRuc=2[ℓ(k/n)−ℓ(p)]LR_{uc}=2[\ell(k/n)-\ell(p)]. Under the independent Bernoulli null and asymptotic conditions it is compared with χ12\chi^2_1. The Bernoulli assumption affects the reference distribution: if exceptions cluster, correct marginal frequency does not guarantee nominal size for the Kupiec p-value. In the transition table, the independence test compares likelihood under a common exception probability against two probabilities, one per previous state. Combined statistic LRcc=LRuc+LRindLR_{cc}=LR_{uc}+LR_{ind} is commonly compared with χ22\chi^2_2 under the null and test conditions. Document treatment of the first observation and do not blindly trust limits with empty cells.

InteractiveCoverage and clustering

The 500 normal innovations use seed 281806 to show how the tests can disagree. Other samples can differ. In the second half the control multiplies the standard deviation. Fixed VaR is the quantile of the equal-weight mixture, while filtered VaR knows each regime's scale. Fixed-VaR exceptions are independent and have different probabilities in the two halves. The test for stationary independence can reject them. Both tests are asymptotic, and the filter uses oracle information.

Fixed VaR

Filtered VaR

3.00
Fixed: exceptions23 / 500
Fixed: coverage / independence p-values0.678 / 0.018
Filtered: exceptions24 / 500
Filtered: coverage / independence p-values0.836 / 0.878
Increase the regime change. Is counting exceptions enough to see they concentrate in the second half?

In this figure the regime change occurs at a fixed date and innovations are independent. Therefore even fixed-VaR exceptions are independent across dates, though their probabilities differ: they concentrate in the second half. The Christoffersen null is an independent Bernoulli sequence with constant probability, and rejection alone does not identify dependence versus regime change. The later power simulation uses a Markov chain with genuine dependence to study another alternative.

The historical Basel traffic light for 250 observations and 99% VaR classifies 0 to 4 exceptions green, 5 to 9 yellow and 10 or more red (1996 Committee document). It is a supervisory rule with defined horizon, period and conventions, not a universal test for every sample or level. A large p-value does not prove the model correct: power can be low with few events.

Forecasts, scores and stress

A functional is elicitable if a strictly consistent score exists: its expectation has the functional’s true value as its unique minimum for every distribution in a declared class. When a quantile is unique, quantile loss elicits it. ES alone is not elicitable on broad distribution classes, but the pair (VaR, ES) admits strictly consistent scores under appropriate assumptions (Fissler, Ziegel and Gneiting). This allows comparing joint forecasts by mean out-of-sample score, with uncertainty accounting for dependence. It does not make ES impossible to validate: specific calibration tests exist, including Acerbi and Szekely, each requiring its own assumptions and data.

One idea compares the sum of realized exception losses with predicted ES and nominal exception probability. If qtq_t and et>0e_t>0 are conditional loss VaR and ES, and p=1−αp=1-\alpha, calibration statistic Z2=1−[np]−1∑tLt1{Lt>qt}/etZ_2=1-[np]^{-1}\sum_t L_t\mathbf1_{\{L_t>q_t\}}/e_t has expectation zero under correct forecasts and continuous distributions when expectations exist. A negative result indicates tail losses greater than predicted under this convention. The statistic’s distribution depends on the process and tail distributions: comparing it with zero alone does not yield a valid p-value. Its test version requires appropriate reference calibration; joint scoring answers a different question, relative comparison of two forecasts.

A stress test calculates the effect of coherent historical or hypothetical scenarios on current positions. Reverse stress starts from a loss or breach and seeks scenarios producing it. State horizon, liquidity, factor relationships, valuation and mitigation measures. Do not assign precise probabilities to a hypothetical scenario without a model justifying them; stress loss is neither VaR nor a prediction.

A historical scenario reproduces observed movements but applies them to a different current portfolio and environment. A hypothetical scenario may combine, for example, an equity decline, implied-volatility jump and liquidity deterioration. Describe how they move jointly and reprice options with affected variables; selecting each extreme movement separately does not automatically make their combination coherent. In reverse stress, objective and constraints define what is plausible: an insolvency boundary may be reached in many ways, and the closest under a metric is not necessarily most likely.

Optimizing ES

For integrable loss, Rockafellar and Uryasev represent CVaR or ES as

ES⁡α(L)=min⁡t[t+11−αE(L−t)+].\operatorname{ES}_\alpha(L)=\min_t\left[t+\frac{1}{1-\alpha}\E(L-t)^+\right].

The minimum is attained at an α\alpha quantile, though several minimizers may exist. With nn return scenarios rj\vb{r}_j, loss −w⊤rj-\vb{w}\T\vb{r}_j, variables zj≥0z_j\ge0 and linear portfolio constraints, impose zj≥−w⊤rj−tz_j\ge-\vb{w}\T\vb{r}_j-t and minimize t+∑jzj/[n(1−α)]t+\sum_j z_j/[n(1-\alpha)]. The problem is linear in w,t,z\vb{w},t,\vb{z}. The optimized portfolio depends on constraints and scenarios, and solving the program does not guarantee out-of-sample risk.

InteractiveTwo criteria, same scenarios

The long-only grid uses unleveraged weights in 5% steps and 500 equally likely scenarios. Seed 281810 illustrates how the criteria can differ. Other samples can give a different answer. The safe asset returns 0.02%. Market returns are normal with mean 0.15% and standard deviation 1.2%. The hypothetical short option returns 0.3% minus 16% on an independent Bernoulli event with probability 1%. These are synthetic assumptions. ES is at 95%.

  • Minimize standard deviation
  • Minimize ES
0.10 %
Minimum-variance weights: safe / market / option short25 / 35 / 40
Minimum-ES weights: safe / market / option short15 / 75 / 10
ES of minimum-variance portfolio (%)1.802
Minimum ES (%)1.705
Change minimum return and compare ES and weights of the minimum-variance and minimum-ES portfolios.

Lab: estimate and check a tail

The sample combines a uniform body and an exact Pareto tail from 1. We know the mechanism, so we can check the estimator without presenting figures as market data. The GPD density for ξ≠0\xi\ne0 is f(y)=β−1(1+ξy/β)−1/ξ−1f(y)=\beta^{-1}(1+\xi y/\beta)^{-1/\xi-1} on its support. Optimize log scale to keep it positive and reject parameters outside support. Compare with SciPy’s implementation fixing location at zero.

[ ]Pareto, Hill and GPD from likelihoodBrowser
import numpy as np
from scipy.optimize import minimize
from scipy.stats import genpareto, chi2, norm

rng=np.random.default_rng(281804)
n=3000
cola=rng.random(n)<.2
perdidas=np.where(cola,(1-rng.random(n))**(-.4),rng.random(n))

def hill(x,k):
    x=np.sort(np.asarray(x,dtype=float))
    if x.ndim!=1 or not np.isfinite(x).all() or not 1<=k<len(x) or x[-k-1]<=0:
        raise ValueError('Se requieren datos positivos en la cola y k válido')
    return float(np.mean(np.log(x[-k:]/x[-k-1])))

def ajustar_gpd(excesos):
    y=np.asarray(excesos,dtype=float)
    if y.ndim!=1 or len(y)<20 or not np.isfinite(y).all() or np.any(y<0) or y.mean()<=0:
        raise ValueError('Excesos inválidos')
    def nll(theta):
        xi,logb=theta; beta=np.exp(logb); soporte=1+xi*y/beta
        if np.any(soporte<=0): return 1e100
        if abs(xi)<1e-6: return len(y)*logb+y.sum()/beta
        return len(y)*logb+(1+1/xi)*np.log1p(xi*y/beta).sum()
    result=minimize(nll,[.1,np.log(y.mean())],method='Nelder-Mead',
                    options={'maxiter':1500,'xatol':1e-8,'fatol':1e-8})
    if not result.success: raise RuntimeError(result.message)
    return float(result.x[0]),float(np.exp(result.x[1]))

u=1.; excesos=perdidas[perdidas>u]-u
xi,beta=ajustar_gpd(excesos)
xi_s,loc_s,beta_s=genpareto.fit(excesos,floc=0)
print('Excesos:',len(excesos),'| Hill:',hill(perdidas,len(excesos)))
print('GPD propia:',xi,beta,'| SciPy:',xi_s,beta_s)
print('Valores teóricos en u=1: xi=0.4, beta=0.4')

The integration limit depends on support. If the optimizer converges to a suspicious endpoint or inadmissible region, change threshold and initial conditions and inspect the fit rather than blindly accepting a result. Comparing two implementations does not prove the model describes the future distribution.

[ ]Extrapolate VaR and ESBrowser
def pot_var_es(u, pu, xi, beta, alpha):
    if not np.isfinite([u,pu,xi,beta,alpha]).all() or beta<=0 or not 0<pu<=1 or not 0<alpha<1 or 1-alpha>=pu:
        raise ValueError('Nivel o parámetros incompatibles con el umbral')
    ratio=pu/(1-alpha)
    q=u+beta*np.log(ratio) if abs(xi)<1e-8 else u+beta*np.expm1(xi*np.log(ratio))/xi
    es=(q+beta-xi*u)/(1-xi) if xi<1 else np.inf
    return float(q),float(es)

print('Estimación POT 99.9 %:',pot_var_es(u,len(excesos)/n,xi,beta,.999))
print('Modelo verdadero 99.9 %:',pot_var_es(1,.2,.4,.4,.999))
print('Ejercicio GPD 99 %:',pot_var_es(2,.05,.25,.6,.99))

The next interval is Hill’s for an exact Pareto tail and fixed number of exceedances. It is not a general interval for the GPD or extrapolated VaR. A VaR interval must also propagate rate uncertainty and threshold selection; bootstrapping the full series is appropriate only under independence, or with a block scheme under dependence.

[ ]Hill asymptotic uncertaintyBrowser
k=len(excesos); h=hill(perdidas,k); se=h/np.sqrt(k)
print('Hill e intervalo aproximado:',h,(h-1.96*se,h+1.96*se))
for umbral in (.5,1.,1.5,2.):
    y=perdidas[perdidas>umbral]-umbral
    print('Umbral:',umbral,'| excesos:',len(y),'| vida media residual:',y.mean())

To illustrate a VaR and ES interval, resample the full independent sample with threshold fixed at 1 and refit both exceedance rate and GPD. There are 100 replicates, split into five browser cells. The percentile interval is noisy with so few replicates, excludes threshold choice and is not automatically valid for a dependent financial series. In real work increase replicates and study sensitivity and coverage.

[ ]Bootstrap, block 1Browser
rng_boot=np.random.default_rng(281809)
replicas=[]
def bloque_bootstrap(cantidad):
    for _ in range(cantidad):
        muestra=rng_boot.choice(perdidas,size=len(perdidas),replace=True)
        exc=muestra[muestra>u]-u
        xi_b,beta_b=ajustar_gpd(exc)
        replicas.append(pot_var_es(u,len(exc)/len(muestra),xi_b,beta_b,.999))

bloque_bootstrap(20)
print('Réplicas:',len(replicas))
[ ]Bootstrap, block 2Browser
bloque_bootstrap(20)
print('Réplicas:',len(replicas))
[ ]Bootstrap, block 3Browser
bloque_bootstrap(20)
print('Réplicas:',len(replicas))
[ ]Bootstrap, block 4Browser
bloque_bootstrap(20)
print('Réplicas:',len(replicas))
[ ]Bootstrap, block 5 and intervalsBrowser
bloque_bootstrap(20)
replicas=np.asarray(replicas)
print('Réplicas:',len(replicas),'| ES finito:',np.isfinite(replicas[:,1]).sum())
print('Percentiles VaR 2.5 % y 97.5 %:',np.quantile(replicas[:,0],[.025,.975]))
print('Percentiles ES 2.5 % y 97.5 %:',np.quantile(replicas[:,1],[.025,.975]))

GARCH-EVT filtering

First use a series with known conditional volatility: the filter is an oracle for checking the EVT combination, not a maximum-likelihood fit. Then reproduce the ajustar_garch function from the previous lesson’s lab so this lesson runs independently.

[ ]EVT on standardized innovationsBrowser
rng_evt=np.random.default_rng(281805)
innovaciones=rng_evt.standard_t(5,size=700)*np.sqrt(3/5)
h=np.empty(len(innovaciones)); retornos=np.empty_like(h)
h[0]=.0001
for i in range(len(h)):
    retornos[i]=np.sqrt(h[i])*innovaciones[i]
    if i+1<len(h): h[i+1]=.000002+.08*retornos[i]**2+.9*h[i]
z=-retornos/np.sqrt(h)
threshold=float(np.quantile(z,.9))
y=z[z>threshold]-threshold
forma,escala=ajustar_gpd(y)
var_z,es_z=pot_var_es(threshold,len(y)/len(z),forma,escala,.99)
h_siguiente=.000002+.08*retornos[-1]**2+.9*h[-1]
print('Filtro conocido: xi, beta',forma,escala)
print('VaR y ES siguientes, media cero:',np.sqrt(h_siguiente)*var_z,np.sqrt(h_siguiente)*es_z)

This control shows scaling the filtered tail by ht+1\sqrt{h_{t+1}}. The next cell reproduces the current m28-l17 fitting function and combines it with estimated residuals and volatility. It uses no observations after the forecast date.

[ ]Fit the filter and repeat EVTBrowser
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

mu,z_estimados,sigma_proxima,parametros=ajustar_garch(retornos)
z_perdida=-z_estimados
umbral_estimado=float(np.quantile(z_perdida,.9))
y_est=z_perdida[z_perdida>umbral_estimado]-umbral_estimado
xi_est,beta_est=ajustar_gpd(y_est)
v_est,e_est=pot_var_es(umbral_estimado,len(y_est)/len(z_perdida),xi_est,beta_est,.99)
print('GARCH estimado:',parametros,'| xi GPD:',xi_est)
print('VaR y ES estimados:',-mu+sigma_proxima*v_est,-mu+sigma_proxima*e_est)

Lab: test coverage and dependence

With kk exceptions over nn dates, Bernoulli log-likelihood is klog⁡p+(n−k)log⁡(1−p)k\log p+(n-k)\log(1-p). The likelihood ratio compares nominal pp with k/nk/n; convention 0log⁡0=00\log0=0 permits samples with no exceptions. For independence, count transitions nijn_{ij} from It−1=iI_{t-1}=i to It=jI_t=j. The alternative fits separate transition probabilities and the null one common probability. Independence uses n−1n-1 transitions and coverage uses nn observations.

[ ]Kupiec and ChristoffersenBrowser
from scipy.special import xlogy

def log_bern(k,n,p):
    return xlogy(k,p)+xlogy(n-k,1-p)

def kupiec(exceptions,p):
    x=np.asarray(exceptions)
    if x.ndim!=1 or len(x)==0 or not np.isin(x,[0,1]).all() or not 0<p<1:
        raise ValueError('Serie o probabilidad inválida')
    n=len(x); k=int(x.sum()); ph=k/n
    lr=max(0.,2*(log_bern(k,n,ph)-log_bern(k,n,p)))
    return float(lr),float(chi2.sf(lr,1))

def christoffersen_test(exceptions):
    x=np.asarray(exceptions)
    if x.ndim!=1 or len(x)<2 or not np.isin(x,[0,1]).all():
        raise ValueError('Se requieren al menos dos indicadores binarios')
    n00=int(np.sum((x[:-1]==0)&(x[1:]==0)))
    n01=int(np.sum((x[:-1]==0)&(x[1:]==1)))
    n10=int(np.sum((x[:-1]==1)&(x[1:]==0)))
    n11=int(np.sum((x[:-1]==1)&(x[1:]==1)))
    n0=n00+n01; n1=n10+n11
    p0=n01/n0 if n0 else 0.; p1=n11/n1 if n1 else 0.
    p=(n01+n11)/(len(x)-1)
    alt=log_bern(n01,n0,p0)+log_bern(n11,n1,p1)
    nul=log_bern(n01+n11,len(x)-1,p)
    lr=max(0.,2*(alt-nul))
    return float(lr),float(chi2.sf(lr,1)),(n00,n01,n10,n11)

ejemplo=np.r_[np.ones(7,dtype=int),np.zeros(243,dtype=int)]
print('Kupiec con 7 excepciones:',kupiec(ejemplo,.01))
print('Independencia en una racha:',christoffersen_test(ejemplo))

Figures from one sequence are not power. To study power, simulate many 250-date sequences under independent Bernoulli probability 0.05 and under a chain with P(1∣1)=0.5P(1\mid1)=0.5 and P(1∣0)=0.05(1−0.5)/(1−0.05)P(1\mid0)=0.05(1-0.5)/(1-0.05), whose stationary exception probability is also 0.05. Both start in the stationary distribution. Rejection proportion uses the asymptotic reference and has Monte Carlo error; the alternatives share coverage but not independence.

[ ]Power against streaksBrowser
rng_test=np.random.default_rng(281806)
repeticiones=500; ntest=250; p=.05
def generar_matriz(agrupada):
    u=rng_test.random((repeticiones,ntest))
    hits=np.zeros_like(u,dtype=int); hits[:,0]=(u[:,0]<p)
    p01=p*.5/(1-p)
    for i in range(1,ntest):
        prob=np.where(hits[:,i-1]==1,.5,p01) if agrupada else p
        hits[:,i]=(u[:,i]<prob)
    return hits

for nombre,agrupada in [('Independiente',False),('Con rachas',True)]:
    matriz=generar_matriz(agrupada)
    independencia=np.array([christoffersen_test(row)[1]<.05 for row in matriz])
    cobertura=np.array([kupiec(row,p)[1]<.05 for row in matriz])
    tasa=float(independencia.mean())
    print(nombre,'| rechazos independencia:',tasa,'| EE:',np.sqrt(tasa*(1-tasa)/repeticiones),
          '| rechazos cobertura:',cobertura.mean())
[ ]Joint scoring and ES calibrationBrowser
def score_conjunto(v,e,x,p):
    # v y e son cuantil y ES de la cola inferior de beneficios, p es su probabilidad.
    if not 0<p<1: raise ValueError('Probabilidad inválida')
    indicador=(x<=v).astype(float)
    return (indicador-p)*(v-x)+np.exp(e)*(indicador*(v-x)/p+e-v-1)

rng_score=np.random.default_rng(281807)
beneficios=rng_score.normal(size=20000); p=.05
v=norm.ppf(p); e=-norm.pdf(v)/p
verdadero=score_conjunto(v,e,beneficios,p)
erroneo=score_conjunto(.8*v,.8*e,beneficios,p)
z2=1-np.mean((-beneficios)*(beneficios<v))/(-e*p)
print('Puntuación media, par correcto:',verdadero.mean(),'| par escalado:',erroneo.mean())
print('Z2 de la muestra:',z2)

The score uses the cited paper’s profit and lower-tail convention, with G1(v)=vG_1(v)=v and G2(e)=exp⁡(e)G_2(e)=\exp(e). Lower mean score is sought, not an absolute value of zero. This simulation uses the same observations to compare both pairs and is not an empirical study. Z2Z_2 has no p-value: one would require a null distribution or suitable simulated calibration.

Lab: CVaR linear program

The portfolio has three hypothetical long-only strategies with weights summing to one. The third receives a frequent premium and suffers a rare loss, imitating option-selling asymmetry without attempting to price it. We use the same scenarios for both optimizers and calculate risk in the same sample: this compares fitting, not future-performance evidence. The LP does not constrain tt to be positive because loss VaR can be negative.

[ ]Minimize ES with constraintsBrowser
from scipy.optimize import linprog

rng_cartera=np.random.default_rng(281808)
n_c=500
R=np.column_stack([np.full(n_c,.0002),
                   .0015+.012*rng_cartera.normal(size=n_c),
                   .003-.16*(rng_cartera.random(n_c)<.01)])
media=R.mean(axis=0); objetivo=.001; alpha_c=.95

def minimo_es(R,objetivo,alpha):
    R=np.asarray(R,dtype=float); n,d=R.shape
    if n==0 or d==0 or not np.isfinite(R).all() or not 0<alpha<1:
        raise ValueError('Escenarios inválidos')
    c=np.r_[np.zeros(d),1.,np.ones(n)/(n*(1-alpha))]
    A=np.zeros((n+1,d+1+n))
    A[:n,:d]=-R; A[:n,d]=-1.; A[:n,d+1:]=-np.eye(n)
    A[-1,:d]=-R.mean(axis=0)
    b=np.r_[np.zeros(n),-objetivo]
    eq=np.zeros((1,d+1+n)); eq[0,:d]=1
    result=linprog(c,A_ub=A,b_ub=b,A_eq=eq,b_eq=[1.],
                   bounds=[(0,None)]*d+[(None,None)]+[(0,None)]*n,
                   method='highs')
    if not result.success: raise RuntimeError(result.message)
    return result.x[:d],result.fun

w_es,valor_es=minimo_es(R,objetivo,alpha_c)
cov=np.cov(R,rowvar=False,bias=True)
res_mv=minimize(lambda w:float(w@cov@w),np.full(3,1/3),method='SLSQP',
                bounds=[(0,1)]*3,constraints=[{'type':'eq','fun':lambda w:w.sum()-1},
                {'type':'ineq','fun':lambda w:float(media@w-objetivo)}],
                options={'ftol':1e-12,'maxiter':1000})
if not res_mv.success: raise RuntimeError(res_mv.message)

def es_empirico(loss,alpha):
    x=np.sort(np.asarray(loss,dtype=float))[::-1]
    masa=len(x)*(1-alpha); k=int(np.floor(masa+1e-12)); f=masa-k
    return (x[:k].sum()+(f*x[k] if f>1e-12 else 0))/masa

print('Pesos ES:',w_es,'| media:',media@w_es,'| ES:',es_empirico(-R@w_es,alpha_c),'| objetivo LP:',valor_es)
print('Pesos varianza:',res_mv.x,'| media:',media@res_mv.x,'| ES:',es_empirico(-R@res_mv.x,alpha_c))
print('Escenarios de pérdida rara:',int((R[:,2]<0).sum()))

The figure uses another seed and a discrete 5% weight grid, while the lab solves the continuous LP and minimizes variance with SLSQP. Their figures need not match. Repeat with new samples and evaluate both portfolios on separate data: optimization can exploit estimation errors, especially when only a few scenarios represent the tail.

In this run there are five rare events among 500 scenarios. The minimum-variance portfolio assigns approximately 29.5% to the selling strategy; the minimum-ES portfolio approximately 9.6%. This is an in-sample comparison for the generated sample, not a universal result for those strategies. Empirical ES of the LP portfolio matches the program’s objective value, checking that free threshold and excesses use the correct sign.

Exercises

NumericSeven exceptions
Over 250 days, a 99% VaR records 7 exceptions. Calculate Kupiec's LR statistic for nominal probability 0.01.
NumericExtrapolate a quantile
Excesses above u=2 have GPD with ξ=0.25 and β=0.6. The probability of exceeding u is 0.05. Calculate 99% VaR.
ProofWhy the quantile appears
Prove: For integrable loss L, prove that the minimum of t + E[(L−t)⁺]/(1−α) is attained at an α quantile and equals ES.
The proof will appear here as you work.

Step 1 of 3. What one-sided derivatives does the convex function have with respect to t?

QuizValidate and compare
What does it imply that ES alone is not elicitable over a broad distribution class?
CodeException streaks
Implement christoffersen_test(exceptions). Receive at least two binary indicators and return (LR, p_valor, (n00,n01,n10,n11)) for the first-order independence test. Use 0 log 0 = 0 and the chi-square reference with one degree of freedom. Reject invalid inputs. Then estimate power using the lab simulation cell.
def christoffersen_test(exceptions):
  raise NotImplementedError()
Shift+Enter to run

What to retain

Key idea
Tail data are scarce. Fitting and extrapolation require threshold diagnostics, uncertainty quantification and evaluation of forecasts issued before losses are known.

Coverage counts exceptions and independence examines their sequence; passing a test does not establish model validity. Joint scoring compares forecast pairs under a stated rule and ES tests assess calibration under their own assumptions. Supplement both with stress scenarios and examine portfolio decisions out of sample. A CVaR optimizer turns scenarios into weights, but does not correct misspecified scenarios.