Spaces:
Sleeping
Sleeping
File size: 1,669 Bytes
4cc2887 cbdae8d 4cc2887 5d00eef 4cc2887 5d00eef 1e19d03 5d00eef 1e19d03 4cc2887 5d00eef 4cc2887 cbdae8d 4cc2887 e81e185 4cc2887 e81e185 4cc2887 5d00eef | 1 2 3 4 5 6 7 8 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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | import numpy as np
import pandas as pd
import plotly.graph_objects as go
from data.schema import Out
def calculate_rolling_volatility(
returns,
window=30,
):
return returns.rolling(
window
).std()
def calculate_ewma_volatility_series(
returns,
lambda_=0.94,
):
alpha = 1 - lambda_
variance = (
returns.pow(2)
.ewm(alpha=alpha)
.mean()
)
return np.sqrt(variance)
def plot_volatility(volatility):
fig = go.Figure()
fig.add_trace(
go.Bar(
x=volatility.index,
y=volatility.values,
name="Implied Volatility",
)
)
fig.update_layout(
title="Volatility Implied by Covariance",
xaxis_title="Factor",
yaxis_title="Volatility",
template="plotly_white",
)
return fig
def volatility_comparison(
returns,
selected_method,
lambda_=0.94,
):
historical = returns.std()
ewma_series = calculate_ewma_volatility_series(
returns,
lambda_,
)
ewma = ewma_series.iloc[-1]
comparison = pd.DataFrame(
{
Out.FACTOR: returns.columns,
"Historical": historical.values,
"EWMA": ewma.values,
}
)
method_to_column = {
"historical": "Historical",
"ewma": "EWMA",
}
if selected_method not in method_to_column:
raise ValueError(
f"Unknown volatility method: {selected_method}"
)
selected_column = method_to_column[
selected_method
]
comparison["Selected"] = comparison[
selected_column
]
return comparison
|