Skip to content

Value at Risk (Historical)

Intuição

O Value at Risk (VaR) histórico estima, a partir de uma janela de retornos passados, a perda (magnitude) que não deve ser excedida com uma determinada confiança.

Definição

Para retornos r em uma janela n e confiança c:

  • alpha = 1 - c
  • VaR = -quantile(r, alpha)

Uso

from quantmaster.features.risk import value_at_risk_historical

df["var"] = value_at_risk_historical(df, window=252, confidence=0.95)

API

Source code in src/quantmaster/features/risk.py
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
def value_at_risk_historical(
    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
    q = rets.rolling(window).quantile(alpha)
    out = (-q).clip(lower=0.0)
    out.name = f"value_at_risk_historical_{window}_{confidence:g}"
    return out