augment_rolling_risk_metrics

augment_rolling_risk_metrics(
    data,
    date_column,
    close_column,
    window=252,
    risk_free_rate=0.0,
    benchmark_column=None,
    annualization_factor=252,
    metrics=None,
    reduce_memory=False,
    engine='pandas',
)

The augment_rolling_risk_metrics function calculates rolling risk-adjusted performance metrics for a financial time series using either pandas or polars engine, and returns the augmented DataFrame with columns for Sharpe Ratio, Sortino Ratio, and other metrics.

Parameters

Name Type Description Default
data Union[pd.DataFrame, pd.core.groupby.generic.DataFrameGroupBy] The input data can be a pandas DataFrame or a pandas DataFrameGroupBy object containing the time series data for risk metric calculations. required
date_column str The name of the column containing dates or timestamps. required
close_column str The column containing closing prices to calculate returns and risk metrics from. required
window int The rolling window size for calculations (e.g., 252 for annual). Default is 252. 252
risk_free_rate float The assumed risk-free rate (e.g., 0.0 for 0%). Default is 0.0. 0.0
benchmark_column str or None The column containing benchmark returns (e.g., market index) for Treynor and Information Ratios. Default is None. None
annualization_factor int The factor to annualize returns and volatility (e.g., 252 for daily data). Default is 252. 252
metrics List[str] or None The list of risk metrics to calculate. Choose from: ‘sharpe_ratio’, ‘sortino_ratio’, ‘treynor_ratio’, ‘information_ratio’, ‘omega_ratio’, ‘volatility_annualized’, ‘skewness’, ‘kurtosis’. Default is None (all metrics). None
reduce_memory bool If True, reduces memory usage of the DataFrame before calculation. Default is False. False
engine str The computation engine to use: ‘pandas’ or ‘polars’. Default is ‘pandas’. 'pandas'

Returns

Name Type Description
pd.DataFrame A pandas DataFrame augmented with columns: - {close_column}sharpe_ratio{window}: Rolling Sharpe Ratio - {close_column}sortino_ratio{window}: Rolling Sortino Ratio - {close_column}treynor_ratio{window}: Rolling Treynor Ratio (if benchmark provided) - {close_column}information_ratio{window}: Rolling Information Ratio (if benchmark provided) - {close_column}omega_ratio{window}: Rolling Omega Ratio - {close_column}volatility_annualized{window}: Rolling annualized volatility - {close_column}skewness{window}: Rolling skewness of returns - {close_column}kurtosis{window}: Rolling kurtosis of returns

Notes

This function computes returns from closing prices and calculates rolling risk metrics:

  • Sharpe Ratio: Excess return over risk-free rate divided by volatility
  • Sortino Ratio: Excess return over risk-free rate divided by downside deviation
  • Treynor Ratio: Excess return over risk-free rate divided by beta (requires benchmark)
  • Information Ratio: Excess return over benchmark divided by tracking error (requires benchmark)
  • Omega Ratio: Ratio of gains to losses above/below a threshold
  • Volatility: Annualized standard deviation of returns
  • Skewness: Asymmetry of return distribution
  • Kurtosis: Fat-tailedness of return distribution

Examples

import pandas as pd
import pytimetk as tk

df = tk.load_dataset('stocks_daily', parse_dates=['date'])

# Single stock risk metrics
risk_df = (
    df.query("symbol == 'AAPL'")
    .augment_rolling_risk_metrics(
        date_column='date',
        close_column='adjusted',
        window=252
    )
)
risk_df.head()
symbol date open high low close volume adjusted adjusted_sharpe_ratio_252 adjusted_sortino_ratio_252 adjusted_volatility_annualized_252 adjusted_omega_ratio_252 adjusted_skewness_252 adjusted_kurtosis_252
5398 AAPL 2013-01-02 19.779285 19.821428 19.343929 19.608213 560518000 16.791180 NaN NaN NaN NaN NaN NaN
5399 AAPL 2013-01-03 19.567142 19.631071 19.321428 19.360714 352965200 16.579241 NaN NaN NaN NaN NaN NaN
5400 AAPL 2013-01-04 19.177500 19.236786 18.779642 18.821428 594333600 16.117437 NaN NaN NaN NaN NaN NaN
5401 AAPL 2013-01-07 18.642857 18.903570 18.400000 18.710714 484156400 16.022623 NaN NaN NaN NaN NaN NaN
5402 AAPL 2013-01-08 18.900356 18.996071 18.616072 18.761070 458707200 16.065746 NaN NaN NaN NaN NaN NaN
# Multiple stocks with groupby and benchmark
risk_df = (
    df.groupby('symbol')
    .augment_rolling_risk_metrics(
        date_column='date',
        close_column='adjusted',
        # benchmark_column='market_adjusted_returns',  # Use if a benchmark returns column exists
        window=60,
        engine='polars'
    )
)
risk_df.head()
symbol date open high low close volume adjusted adjusted_sharpe_ratio_60 adjusted_volatility_annualized_60 adjusted_sortino_ratio_60 adjusted_omega_ratio_60 adjusted_skewness_60 adjusted_kurtosis_60
0 META 2013-01-02 27.440001 28.180000 27.420000 28.000000 69846400 28.000000 NaN NaN NaN NaN NaN NaN
1 META 2013-01-03 27.879999 28.469999 27.590000 27.770000 63140600 27.770000 NaN NaN NaN NaN NaN NaN
2 META 2013-01-04 28.010000 28.930000 27.830000 28.760000 72715400 28.760000 NaN NaN NaN NaN NaN NaN
3 META 2013-01-07 28.690001 29.790001 28.650000 29.420000 83781800 29.420000 NaN NaN NaN NaN NaN NaN
4 META 2013-01-08 29.510000 29.600000 28.860001 29.059999 45871300 29.059999 NaN NaN NaN NaN NaN NaN
# Selective metrics
risk_df = (
    df.groupby('symbol')
    .augment_rolling_risk_metrics(
        date_column='date',
        close_column='adjusted',
        window=252,
        metrics=['sharpe_ratio', 'sortino_ratio', 'volatility_annualized'],
    )
)
risk_df.tail()
symbol date open high low close volume adjusted adjusted_sharpe_ratio_252 adjusted_sortino_ratio_252 adjusted_volatility_annualized_252
16189 GOOG 2023-09-15 138.800003 139.360001 137.179993 138.300003 48947600 138.300003 0.779725 1.180882 0.342702
16190 GOOG 2023-09-18 137.630005 139.929993 137.630005 138.960007 16233600 138.960007 0.849816 1.280206 0.342142
16191 GOOG 2023-09-19 138.250000 139.175003 137.500000 138.830002 15479100 138.830002 0.854721 1.286448 0.342127
16192 GOOG 2023-09-20 138.830002 138.839996 134.520004 134.589996 21473500 134.589996 0.754537 1.139451 0.343635
16193 GOOG 2023-09-21 132.389999 133.190002 131.089996 131.360001 22042700 131.360001 0.740337 1.117618 0.343947