6.7 KiB
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.
import numpy as np import yfinance as yf from arch import arch_model
%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
data = yf.download("aapl", start="2020-01-01", end="2022-07-31")
Extract adjusted closing prices and calculate daily returns in percentage terms
adjusted_closes = data['Adj Close'] returns = 100 * adjusted_closes.pct_change().dropna()
Initialize an ARCH model using the calculated returns
model = arch_model(returns)
Fit the ARCH model to the returns data
res = model.fit()
Print a summary of the model fitting results
print(res.summary())
Plot the results of the model fitting for visualization
fig = res.plot("D")
Forecast variance for the next period using the fitted model
forecast = res.forecast(horizon=1, reindex=False) variance_forecast = forecast.variance.iloc[-1][0]
Calculate the forecasted volatility and annualize it
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
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
(annualized_volatility_forecast - annualized_volatility_stdev) / annualized_volatility_stdev
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.
