{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Rolling Regression\n",
    "\n",
    "Rolling OLS applies OLS across a fixed windows of observations and then rolls \n",
    "(moves or slides) the window across the data set. They key parameter is `window` \n",
    "which determines the number of observations used in each OLS regression. By \n",
    "default, `RollingOLS` drops missing values in the window and so will estimate \n",
    "the model using the available data points.\n",
    "\n",
    "Estimated values are aligned so that models estimated using data points \n",
    "$i+1, i+2, ... i+window$ are stored in location $i+window$. \n",
    "\n",
    "Start by importing the modules that are used in this notebook."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "is_executing": false
    }
   },
   "outputs": [],
   "source": [
    "import matplotlib.pyplot as plt\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import pandas_datareader as pdr\n",
    "import seaborn\n",
    "\n",
    "import statsmodels.api as sm\n",
    "from statsmodels.regression.rolling import RollingOLS\n",
    "\n",
    "seaborn.set_style(\"darkgrid\")\n",
    "pd.plotting.register_matplotlib_converters()\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "`pandas-datareader` is used to download data from\n",
    "[Ken French's website](https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/data_library.html). \n",
    "The two data sets downloaded are the 3 Fama-French factors and the 10 industry portfolios. \n",
    "Data is available from 1926. \n",
    "\n",
    "The data are monthly returns for the factors or industry portfolios."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "is_executing": false,
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "factors = pdr.get_data_famafrench(\"F-F_Research_Data_Factors\", start=\"1-1-1926\")[0]\n",
    "factors.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "industries = pdr.get_data_famafrench(\"10_Industry_Portfolios\", start=\"1-1-1926\")[0]\n",
    "industries.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "The first model estimated is a rolling version of the CAPM that regresses\n",
    "the excess return of Technology sector firms on the excess return of the market.\n",
    "\n",
    "The window is 60 months, and so results are available after the first 60 (`window`) \n",
    "months. The first 59 (`window - 1`) estimates are all `nan` filled."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "is_executing": false,
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "endog = industries.HiTec - factors.RF.values\n",
    "exog = sm.add_constant(factors[\"Mkt-RF\"])\n",
    "rols = RollingOLS(endog, exog, window=60)\n",
    "rres = rols.fit()\n",
    "params = rres.params.copy()\n",
    "params.index = np.arange(1, params.shape[0] + 1)\n",
    "params.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "params.iloc[57:62]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "params.tail()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "pycharm": {
     "name": "#%% md\n"
    }
   },
   "source": [
    "We next plot the market loading along with a 95% point-wise confidence interval.\n",
    "The `alpha=False` omits the constant column, if present.  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "is_executing": false,
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "fig = rres.plot_recursive_coefficient(variables=[\"Mkt-RF\"], figsize=(14, 6))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Next, the model is expanded to include all three factors, the excess market, the size factor\n",
    "and the value factor. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "is_executing": false,
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "exog_vars = [\"Mkt-RF\", \"SMB\", \"HML\"]\n",
    "exog = sm.add_constant(factors[exog_vars])\n",
    "rols = RollingOLS(endog, exog, window=60)\n",
    "rres = rols.fit()\n",
    "fig = rres.plot_recursive_coefficient(variables=exog_vars, figsize=(14, 18))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Formulas\n",
    "\n",
    "`RollingOLS` and `RollingWLS` both support model specification using the formula interface. The example below is equivalent to the 3-factor model estimated previously. Note that one variable is renamed to have a valid Python variable name."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "joined = pd.concat([factors, industries], axis=1)\n",
    "joined[\"Mkt_RF\"] = joined[\"Mkt-RF\"]\n",
    "mod = RollingOLS.from_formula(\"HiTec ~ Mkt_RF + SMB + HML\", data=joined, window=60)\n",
    "rres = mod.fit()\n",
    "rres.params.tail()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## `RollingWLS`: Rolling Weighted Least Squares \n",
    "\n",
    "The `rolling` module also provides `RollingWLS` which takes an optional `weights` input to perform rolling weighted least squares.  It produces results that match `WLS` when applied to rolling windows of data. "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Fit Options\n",
    "\n",
    "Fit accepts other optional keywords to set the covariance estimator.  Only two estimators are supported, `'nonrobust'` (the classic OLS estimator) and `'HC0'` which is White's heteroskedasticity robust estimator.\n",
    "\n",
    "You can set `params_only=True` to only estimate the model parameters.  This is substantially faster than computing the full set of values required to perform inference. \n",
    "\n",
    "Finally, the parameter `reset` can be set to a positive integer to control estimation error in very long samples. `RollingOLS` avoids the full matrix product when rolling by only adding the most recent observation and removing the dropped observation as it rolls through the sample. Setting `reset` uses the full inner product every `reset` periods.  In most applications this parameter can be omitted. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "pycharm": {
     "is_executing": false,
     "name": "#%%\n"
    }
   },
   "outputs": [],
   "source": [
    "%timeit rols.fit()\n",
    "%timeit rols.fit(params_only=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Expanding Sample\n",
    "It is possible to expand the sample until sufficient observations are available for the full window length.  In this example, we start once we have 12 observations available, and then increase the sample until we have 60 observations available. The first non-`nan` value is computed using 12 observations, the second 13, and so on. All other estimates are computed using 60 observations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "res = RollingOLS(endog, exog, window=60, min_nobs=12, expanding=True).fit()\n",
    "res.params.iloc[10:15]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "res.nobs[10:15]"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  },
  "pycharm": {
   "stem_cell": {
    "cell_type": "raw",
    "metadata": {
     "collapsed": false
    },
    "source": []
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
