Skip to content

REALIZED SEMIVARIANCE

Intuição

A Realized Semivariance decompõe a variância realizada em componentes de retornos positivos e negativos, permitindo medir separadamente a volatilidade “boa” e “ruim”.

Definição

Para retornos r_t:

  • RSV+_t = r_t^2 * I(r_t > 0)
  • RSV-_t = r_t^2 * I(r_t < 0)

A função retorna um DataFrame com as colunas rsv_pos e rsv_neg.

Uso

from quantmaster.features.volatility import realized_semivariance

out = realized_semivariance(df)
# df = df.join(out)

API

Source code in src/quantmaster/features/volatility.py
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def realized_semivariance(
    data: pd.DataFrame | pd.Series,
    *,
    price_col: str = "close",
    log_returns: bool = True,
) -> pd.DataFrame:
    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()

    sq = rets.pow(2)
    pos = sq.where(rets > 0, 0.0)
    neg = sq.where(rets < 0, 0.0)

    out = pd.DataFrame(index=price.index)
    out["rsv_pos"] = pos
    out["rsv_neg"] = neg
    return out