adds realized volatility cones to volatility_model.py

This commit is contained in:
Danglewood
2023-02-19 20:49:19 -08:00
parent 606003ce98
commit 61c03c7359

View File

@@ -2,7 +2,7 @@
__docformat__ = "numpy"
import logging
import numpy as np
import pandas as pd
import pandas_ta as ta
@@ -166,3 +166,75 @@ def atr(
offset=offset,
).dropna()
)
@log_start_end(log=logger)
def rvol(
data:pd.DataFrame,
lower_q:float = 0.25,
upper_q: float = 0.75
) -> pd.DataFrame:
"""Returns a DataFrame of realized volatility quantiles.
Paramters
---------
data: pd.DataFrame
DataFrame of the OHLC data.
lower_q: float (default = 0.25)
The lower quantile to calculate the realized volatility over time for.
upper_q: float (default = 0.75)
The upper quantile to calculate the realized volatility over time for.
Returns
-------
pd.DataFrame: rvol_cones
DataFrame of realized volatility quantiles.
Examples
--------
df = get_rvol_cones(symbol = "AAPL")
df = get_rvol_cones(symbol = "AAPL", lower_q = 0.10, upper_q = 0.90)
"""
lower_q_label = str((int(lower_q*100)))
upper_q_label = str((int(upper_q*100)))
rvol_cones: DataFrame = pd.DataFrame()
quantiles = [lower_q, upper_q]
windows = [3,10,30,60,90,120,150,180,210,240]
data = data
min_ = []
max_ = []
median = []
top_q = []
bottom_q = []
realized = []
data.index = data.index.date
data = pd.DataFrame(data).sort_index(ascending = False)
def realized_vol(data, window=30):
"""Helper function for calculating realized volatility."""
log_return = (data["Close"] / data["Close"].shift(1)).apply(np.log)
return log_return.rolling(window=window, center=False).std() * np.sqrt(252)
for window in windows:
# Looping to build a dataframe with realized volatility over each window.
estimator = realized_vol(window=window,data=data)
min_.append(estimator.min())
max_.append(estimator.max())
median.append(estimator.median())
top_q.append(estimator.quantile(quantiles[1]))
bottom_q.append(estimator.quantile(quantiles[0]))
realized.append(estimator[-1])
df = [realized, min_, bottom_q, median, top_q, max_]
pd.DataFrame(df).columns = windows
df_windows = list(windows)
df = pd.DataFrame(df, columns=df_windows)
df = df.rename(index = {0:'Realized', 1: 'Min', 2:'Lower 'f"{lower_q_label}"'%', 3:'Median', 4:'Upper 'f"{upper_q_label}"'%', 5: 'Max'})
rvol_cones = df.copy()
return rvol_cones.transpose()