{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "920cf328",
   "metadata": {},
   "source": [
    "<div style=\"background-color:#000;\"><img src=\"pqn.png\"></img></div>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "879db885",
   "metadata": {},
   "source": [
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "335fbd37",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import yfinance as yf\n",
    "from arch import arch_model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2332c898",
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "import matplotlib.pyplot as plt\n",
    "plt.rc(\"figure\", figsize=(16, 6))\n",
    "plt.rc(\"savefig\", dpi=90)\n",
    "plt.rc(\"font\", family=\"sans-serif\")\n",
    "plt.rc(\"font\", size=14)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2088696e",
   "metadata": {},
   "source": [
    "Download historical stock data for Apple (AAPL) from Yahoo Finance"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "38de8923",
   "metadata": {},
   "outputs": [],
   "source": [
    "data = yf.download(\"aapl\", start=\"2020-01-01\", end=\"2022-07-31\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ebf2b85c",
   "metadata": {},
   "source": [
    "Extract adjusted closing prices and calculate daily returns in percentage terms"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ff63f46b",
   "metadata": {},
   "outputs": [],
   "source": [
    "adjusted_closes = data['Adj Close']\n",
    "returns = 100 * adjusted_closes.pct_change().dropna()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "066381ec",
   "metadata": {},
   "source": [
    "Initialize an ARCH model using the calculated returns"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "77127441",
   "metadata": {},
   "outputs": [],
   "source": [
    "model = arch_model(returns)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e0fbb63b",
   "metadata": {},
   "source": [
    "Fit the ARCH model to the returns data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8c4d2599",
   "metadata": {},
   "outputs": [],
   "source": [
    "res = model.fit()"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f00f8634",
   "metadata": {},
   "source": [
    "Print a summary of the model fitting results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "afe19f42",
   "metadata": {},
   "outputs": [],
   "source": [
    "print(res.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b19de7fa",
   "metadata": {},
   "source": [
    "Plot the results of the model fitting for visualization"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "820b348f",
   "metadata": {},
   "outputs": [],
   "source": [
    "fig = res.plot(\"D\")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "377f0e9a",
   "metadata": {},
   "source": [
    "Forecast variance for the next period using the fitted model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "67613456",
   "metadata": {},
   "outputs": [],
   "source": [
    "forecast = res.forecast(horizon=1, reindex=False)\n",
    "variance_forecast = forecast.variance.iloc[-1][0]"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "18fd8b24",
   "metadata": {},
   "source": [
    "Calculate the forecasted volatility and annualize it"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0f457d02",
   "metadata": {},
   "outputs": [],
   "source": [
    "volatility_forecast = np.sqrt(variance_forecast)\n",
    "annualized_volatility_forecast = volatility_forecast * np.sqrt(252) / 100\n",
    "annualized_volatility_forecast"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "8f619b19",
   "metadata": {},
   "source": [
    "Calculate the historical annualized volatility standard deviation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3522f50d",
   "metadata": {},
   "outputs": [],
   "source": [
    "annualized_volatility_stdev = returns.std() * np.sqrt(252) / 100\n",
    "annualized_volatility_stdev"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b1fa7d5d",
   "metadata": {},
   "source": [
    "Compute the relative error between the forecasted volatility and the historical volatility standard deviation"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a5e08674",
   "metadata": {},
   "outputs": [],
   "source": [
    "(annualized_volatility_forecast - annualized_volatility_stdev) / annualized_volatility_stdev"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "35246630",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ca318b09",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d2cc08df",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a12d9575",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3956f9ac",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ac528c77",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "5449b958",
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "id": "7548750a",
   "metadata": {},
   "source": [
    "<a href=\"https://pyquantnews.com/\">PyQuant News</a> 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 <a href=\"https://gettingstartedwithpythonforquantfinance.com/\">get started with Python for quant finance</a>. For educational purposes. Not investment advise. Use at your own risk."
   ]
  }
 ],
 "metadata": {
  "jupytext": {
   "cell_metadata_filter": "-all",
   "main_language": "python",
   "notebook_metadata_filter": "-all"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
