Spaces:
Sleeping
Sleeping
Download visualization/volatility.py from MinsaitEU/VaR_model: direct link, hf CLI and curl.
- Browser
- Download file 1.67 kB
-
https://huggingface.co/spaces/MinsaitEU/VaR_model/resolve/main/visualization/volatility.py
- Command line
-
hf download hf://spaces/MinsaitEU/VaR_model/visualization/volatility.py
-
curl -L -o volatility.py https://huggingface.co/spaces/MinsaitEU/VaR_model/resolve/main/visualization/volatility.py
1.67 kB
| 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 | |