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

6.7 KiB

No description has been provided for this image

This code downloads historical stock data, calculates returns, and fits an ARCH model to forecast volatility. It utilizes the Yahoo Finance API to obtain the adjusted closing prices of a specified stock. The ARCH model is then fitted to the calculated returns to estimate future volatility. The results are visualized and the forecasted volatility is annualized. This approach is valuable for financial modeling and risk management.

In [ ]:
import numpy as np
import yfinance as yf
from arch import arch_model
In [ ]:
%matplotlib inline
import matplotlib.pyplot as plt
plt.rc("figure", figsize=(16, 6))
plt.rc("savefig", dpi=90)
plt.rc("font", family="sans-serif")
plt.rc("font", size=14)

Download historical stock data for Apple (AAPL) from Yahoo Finance

In [ ]:
data = yf.download("aapl", start="2020-01-01", end="2022-07-31")

Extract adjusted closing prices and calculate daily returns in percentage terms

In [ ]:
adjusted_closes = data['Adj Close']
returns = 100 * adjusted_closes.pct_change().dropna()

Initialize an ARCH model using the calculated returns

In [ ]:
model = arch_model(returns)

Fit the ARCH model to the returns data

In [ ]:
res = model.fit()

Print a summary of the model fitting results

In [ ]:
print(res.summary())

Plot the results of the model fitting for visualization

In [ ]:
fig = res.plot("D")

Forecast variance for the next period using the fitted model

In [ ]:
forecast = res.forecast(horizon=1, reindex=False)
variance_forecast = forecast.variance.iloc[-1][0]

Calculate the forecasted volatility and annualize it

In [ ]:
volatility_forecast = np.sqrt(variance_forecast)
annualized_volatility_forecast = volatility_forecast * np.sqrt(252) / 100
annualized_volatility_forecast

Calculate the historical annualized volatility standard deviation

In [ ]:
annualized_volatility_stdev = returns.std() * np.sqrt(252) / 100
annualized_volatility_stdev

Compute the relative error between the forecasted volatility and the historical volatility standard deviation

In [ ]:
(annualized_volatility_forecast - annualized_volatility_stdev) / annualized_volatility_stdev
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 
In [ ]:
 

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.