{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# ETS models\n",
    "\n",
    "The ETS models are a family of time series models with an underlying state space model consisting of a level component, a trend component (T), a seasonal component (S), and an error term (E).\n",
    "\n",
    "This notebook shows how they can be used with `statsmodels`. For a more thorough treatment we refer to [1], chapter 8 (free online resource), on which the implementation in statsmodels and the examples used in this notebook are based.\n",
    "\n",
    "`statsmodels` implements all combinations of:\n",
    "- additive and multiplicative error model\n",
    "- additive and multiplicative trend, possibly dampened\n",
    "- additive and multiplicative seasonality\n",
    "\n",
    "However, not all of these methods are stable. Refer to [1] and references therein for more info about model stability.\n",
    "\n",
    "[1] Hyndman, Rob J., and George Athanasopoulos. *Forecasting: principles and practice*, 3rd edition, OTexts, 2019. https://www.otexts.org/fpp3/7"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "import pandas as pd\n",
    "\n",
    "%matplotlib inline\n",
    "from statsmodels.tsa.exponential_smoothing.ets import ETSModel"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "plt.rcParams[\"figure.figsize\"] = (12, 8)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simple exponential smoothing\n",
    "\n",
    "The simplest of the ETS models is also known as *simple exponential smoothing*. In ETS terms, it corresponds to the (A, N, N) model, that is, a model with additive errors, no trend, and no seasonality. The state space formulation of Holt's method is:\n",
    "\n",
    "\\begin{align}\n",
    "y_{t} &= y_{t-1} + e_t\\\\\n",
    "l_{t} &= l_{t-1} + \\alpha e_t\\\\\n",
    "\\end{align}\n",
    "\n",
    "This state space formulation can be turned into a different formulation, a forecast and a smoothing equation (as can be done with all ETS models):\n",
    "\n",
    "\\begin{align}\n",
    "\\hat{y}_{t|t-1} &= l_{t-1}\\\\\n",
    "l_{t} &= \\alpha y_{t-1} + (1 - \\alpha) l_{t-1}\n",
    "\\end{align}\n",
    "\n",
    "Here, $\\hat{y}_{t|t-1}$ is the forecast/expectation of $y_t$ given the information of the previous step. In the simple exponential smoothing model, the forecast corresponds to the previous level. The second equation (smoothing equation) calculates the next level as weighted average of the previous level and the previous observation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "oildata = [\n",
    "    111.0091,\n",
    "    130.8284,\n",
    "    141.2871,\n",
    "    154.2278,\n",
    "    162.7409,\n",
    "    192.1665,\n",
    "    240.7997,\n",
    "    304.2174,\n",
    "    384.0046,\n",
    "    429.6622,\n",
    "    359.3169,\n",
    "    437.2519,\n",
    "    468.4008,\n",
    "    424.4353,\n",
    "    487.9794,\n",
    "    509.8284,\n",
    "    506.3473,\n",
    "    340.1842,\n",
    "    240.2589,\n",
    "    219.0328,\n",
    "    172.0747,\n",
    "    252.5901,\n",
    "    221.0711,\n",
    "    276.5188,\n",
    "    271.1480,\n",
    "    342.6186,\n",
    "    428.3558,\n",
    "    442.3946,\n",
    "    432.7851,\n",
    "    437.2497,\n",
    "    437.2092,\n",
    "    445.3641,\n",
    "    453.1950,\n",
    "    454.4096,\n",
    "    422.3789,\n",
    "    456.0371,\n",
    "    440.3866,\n",
    "    425.1944,\n",
    "    486.2052,\n",
    "    500.4291,\n",
    "    521.2759,\n",
    "    508.9476,\n",
    "    488.8889,\n",
    "    509.8706,\n",
    "    456.7229,\n",
    "    473.8166,\n",
    "    525.9509,\n",
    "    549.8338,\n",
    "    542.3405,\n",
    "]\n",
    "oil = pd.Series(oildata, index=pd.date_range(\"1965\", \"2013\", freq=\"AS\"))\n",
    "oil.plot()\n",
    "plt.ylabel(\"Annual oil production in Saudi Arabia (Mt)\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The plot above shows annual oil production in Saudi Arabia in million tonnes. The data are taken from the R package `fpp2` (companion package to prior version [1]).\n",
    "Below you can see how to fit a simple exponential smoothing model using statsmodels's ETS implementation to this data. Additionally, the fit using `forecast` in R is shown as comparison."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = ETSModel(oil)\n",
    "fit = model.fit(maxiter=10000)\n",
    "oil.plot(label=\"data\")\n",
    "fit.fittedvalues.plot(label=\"statsmodels fit\")\n",
    "plt.ylabel(\"Annual oil production in Saudi Arabia (Mt)\")\n",
    "\n",
    "# obtained from R\n",
    "params_R = [0.99989969, 0.11888177503085334, 0.80000197, 36.46466837, 34.72584983]\n",
    "yhat = model.smooth(params_R).fittedvalues\n",
    "yhat.plot(label=\"R fit\", linestyle=\"--\")\n",
    "\n",
    "plt.legend()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "By default the initial states are considered to be fitting parameters and are estimated by maximizing log-likelihood. It is possible to only use a heuristic for the initial values:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model_heuristic = ETSModel(oil, initialization_method=\"heuristic\")\n",
    "fit_heuristic = model_heuristic.fit()\n",
    "oil.plot(label=\"data\")\n",
    "fit.fittedvalues.plot(label=\"estimated\")\n",
    "fit_heuristic.fittedvalues.plot(label=\"heuristic\", linestyle=\"--\")\n",
    "plt.ylabel(\"Annual oil production in Saudi Arabia (Mt)\")\n",
    "\n",
    "# obtained from R\n",
    "params = [0.99989969, 0.11888177503085334, 0.80000197, 36.46466837, 34.72584983]\n",
    "yhat = model.smooth(params).fittedvalues\n",
    "yhat.plot(label=\"with R params\", linestyle=\":\")\n",
    "\n",
    "plt.legend()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The fitted parameters and some other measures are shown using `fit.summary()`. Here we can see that the log-likelihood of the model using fitted initial states is fractionally lower than the one using a heuristic for the initial states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(fit.summary())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(fit_heuristic.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Holt-Winters' seasonal method\n",
    "\n",
    "The exponential smoothing method can be modified to incorporate a trend and a seasonal component. In the additive Holt-Winters' method, the seasonal component is added to the rest. This model corresponds to the ETS(A, A, A) model, and has the following state space formulation:\n",
    "\n",
    "\\begin{align}\n",
    "y_t &= l_{t-1} + b_{t-1} + s_{t-m} + e_t\\\\\n",
    "l_{t} &= l_{t-1} + b_{t-1} + \\alpha e_t\\\\\n",
    "b_{t} &= b_{t-1} + \\beta e_t\\\\\n",
    "s_{t} &= s_{t-m} + \\gamma e_t\n",
    "\\end{align}\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "austourists_data = [\n",
    "    30.05251300,\n",
    "    19.14849600,\n",
    "    25.31769200,\n",
    "    27.59143700,\n",
    "    32.07645600,\n",
    "    23.48796100,\n",
    "    28.47594000,\n",
    "    35.12375300,\n",
    "    36.83848500,\n",
    "    25.00701700,\n",
    "    30.72223000,\n",
    "    28.69375900,\n",
    "    36.64098600,\n",
    "    23.82460900,\n",
    "    29.31168300,\n",
    "    31.77030900,\n",
    "    35.17787700,\n",
    "    19.77524400,\n",
    "    29.60175000,\n",
    "    34.53884200,\n",
    "    41.27359900,\n",
    "    26.65586200,\n",
    "    28.27985900,\n",
    "    35.19115300,\n",
    "    42.20566386,\n",
    "    24.64917133,\n",
    "    32.66733514,\n",
    "    37.25735401,\n",
    "    45.24246027,\n",
    "    29.35048127,\n",
    "    36.34420728,\n",
    "    41.78208136,\n",
    "    49.27659843,\n",
    "    31.27540139,\n",
    "    37.85062549,\n",
    "    38.83704413,\n",
    "    51.23690034,\n",
    "    31.83855162,\n",
    "    41.32342126,\n",
    "    42.79900337,\n",
    "    55.70835836,\n",
    "    33.40714492,\n",
    "    42.31663797,\n",
    "    45.15712257,\n",
    "    59.57607996,\n",
    "    34.83733016,\n",
    "    44.84168072,\n",
    "    46.97124960,\n",
    "    60.01903094,\n",
    "    38.37117851,\n",
    "    46.97586413,\n",
    "    50.73379646,\n",
    "    61.64687319,\n",
    "    39.29956937,\n",
    "    52.67120908,\n",
    "    54.33231689,\n",
    "    66.83435838,\n",
    "    40.87118847,\n",
    "    51.82853579,\n",
    "    57.49190993,\n",
    "    65.25146985,\n",
    "    43.06120822,\n",
    "    54.76075713,\n",
    "    59.83447494,\n",
    "    73.25702747,\n",
    "    47.69662373,\n",
    "    61.09776802,\n",
    "    66.05576122,\n",
    "]\n",
    "index = pd.date_range(\"1999-03-01\", \"2015-12-01\", freq=\"3MS\")\n",
    "austourists = pd.Series(austourists_data, index=index)\n",
    "austourists.plot()\n",
    "plt.ylabel(\"Australian Tourists\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# fit in statsmodels\n",
    "model = ETSModel(\n",
    "    austourists,\n",
    "    error=\"add\",\n",
    "    trend=\"add\",\n",
    "    seasonal=\"add\",\n",
    "    damped_trend=True,\n",
    "    seasonal_periods=4,\n",
    ")\n",
    "fit = model.fit()\n",
    "\n",
    "# fit with R params\n",
    "params_R = [\n",
    "    0.35445427,\n",
    "    0.03200749,\n",
    "    0.39993387,\n",
    "    0.97999997,\n",
    "    24.01278357,\n",
    "    0.97770147,\n",
    "    1.76951063,\n",
    "    -0.50735902,\n",
    "    -6.61171798,\n",
    "    5.34956637,\n",
    "]\n",
    "fit_R = model.smooth(params_R)\n",
    "\n",
    "austourists.plot(label=\"data\")\n",
    "plt.ylabel(\"Australian Tourists\")\n",
    "\n",
    "fit.fittedvalues.plot(label=\"statsmodels fit\")\n",
    "fit_R.fittedvalues.plot(label=\"R fit\", linestyle=\"--\")\n",
    "plt.legend()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(fit.summary())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Predictions\n",
    "\n",
    "The ETS model can also be used for predicting. There are several different methods available:\n",
    "- `forecast`: makes out of sample predictions\n",
    "- `predict`: in sample and out of sample predictions\n",
    "- `simulate`: runs simulations of the statespace model\n",
    "- `get_prediction`: in sample and out of sample predictions, as well as prediction intervals\n",
    "\n",
    "We can use them on our previously fitted model to predict from 2014 to 2020."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pred = fit.get_prediction(start=\"2014\", end=\"2020\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pred.summary_frame(alpha=0.05)\n",
    "df"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this case the prediction intervals were calculated using an analytical formula. This is not available for all models. For these other models, prediction intervals are calculated by performing multiple simulations (1000 by default) and using the percentiles of the simulation results. This is done internally by the `get_prediction` method.\n",
    "\n",
    "We can also manually run simulations, e.g. to plot them. Since the data ranges until end of 2015, we have to simulate from the first quarter of 2016 to the first quarter of 2020, which means 17 steps."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "simulated = fit.simulate(anchor=\"end\", nsimulations=17, repetitions=100)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "for i in range(simulated.shape[1]):\n",
    "    simulated.iloc[:, i].plot(label=\"_\", color=\"gray\", alpha=0.1)\n",
    "df[\"mean\"].plot(label=\"mean prediction\")\n",
    "df[\"pi_lower\"].plot(linestyle=\"--\", color=\"tab:blue\", label=\"95% interval\")\n",
    "df[\"pi_upper\"].plot(linestyle=\"--\", color=\"tab:blue\", label=\"_\")\n",
    "pred.endog.plot(label=\"data\")\n",
    "plt.legend()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this case, we chose \"end\" as simulation anchor, which means that the first simulated value will be the first out of sample value. It is also possible to choose other anchor inside the sample."
   ]
  }
 ],
 "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"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
