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
- 28Value at RiskExpected ShortfallCoherent risk measuresHistorical simulation VaRFiltered historical simulationMean-variance optimization
- 04Heavy-tailed distributionsOrder statistics
- 05Generalized likelihood ratio testWilks' theoremNumerically stable maximum likelihoodProfile likelihood interval
- 06Linear programming
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.
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 conditional on .
For normalized maxima, the limiting GEV family has distribution on its support, with and . The case is the Gumbel limit, ; corresponds to a Fréchet-type tail and 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):
When take the exponential limit . If the tail has finite upper endpoint ; if it is Pareto-like; if 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 and , the approximation gives
For , and . In data, estimate by the exceedance proportion and 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 and solving for . For ES, threshold stability gives scale at the new threshold; when , mean excess is that scale divided by . Adding it to gives the expression above. If , a finite sum of observations is not evidence that theoretical model ES is finite.
The mean residual-life plot shows . For a GPD valid from and , for . Look for an approximately linear region alongside stability of tail index and quantiles. GPD scale changes with threshold, , so requiring raw scale to be constant would be an incorrect diagnostic.
Hill and conditional risk
For ordered positive losses , the Hill estimator with upper observations is
If the tail is exactly Pareto with , the log ratio above a tail threshold is exponential with mean . Hill averages those logarithms. For regularly varying tails, consistency requires an intermediate sequence and , plus tail assumptions. A Hill plot against helps seek stability, but a flat stretch alone does not prove the threshold correct. The normal approximation with standard error 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 : it averages over losses exceeding it. Hill instead uses the ordered observation immediately below the largest 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 issued before observing with . With a continuous conditional distribution and correct VaR at level , conditional exception probability is . For distributions with atoms, the strict rule can produce fewer exceptions than ; state the convention.
Kupiec tests unconditional coverage with a Bernoulli likelihood ratio, comparing with . 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 , the statistic is . Under the independent Bernoulli null and asymptotic conditions it is compared with . 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 is commonly compared with under the null and test conditions. Document treatment of the first observation and do not blindly trust limits with empty cells.
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 and are conditional loss VaR and ES, and , calibration statistic 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
The minimum is attained at an quantile, though several minimizers may exist. With return scenarios , loss , variables and linear portfolio constraints, impose and minimize . The problem is linear in . The optimized portfolio depends on constraints and scenarios, and solving the program does not guarantee out-of-sample risk.
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 is on its support. Optimize log scale to keep it positive and reject parameters outside support. Compare with SciPy’s implementation fixing location at zero.
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.
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.
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.
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))bloque_bootstrap(20)
print('Réplicas:',len(replicas))bloque_bootstrap(20)
print('Réplicas:',len(replicas))bloque_bootstrap(20)
print('Réplicas:',len(replicas))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.
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 . 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.
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 exceptions over dates, Bernoulli log-likelihood is . The likelihood ratio compares nominal with ; convention permits samples with no exceptions. For independence, count transitions from to . The alternative fits separate transition probabilities and the null one common probability. Independence uses transitions and coverage uses observations.
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 and , 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.
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())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 and . 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. 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 to be positive because loss VaR can be negative.
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
Step 1 of 3. What one-sided derivatives does the convex function have with respect to t?
def christoffersen_test(exceptions):
raise NotImplementedError()What to retain
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.