Expected Shortfall
Intuição
O Expected Shortfall (ES) (também conhecido como CVaR) mede a perda média condicional nas piores realizações além do VaR.
Definição
Para retornos r, janela n e confiança c:
alpha = 1 - c
q = quantile(r, alpha)
ES = -mean(r | r <= q)
Uso
from quantmaster.features.risk import expected_shortfall
df["es"] = expected_shortfall(df, window=252, confidence=0.95)
API
Source code in src/quantmaster/features/risk.py
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79 | def expected_shortfall(
data: pd.DataFrame | pd.Series,
*,
window: int = 252,
confidence: float = 0.95,
price_col: str = "close",
log_returns: bool = True,
) -> pd.Series:
window = validate_positive_int(window, name="window")
try:
confidence = float(confidence)
except (TypeError, ValueError) as exc:
raise TypeError(f"confidence must be float, got {type(confidence).__name__}") from exc
if not (0.0 < confidence < 1.0):
raise ValueError(f"confidence must be between 0 and 1, got {confidence}")
price = get_price_series(data, price_col=price_col).astype(float)
price = price.where(price > 0)
if log_returns:
rets = np.log(price).diff()
else:
rets = price.pct_change()
alpha = 1.0 - confidence
out = rets.rolling(window).apply(lambda x: _expected_shortfall_window(x, alpha=alpha), raw=True)
out = out.clip(lower=0.0)
out.name = f"expected_shortfall_{window}_{confidence:g}"
return out
|