{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Estimating or specifying parameters in state space models\n",
    "\n",
    "In this notebook we show how to fix specific values of certain parameters in statsmodels' state space models while estimating others.\n",
    "\n",
    "In general, state space models allow users to:\n",
    "\n",
    "1. Estimate all parameters by maximum likelihood\n",
    "2. Fix some parameters and estimate the rest\n",
    "3. Fix all parameters (so that no parameters are estimated)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline\n",
    "\n",
    "from importlib import reload\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import statsmodels.api as sm\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "from pandas_datareader.data import DataReader"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To illustrate, we will use the Consumer Price Index for Apparel, which has a time-varying level and a strong seasonal component."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "endog = DataReader('CPIAPPNS', 'fred', start='1980').asfreq('MS')\n",
    "endog.plot(figsize=(15, 3));"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It is well known (e.g. Harvey and Jaeger [1993]) that the HP filter output can be generated by an unobserved components model given certain restrictions on the parameters.\n",
    "\n",
    "The unobserved components model is:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "y_t & = \\mu_t + \\varepsilon_t & \\varepsilon_t \\sim N(0, \\sigma_\\varepsilon^2) \\\\\n",
    "\\mu_t &= \\mu_{t-1} + \\beta_{t-1} + \\eta_t & \\eta_t \\sim N(0, \\sigma_\\eta^2) \\\\\n",
    "\\beta_t &= \\beta_{t-1} + \\zeta_t & \\zeta_t \\sim N(0, \\sigma_\\zeta^2) \\\\\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "For the trend to match the output of the HP filter, the parameters must be set as follows:\n",
    "\n",
    "$$\n",
    "\\begin{aligned}\n",
    "\\frac{\\sigma_\\varepsilon^2}{\\sigma_\\zeta^2} & = \\lambda \\\\\n",
    "\\sigma_\\eta^2 & = 0\n",
    "\\end{aligned}\n",
    "$$\n",
    "\n",
    "where $\\lambda$ is the parameter of the associated HP filter. For the monthly data that we use here, it is usually recommended that $\\lambda = 129600$."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Run the HP filter with lambda = 129600\n",
    "hp_cycle, hp_trend = sm.tsa.filters.hpfilter(endog, lamb=129600)\n",
    "\n",
    "# The unobserved components model above is the local linear trend, or \"lltrend\", specification\n",
    "mod = sm.tsa.UnobservedComponents(endog, 'lltrend')\n",
    "print(mod.param_names)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The parameters of the unobserved components model (UCM) are written as:\n",
    "\n",
    "- $\\sigma_\\varepsilon^2 = \\text{sigma2.irregular}$\n",
    "- $\\sigma_\\eta^2 = \\text{sigma2.level}$\n",
    "- $\\sigma_\\zeta^2 = \\text{sigma2.trend}$\n",
    "\n",
    "To satisfy the above restrictions, we will set $(\\sigma_\\varepsilon^2, \\sigma_\\eta^2, \\sigma_\\zeta^2) = (1, 0, 1 / 129600)$.\n",
    "\n",
    "Since we are fixing all parameters here, we do not need to use the `fit` method at all, since that method is used to perform maximum likelihood estimation. Instead, we can directly run the Kalman filter and smoother at our chosen parameters using the `smooth` method."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "res = mod.smooth([1., 0, 1. / 129600])\n",
    "print(res.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The estimate that corresponds to the HP filter's trend estimate is given by the smoothed estimate of the `level` (which is $\\mu_t$ in the notation above):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ucm_trend = pd.Series(res.level.smoothed, index=endog.index)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It is easy to see that the estimate of the smoothed level from the UCM is equal to the output of the HP filter:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(figsize=(15, 3))\n",
    "\n",
    "ax.plot(hp_trend, label='HP estimate')\n",
    "ax.plot(ucm_trend, label='UCM estimate')\n",
    "ax.legend();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Adding a seasonal component"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "However, unobserved components models are more flexible than the HP filter. For example, the data shown above is clearly seasonal, but with time-varying seasonal effects (the seasonality is much weaker at the beginning than at the end). One of the benefits of the unobserved components framework is that we can add a stochastic seasonal component. In this case, we will estimate the variance of the seasonal component by maximum likelihood while still including the restriction on the parameters implied above so that the trend corresponds to the HP filter concept.\n",
    "\n",
    "Adding the stochastic seasonal component adds one new parameter, `sigma2.seasonal`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Construct a local linear trend model with a stochastic seasonal component of period 1 year\n",
    "mod = sm.tsa.UnobservedComponents(endog, 'lltrend', seasonal=12, stochastic_seasonal=True)\n",
    "print(mod.param_names)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this case, we will continue to restrict the first three parameters as described above, but we want to estimate the value of `sigma2.seasonal` by maximum likelihood. Therefore, we will use the `fit` method along with the `fix_params` context manager.\n",
    "\n",
    "The `fix_params` method takes a dictionary of parameters names and associated values. Within the generated context, those parameters will be used in all cases. In the case of the `fit` method, only the parameters that were not fixed will be estimated."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Here we restrict the first three parameters to specific values\n",
    "with mod.fix_params({'sigma2.irregular': 1, 'sigma2.level': 0, 'sigma2.trend': 1. / 129600}):\n",
    "    # Now we fit any remaining parameters, which in this case\n",
    "    # is just `sigma2.seasonal`\n",
    "    res_restricted = mod.fit()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Alternatively, we could have simply used the `fit_constrained` method, which also accepts a dictionary of constraints:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "res_restricted = mod.fit_constrained({'sigma2.irregular': 1, 'sigma2.level': 0, 'sigma2.trend': 1. / 129600})"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The summary output includes all parameters, but indicates that the first three were fixed (and so were not estimated)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(res_restricted.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For comparison, we construct the unrestricted maximum likelihood estimates (MLE). In this case, the estimate of the level will no longer correspond to the HP filter concept."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "res_unrestricted = mod.fit()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, we can retrieve the smoothed estimates of the trend and seasonal components."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Construct the smoothed level estimates\n",
    "unrestricted_trend = pd.Series(res_unrestricted.level.smoothed, index=endog.index)\n",
    "restricted_trend = pd.Series(res_restricted.level.smoothed, index=endog.index)\n",
    "\n",
    "# Construct the smoothed estimates of the seasonal pattern\n",
    "unrestricted_seasonal = pd.Series(res_unrestricted.seasonal.smoothed, index=endog.index)\n",
    "restricted_seasonal = pd.Series(res_restricted.seasonal.smoothed, index=endog.index)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Comparing the estimated level, it is clear that the seasonal UCM with fixed parameters still produces a trend that corresponds very closely (although no longer exactly) to the HP filter output.\n",
    "\n",
    "Meanwhile, the estimated level from the model with no parameter restrictions (the MLE model) is much less smooth than these."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(figsize=(15, 3))\n",
    "\n",
    "ax.plot(unrestricted_trend, label='MLE, with seasonal')\n",
    "ax.plot(restricted_trend, label='Fixed parameters, with seasonal')\n",
    "ax.plot(hp_trend, label='HP filter, no seasonal')\n",
    "ax.legend();"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally, the UCM with the parameter restrictions is still able to pick up the time-varying seasonal component quite well."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fig, ax = plt.subplots(figsize=(15, 3))\n",
    "\n",
    "ax.plot(unrestricted_seasonal, label='MLE')\n",
    "ax.plot(restricted_seasonal, label='Fixed parameters')\n",
    "ax.legend();"
   ]
  }
 ],
 "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.9.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
