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 is value and there are no flows, take : 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 is the lower quantile . It is not maximum loss: the tail can be much larger. Expected shortfall (ES) is the average of upper quantiles:
Assume integrable loss. For a continuous distribution with no mass at the threshold, this is conditional expected above VaR. With atoms that expression may be incorrect: take only the fraction of the atom needed to complete probability . This distinction is essential for credit portfolios; see Acerbi and Tasche.
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, implies ; ; for ; and . 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 , exactly one loss and two losses . VaR of the sum is 1, greater than 0+0. Individual ES is 0.8 and combined ES is , less than 1.6. The tail includes a fraction of the one-loss scenario.
For integrable losses, ES satisfies all four axioms. A subadditivity proof starts from the dual representation , where and . The same admissible family is used for , 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 to quantiles between 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 , with and standard normal , gives
For , , and with , let and be its density. Then and . Here is scale, not standard deviation: for the latter is . The tail integral follows by integrating using the derivative of .
Cornish-Fisher approximates the standardized quantile using skewness and excess kurtosis : . 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 , has mean and variance . 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 summing to one, order losses from largest to smallest. ES integrates scenario masses until accumulating ; if the final mass exceeds the remainder, only the required fraction is taken. For example, exponential weighting assigns an observation of age weight proportional to , with . Smaller reduces the influence of old events but also reduces effective size . 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), and is calculated only with information available through . 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.).
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 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.
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 , if is homogeneous of degree one and differentiable, Euler’s theorem gives
The Euler contribution of position is . With a continuous distribution and sufficient regularity, the ES derivative is . 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 and define . Homogeneity gives , while the chain rule gives . 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, ; 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 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.
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))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, . 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.
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.
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.
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.
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.
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
Step 1 of 2. Which set of densities is used for L and M?
Step 1 of 2. What identity holds for positive t?
def fhs_var_es(returns, weights, alpha):
raise NotImplementedError()What to retain
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.