Skip to content

Tail Risk Measure

Intuição

A Tail Risk Measure segue a ideia de Kelly & Jiang (2014): compara a severidade média das perdas na cauda com um quantil de referência.

Definição

Para retornos r, janela n e quantil q:

  • t = quantile(r, q)
  • TRM = mean(r | r <= t) / t

Uso

from quantmaster.features.risk import tail_risk_measure

df["trm"] = tail_risk_measure(df, window=60, quantile=0.05)

API

Source code in src/quantmaster/features/risk.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def tail_risk_measure(
    data: pd.DataFrame | pd.Series,
    *,
    window: int = 60,
    quantile: float = 0.05,
    price_col: str = "close",
    log_returns: bool = True,
) -> pd.Series:
    window = validate_positive_int(window, name="window")
    try:
        quantile = float(quantile)
    except (TypeError, ValueError) as exc:
        raise TypeError(f"quantile must be float, got {type(quantile).__name__}") from exc
    if not (0.0 < quantile < 1.0):
        raise ValueError(f"quantile must be between 0 and 1, got {quantile}")

    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()

    out = rets.rolling(window).apply(lambda x: _tail_risk_measure_window(x, quantile=quantile), raw=True)
    out.name = f"tail_risk_measure_{window}_{quantile:g}"
    return out