Files
strategy-lab/to_explore/pyquantnews/4_VolatilityCones.ipynb
David Brazda e3da60c647 daily update
2024-10-21 20:57:56 +02:00

6.8 KiB

No description has been provided for this image

This code downloads historical stock data for JPMorgan Chase & Co. (JPM) from Yahoo Finance, covering the year 2020. It calculates realized volatility over various rolling windows (30, 60, 90, 120 days) and analyzes the maximum, minimum, top quantile, median, and bottom quantile of these volatilities. The results are visualized using Matplotlib to show the volatility distribution over different windows. This is useful for understanding the stock's risk profile over different time frames.

In [ ]:
import math
import yfinance as yf
import numpy as np
import matplotlib.pyplot as plt

Download historical stock data for JPM from Yahoo Finance for the year 2020

In [ ]:
data = yf.download("JPM", start="2020-01-01", end="2020-12-31")

Define rolling windows and quantiles to analyze

In [ ]:
windows = [30, 60, 90, 120]
quantiles = [0.25, 0.75]

Initialize lists to store maximum, minimum, quantiles, median, and realized volatilities

In [ ]:
max_ = []
min_ = []
top_q = []
median = []
bottom_q = []
realized = []

Calculate realized volatility using rolling windows

In [ ]:
def realized_vol(price_data, window=30):
    """
    Calculates realized volatility over a rolling window
    
    Parameters
    ----------
    price_data : pd.DataFrame
        DataFrame containing stock price data
    window : int
        Rolling window size in days
    
    Returns
    -------
    realized_vol : pd.Series
        Series containing realized volatility values
    """
    
    # Compute log returns from closing prices
    log_return = (price_data["Close"] / price_data["Close"].shift(1)).apply(np.log)
    
    # Compute rolling standard deviation of log returns and annualize it
    return log_return.rolling(window=window, center=False).std() * math.sqrt(252)

Loop over each window to calculate and store volatility metrics

In [ ]:
for window in windows:

    # Calculate realized volatility for the current window
    estimator = realized_vol(window=window, price_data=data)

    # Append the maximum realized volatility to the list
    max_.append(estimator.max())

    # Append the top quantile realized volatility to the list
    top_q.append(estimator.quantile(quantiles[1]))

    # Append the median realized volatility to the list
    median.append(estimator.median())

    # Append the bottom quantile realized volatility to the list
    bottom_q.append(estimator.quantile(quantiles[0]))

    # Append the minimum realized volatility to the list
    min_.append(estimator.min())

    # Append the last realized volatility to the list
    realized.append(estimator[-1])

Plot the realized volatility metrics for different rolling windows

In [ ]:
plt.plot(windows, max_, "-o", linewidth=1, label="Max")
plt.plot(windows, top_q, "-o", linewidth=1, label=f"{quantiles[1] * 100:.0f} Prctl")
plt.plot(windows, median, "-o", linewidth=1, label="Median")
plt.plot(windows, bottom_q, "-o", linewidth=1, label=f"{quantiles[0] * 100:.0f} Prctl")
plt.plot(windows, min_, "-o", linewidth=1, label="Min")

Plot the realized volatility calculated from the latest window

In [ ]:
plt.plot(windows, realized, "ro-.", linewidth=1, label="Realized")
plt.xticks(windows)
plt.legend(loc="upper center", bbox_to_anchor=(0.5, -0.1), ncol=3)

Plot the closing prices of the stock data

In [ ]:
data.Close.plot()

PyQuant News is where finance practitioners level up with Python for quant finance, algorithmic trading, and market data analysis. Looking to get started? Check out the fastest growing, top-selling course to get started with Python for quant finance. For educational purposes. Not investment advise. Use at your own risk.