{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Exponential smoothing\n",
    "\n",
    "Let us consider chapter 7 of the excellent treatise on the subject of Exponential Smoothing By Hyndman and Athanasopoulos [1].\n",
    "We will work through all the examples in the chapter as they unfold.\n",
    "\n",
    "[1] [Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles and practice. OTexts, 2014.](https://www.otexts.org/fpp/7)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Loading data\n",
    "\n",
    "First we load some data. We have included the R data in the notebook for expedience."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2017-12-07T12:39:15.020317Z",
     "start_time": "2017-12-07T12:39:14.263100Z"
    }
   },
   "outputs": [],
   "source": [
    "import os\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "from statsmodels.tsa.api import ExponentialSmoothing, SimpleExpSmoothing, Holt\n",
    "\n",
    "%matplotlib inline\n",
    "\n",
    "data = [\n",
    "    446.6565,\n",
    "    454.4733,\n",
    "    455.663,\n",
    "    423.6322,\n",
    "    456.2713,\n",
    "    440.5881,\n",
    "    425.3325,\n",
    "    485.1494,\n",
    "    506.0482,\n",
    "    526.792,\n",
    "    514.2689,\n",
    "    494.211,\n",
    "]\n",
    "index = pd.date_range(start=\"1996\", end=\"2008\", freq=\"Y\")\n",
    "oildata = pd.Series(data, index)\n",
    "\n",
    "data = [\n",
    "    17.5534,\n",
    "    21.86,\n",
    "    23.8866,\n",
    "    26.9293,\n",
    "    26.8885,\n",
    "    28.8314,\n",
    "    30.0751,\n",
    "    30.9535,\n",
    "    30.1857,\n",
    "    31.5797,\n",
    "    32.5776,\n",
    "    33.4774,\n",
    "    39.0216,\n",
    "    41.3864,\n",
    "    41.5966,\n",
    "]\n",
    "index = pd.date_range(start=\"1990\", end=\"2005\", freq=\"Y\")\n",
    "air = pd.Series(data, index)\n",
    "\n",
    "data = [\n",
    "    263.9177,\n",
    "    268.3072,\n",
    "    260.6626,\n",
    "    266.6394,\n",
    "    277.5158,\n",
    "    283.834,\n",
    "    290.309,\n",
    "    292.4742,\n",
    "    300.8307,\n",
    "    309.2867,\n",
    "    318.3311,\n",
    "    329.3724,\n",
    "    338.884,\n",
    "    339.2441,\n",
    "    328.6006,\n",
    "    314.2554,\n",
    "    314.4597,\n",
    "    321.4138,\n",
    "    329.7893,\n",
    "    346.3852,\n",
    "    352.2979,\n",
    "    348.3705,\n",
    "    417.5629,\n",
    "    417.1236,\n",
    "    417.7495,\n",
    "    412.2339,\n",
    "    411.9468,\n",
    "    394.6971,\n",
    "    401.4993,\n",
    "    408.2705,\n",
    "    414.2428,\n",
    "]\n",
    "index = pd.date_range(start=\"1970\", end=\"2001\", freq=\"Y\")\n",
    "livestock2 = pd.Series(data, index)\n",
    "\n",
    "data = [407.9979, 403.4608, 413.8249, 428.105, 445.3387, 452.9942, 455.7402]\n",
    "index = pd.date_range(start=\"2001\", end=\"2008\", freq=\"Y\")\n",
    "livestock3 = pd.Series(data, index)\n",
    "\n",
    "data = [\n",
    "    41.7275,\n",
    "    24.0418,\n",
    "    32.3281,\n",
    "    37.3287,\n",
    "    46.2132,\n",
    "    29.3463,\n",
    "    36.4829,\n",
    "    42.9777,\n",
    "    48.9015,\n",
    "    31.1802,\n",
    "    37.7179,\n",
    "    40.4202,\n",
    "    51.2069,\n",
    "    31.8872,\n",
    "    40.9783,\n",
    "    43.7725,\n",
    "    55.5586,\n",
    "    33.8509,\n",
    "    42.0764,\n",
    "    45.6423,\n",
    "    59.7668,\n",
    "    35.1919,\n",
    "    44.3197,\n",
    "    47.9137,\n",
    "]\n",
    "index = pd.date_range(start=\"2005\", end=\"2010-Q4\", freq=\"QS-OCT\")\n",
    "aust = pd.Series(data, index)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Simple Exponential Smoothing\n",
    "Lets use Simple Exponential Smoothing to forecast the below oil data."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2017-12-07T12:39:15.189907Z",
     "start_time": "2017-12-07T12:39:15.022229Z"
    }
   },
   "outputs": [],
   "source": [
    "ax = oildata.plot()\n",
    "ax.set_xlabel(\"Year\")\n",
    "ax.set_ylabel(\"Oil (millions of tonnes)\")\n",
    "print(\"Figure 7.1: Oil production in Saudi Arabia from 1996 to 2007.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Here we run three variants of simple exponential smoothing:\n",
    "1. In ```fit1``` we do not use the auto optimization but instead choose to explicitly provide the model with the $\\alpha=0.2$ parameter\n",
    "2. In ```fit2``` as above we choose an $\\alpha=0.6$\n",
    "3. In ```fit3``` we allow statsmodels to automatically find an optimized $\\alpha$ value for us. This is the recommended approach."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2017-12-07T12:39:15.785068Z",
     "start_time": "2017-12-07T12:39:15.191930Z"
    }
   },
   "outputs": [],
   "source": [
    "fit1 = SimpleExpSmoothing(oildata, initialization_method=\"heuristic\").fit(\n",
    "    smoothing_level=0.2, optimized=False\n",
    ")\n",
    "fcast1 = fit1.forecast(3).rename(r\"$\\alpha=0.2$\")\n",
    "fit2 = SimpleExpSmoothing(oildata, initialization_method=\"heuristic\").fit(\n",
    "    smoothing_level=0.6, optimized=False\n",
    ")\n",
    "fcast2 = fit2.forecast(3).rename(r\"$\\alpha=0.6$\")\n",
    "fit3 = SimpleExpSmoothing(oildata, initialization_method=\"estimated\").fit()\n",
    "fcast3 = fit3.forecast(3).rename(r\"$\\alpha=%s$\" % fit3.model.params[\"smoothing_level\"])\n",
    "\n",
    "plt.figure(figsize=(12, 8))\n",
    "plt.plot(oildata, marker=\"o\", color=\"black\")\n",
    "plt.plot(fit1.fittedvalues, marker=\"o\", color=\"blue\")\n",
    "(line1,) = plt.plot(fcast1, marker=\"o\", color=\"blue\")\n",
    "plt.plot(fit2.fittedvalues, marker=\"o\", color=\"red\")\n",
    "(line2,) = plt.plot(fcast2, marker=\"o\", color=\"red\")\n",
    "plt.plot(fit3.fittedvalues, marker=\"o\", color=\"green\")\n",
    "(line3,) = plt.plot(fcast3, marker=\"o\", color=\"green\")\n",
    "plt.legend([line1, line2, line3], [fcast1.name, fcast2.name, fcast3.name])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Holt's Method\n",
    "\n",
    "Lets take a look at another example.\n",
    "This time we use air pollution data and the Holt's Method.\n",
    "We will fit three examples again.\n",
    "1. In ```fit1``` we again choose not to use the optimizer and provide explicit values for $\\alpha=0.8$ and $\\beta=0.2$\n",
    "2. In ```fit2``` we do the same as in ```fit1``` but choose to use an exponential model rather than a Holt's additive model.\n",
    "3. In ```fit3``` we used a damped versions of the Holt's additive model but allow the dampening parameter $\\phi$ to be optimized while fixing the values for $\\alpha=0.8$ and $\\beta=0.2$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2017-12-07T12:39:16.114361Z",
     "start_time": "2017-12-07T12:39:15.786542Z"
    }
   },
   "outputs": [],
   "source": [
    "fit1 = Holt(air, initialization_method=\"estimated\").fit(\n",
    "    smoothing_level=0.8, smoothing_trend=0.2, optimized=False\n",
    ")\n",
    "fcast1 = fit1.forecast(5).rename(\"Holt's linear trend\")\n",
    "fit2 = Holt(air, exponential=True, initialization_method=\"estimated\").fit(\n",
    "    smoothing_level=0.8, smoothing_trend=0.2, optimized=False\n",
    ")\n",
    "fcast2 = fit2.forecast(5).rename(\"Exponential trend\")\n",
    "fit3 = Holt(air, damped_trend=True, initialization_method=\"estimated\").fit(\n",
    "    smoothing_level=0.8, smoothing_trend=0.2\n",
    ")\n",
    "fcast3 = fit3.forecast(5).rename(\"Additive damped trend\")\n",
    "\n",
    "plt.figure(figsize=(12, 8))\n",
    "plt.plot(air, marker=\"o\", color=\"black\")\n",
    "plt.plot(fit1.fittedvalues, color=\"blue\")\n",
    "(line1,) = plt.plot(fcast1, marker=\"o\", color=\"blue\")\n",
    "plt.plot(fit2.fittedvalues, color=\"red\")\n",
    "(line2,) = plt.plot(fcast2, marker=\"o\", color=\"red\")\n",
    "plt.plot(fit3.fittedvalues, color=\"green\")\n",
    "(line3,) = plt.plot(fcast3, marker=\"o\", color=\"green\")\n",
    "plt.legend([line1, line2, line3], [fcast1.name, fcast2.name, fcast3.name])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Seasonally adjusted data\n",
    "Lets look at some seasonally adjusted livestock data. We fit five Holt's models.\n",
    "The below table allows us to compare results when we use exponential versus additive and damped versus non-damped.\n",
    " \n",
    "Note: ```fit4``` does not allow the parameter $\\phi$ to be optimized by providing a fixed value of $\\phi=0.98$"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2017-12-07T12:39:16.605618Z",
     "start_time": "2017-12-07T12:39:16.116424Z"
    }
   },
   "outputs": [],
   "source": [
    "fit1 = SimpleExpSmoothing(livestock2, initialization_method=\"estimated\").fit()\n",
    "fit2 = Holt(livestock2, initialization_method=\"estimated\").fit()\n",
    "fit3 = Holt(livestock2, exponential=True, initialization_method=\"estimated\").fit()\n",
    "fit4 = Holt(livestock2, damped_trend=True, initialization_method=\"estimated\").fit(\n",
    "    damping_trend=0.98\n",
    ")\n",
    "fit5 = Holt(\n",
    "    livestock2, exponential=True, damped_trend=True, initialization_method=\"estimated\"\n",
    ").fit()\n",
    "params = [\n",
    "    \"smoothing_level\",\n",
    "    \"smoothing_trend\",\n",
    "    \"damping_trend\",\n",
    "    \"initial_level\",\n",
    "    \"initial_trend\",\n",
    "]\n",
    "results = pd.DataFrame(\n",
    "    index=[r\"$\\alpha$\", r\"$\\beta$\", r\"$\\phi$\", r\"$l_0$\", \"$b_0$\", \"SSE\"],\n",
    "    columns=[\"SES\", \"Holt's\", \"Exponential\", \"Additive\", \"Multiplicative\"],\n",
    ")\n",
    "results[\"SES\"] = [fit1.params[p] for p in params] + [fit1.sse]\n",
    "results[\"Holt's\"] = [fit2.params[p] for p in params] + [fit2.sse]\n",
    "results[\"Exponential\"] = [fit3.params[p] for p in params] + [fit3.sse]\n",
    "results[\"Additive\"] = [fit4.params[p] for p in params] + [fit4.sse]\n",
    "results[\"Multiplicative\"] = [fit5.params[p] for p in params] + [fit5.sse]\n",
    "results"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Plots of Seasonally Adjusted Data\n",
    "The following plots allow us to evaluate the level and slope/trend components of the above table's fits."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2017-12-07T12:39:17.105928Z",
     "start_time": "2017-12-07T12:39:16.607306Z"
    }
   },
   "outputs": [],
   "source": [
    "for fit in [fit2, fit4]:\n",
    "    pd.DataFrame(np.c_[fit.level, fit.trend]).rename(\n",
    "        columns={0: \"level\", 1: \"slope\"}\n",
    "    ).plot(subplots=True)\n",
    "plt.show()\n",
    "print(\n",
    "    \"Figure 7.4: Level and slope components for Holt’s linear trend method and the additive damped trend method.\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Comparison\n",
    "Here we plot a comparison Simple Exponential Smoothing and Holt's Methods for various additive, exponential and damped combinations. All of the models parameters will be optimized by statsmodels."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2017-12-07T12:39:18.038995Z",
     "start_time": "2017-12-07T12:39:17.108323Z"
    }
   },
   "outputs": [],
   "source": [
    "fit1 = SimpleExpSmoothing(livestock2, initialization_method=\"estimated\").fit()\n",
    "fcast1 = fit1.forecast(9).rename(\"SES\")\n",
    "fit2 = Holt(livestock2, initialization_method=\"estimated\").fit()\n",
    "fcast2 = fit2.forecast(9).rename(\"Holt's\")\n",
    "fit3 = Holt(livestock2, exponential=True, initialization_method=\"estimated\").fit()\n",
    "fcast3 = fit3.forecast(9).rename(\"Exponential\")\n",
    "fit4 = Holt(livestock2, damped_trend=True, initialization_method=\"estimated\").fit(\n",
    "    damping_trend=0.98\n",
    ")\n",
    "fcast4 = fit4.forecast(9).rename(\"Additive Damped\")\n",
    "fit5 = Holt(\n",
    "    livestock2, exponential=True, damped_trend=True, initialization_method=\"estimated\"\n",
    ").fit()\n",
    "fcast5 = fit5.forecast(9).rename(\"Multiplicative Damped\")\n",
    "\n",
    "ax = livestock2.plot(color=\"black\", marker=\"o\", figsize=(12, 8))\n",
    "livestock3.plot(ax=ax, color=\"black\", marker=\"o\", legend=False)\n",
    "fcast1.plot(ax=ax, color=\"red\", legend=True)\n",
    "fcast2.plot(ax=ax, color=\"green\", legend=True)\n",
    "fcast3.plot(ax=ax, color=\"blue\", legend=True)\n",
    "fcast4.plot(ax=ax, color=\"cyan\", legend=True)\n",
    "fcast5.plot(ax=ax, color=\"magenta\", legend=True)\n",
    "ax.set_ylabel(\"Livestock, sheep in Asia (millions)\")\n",
    "plt.show()\n",
    "print(\n",
    "    \"Figure 7.5: Forecasting livestock, sheep in Asia: comparing forecasting performance of non-seasonal methods.\"\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "ExecuteTime": {
     "end_time": "2017-10-05T09:40:15.958575Z",
     "start_time": "2017-10-05T09:40:15.615Z"
    }
   },
   "source": [
    "## Holt's Winters Seasonal\n",
    "Finally we are able to run full Holt's Winters Seasonal Exponential Smoothing  including a trend component and a seasonal component.\n",
    "statsmodels allows for all the combinations including as shown in the examples below:\n",
    "1. ```fit1``` additive trend, additive seasonal of period ```season_length=4``` and the use of a Box-Cox transformation.\n",
    "1. ```fit2``` additive trend, multiplicative seasonal of period ```season_length=4``` and the use of a Box-Cox transformation..\n",
    "1. ```fit3``` additive damped trend, additive seasonal of period ```season_length=4``` and the use of a Box-Cox transformation.\n",
    "1. ```fit4``` additive damped trend, multiplicative seasonal of period ```season_length=4``` and the use of a Box-Cox transformation.\n",
    "\n",
    "The plot shows the results and forecast for ```fit1``` and ```fit2```.\n",
    "The table allows us to compare the results and parameterizations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2017-12-07T12:39:28.375871Z",
     "start_time": "2017-12-07T12:39:18.040674Z"
    }
   },
   "outputs": [],
   "source": [
    "fit1 = ExponentialSmoothing(\n",
    "    aust,\n",
    "    seasonal_periods=4,\n",
    "    trend=\"add\",\n",
    "    seasonal=\"add\",\n",
    "    use_boxcox=True,\n",
    "    initialization_method=\"estimated\",\n",
    ").fit()\n",
    "fit2 = ExponentialSmoothing(\n",
    "    aust,\n",
    "    seasonal_periods=4,\n",
    "    trend=\"add\",\n",
    "    seasonal=\"mul\",\n",
    "    use_boxcox=True,\n",
    "    initialization_method=\"estimated\",\n",
    ").fit()\n",
    "fit3 = ExponentialSmoothing(\n",
    "    aust,\n",
    "    seasonal_periods=4,\n",
    "    trend=\"add\",\n",
    "    seasonal=\"add\",\n",
    "    damped_trend=True,\n",
    "    use_boxcox=True,\n",
    "    initialization_method=\"estimated\",\n",
    ").fit()\n",
    "fit4 = ExponentialSmoothing(\n",
    "    aust,\n",
    "    seasonal_periods=4,\n",
    "    trend=\"add\",\n",
    "    seasonal=\"mul\",\n",
    "    damped_trend=True,\n",
    "    use_boxcox=True,\n",
    "    initialization_method=\"estimated\",\n",
    ").fit()\n",
    "results = pd.DataFrame(\n",
    "    index=[r\"$\\alpha$\", r\"$\\beta$\", r\"$\\phi$\", r\"$\\gamma$\", r\"$l_0$\", \"$b_0$\", \"SSE\"]\n",
    ")\n",
    "params = [\n",
    "    \"smoothing_level\",\n",
    "    \"smoothing_trend\",\n",
    "    \"damping_trend\",\n",
    "    \"smoothing_seasonal\",\n",
    "    \"initial_level\",\n",
    "    \"initial_trend\",\n",
    "]\n",
    "results[\"Additive\"] = [fit1.params[p] for p in params] + [fit1.sse]\n",
    "results[\"Multiplicative\"] = [fit2.params[p] for p in params] + [fit2.sse]\n",
    "results[\"Additive Dam\"] = [fit3.params[p] for p in params] + [fit3.sse]\n",
    "results[\"Multiplica Dam\"] = [fit4.params[p] for p in params] + [fit4.sse]\n",
    "\n",
    "ax = aust.plot(\n",
    "    figsize=(10, 6),\n",
    "    marker=\"o\",\n",
    "    color=\"black\",\n",
    "    title=\"Forecasts from Holt-Winters' multiplicative method\",\n",
    ")\n",
    "ax.set_ylabel(\"International visitor night in Australia (millions)\")\n",
    "ax.set_xlabel(\"Year\")\n",
    "fit1.fittedvalues.plot(ax=ax, style=\"--\", color=\"red\")\n",
    "fit2.fittedvalues.plot(ax=ax, style=\"--\", color=\"green\")\n",
    "\n",
    "fit1.forecast(8).rename(\"Holt-Winters (add-add-seasonal)\").plot(\n",
    "    ax=ax, style=\"--\", marker=\"o\", color=\"red\", legend=True\n",
    ")\n",
    "fit2.forecast(8).rename(\"Holt-Winters (add-mul-seasonal)\").plot(\n",
    "    ax=ax, style=\"--\", marker=\"o\", color=\"green\", legend=True\n",
    ")\n",
    "\n",
    "plt.show()\n",
    "print(\n",
    "    \"Figure 7.6: Forecasting international visitor nights in Australia using Holt-Winters method with both additive and multiplicative seasonality.\"\n",
    ")\n",
    "\n",
    "results"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### The Internals\n",
    "It is possible to get at the internals of the Exponential Smoothing models. \n",
    "\n",
    "Here we show some tables that allow you to view side by side the original values $y_t$, the level $l_t$, the trend $b_t$, the season $s_t$ and the fitted values $\\hat{y}_t$. Note that these values only have meaningful values in the space of your original data if the fit is performed without a Box-Cox transformation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fit1 = ExponentialSmoothing(\n",
    "    aust,\n",
    "    seasonal_periods=4,\n",
    "    trend=\"add\",\n",
    "    seasonal=\"add\",\n",
    "    initialization_method=\"estimated\",\n",
    ").fit()\n",
    "fit2 = ExponentialSmoothing(\n",
    "    aust,\n",
    "    seasonal_periods=4,\n",
    "    trend=\"add\",\n",
    "    seasonal=\"mul\",\n",
    "    initialization_method=\"estimated\",\n",
    ").fit()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2017-12-07T12:39:28.399765Z",
     "start_time": "2017-12-07T12:39:28.377215Z"
    }
   },
   "outputs": [],
   "source": [
    "df = pd.DataFrame(\n",
    "    np.c_[aust, fit1.level, fit1.trend, fit1.season, fit1.fittedvalues],\n",
    "    columns=[r\"$y_t$\", r\"$l_t$\", r\"$b_t$\", r\"$s_t$\", r\"$\\hat{y}_t$\"],\n",
    "    index=aust.index,\n",
    ")\n",
    "forecasts = fit1.forecast(8).rename(r\"$\\hat{y}_t$\").to_frame()\n",
    "df = pd.concat([df, forecasts], axis=0, sort=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2017-12-07T12:39:28.574783Z",
     "start_time": "2017-12-07T12:39:28.401234Z"
    }
   },
   "outputs": [],
   "source": [
    "df = pd.DataFrame(\n",
    "    np.c_[aust, fit2.level, fit2.trend, fit2.season, fit2.fittedvalues],\n",
    "    columns=[r\"$y_t$\", r\"$l_t$\", r\"$b_t$\", r\"$s_t$\", r\"$\\hat{y}_t$\"],\n",
    "    index=aust.index,\n",
    ")\n",
    "forecasts = fit2.forecast(8).rename(r\"$\\hat{y}_t$\").to_frame()\n",
    "df = pd.concat([df, forecasts], axis=0, sort=True)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Finally lets look at the levels, slopes/trends and seasonal components of the models."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "ExecuteTime": {
     "end_time": "2017-12-07T12:39:29.636548Z",
     "start_time": "2017-12-07T12:39:28.576279Z"
    }
   },
   "outputs": [],
   "source": [
    "states1 = pd.DataFrame(\n",
    "    np.c_[fit1.level, fit1.trend, fit1.season],\n",
    "    columns=[\"level\", \"slope\", \"seasonal\"],\n",
    "    index=aust.index,\n",
    ")\n",
    "states2 = pd.DataFrame(\n",
    "    np.c_[fit2.level, fit2.trend, fit2.season],\n",
    "    columns=[\"level\", \"slope\", \"seasonal\"],\n",
    "    index=aust.index,\n",
    ")\n",
    "fig, [[ax1, ax4], [ax2, ax5], [ax3, ax6]] = plt.subplots(3, 2, figsize=(12, 8))\n",
    "states1[[\"level\"]].plot(ax=ax1)\n",
    "states1[[\"slope\"]].plot(ax=ax2)\n",
    "states1[[\"seasonal\"]].plot(ax=ax3)\n",
    "states2[[\"level\"]].plot(ax=ax4)\n",
    "states2[[\"slope\"]].plot(ax=ax5)\n",
    "states2[[\"seasonal\"]].plot(ax=ax6)\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Simulations and Confidence Intervals\n",
    "\n",
    "By using a state space formulation, we can perform simulations of future values. The mathematical details are described in Hyndman and Athanasopoulos [2] and in the documentation of `HoltWintersResults.simulate`.\n",
    "\n",
    "Similar to the example in [2], we use the model with additive trend, multiplicative seasonality, and multiplicative error. We simulate up to 8 steps into the future, and perform 1000 simulations. As can be seen in the below figure, the simulations match the forecast values quite well.\n",
    "\n",
    "[2] [Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles and practice, 2nd edition. OTexts, 2018.](https://otexts.com/fpp2/ets.html)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fit = ExponentialSmoothing(\n",
    "    aust,\n",
    "    seasonal_periods=4,\n",
    "    trend=\"add\",\n",
    "    seasonal=\"mul\",\n",
    "    initialization_method=\"estimated\",\n",
    ").fit()\n",
    "simulations = fit.simulate(8, repetitions=100, error=\"mul\")\n",
    "\n",
    "ax = aust.plot(\n",
    "    figsize=(10, 6),\n",
    "    marker=\"o\",\n",
    "    color=\"black\",\n",
    "    title=\"Forecasts and simulations from Holt-Winters' multiplicative method\",\n",
    ")\n",
    "ax.set_ylabel(\"International visitor night in Australia (millions)\")\n",
    "ax.set_xlabel(\"Year\")\n",
    "fit.fittedvalues.plot(ax=ax, style=\"--\", color=\"green\")\n",
    "simulations.plot(ax=ax, style=\"-\", alpha=0.05, color=\"grey\", legend=False)\n",
    "fit.forecast(8).rename(\"Holt-Winters (add-mul-seasonal)\").plot(\n",
    "    ax=ax, style=\"--\", marker=\"o\", color=\"green\", legend=True\n",
    ")\n",
    "plt.show()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Simulations can also be started at different points in time, and there are multiple options for choosing the random noise."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "fit = ExponentialSmoothing(\n",
    "    aust,\n",
    "    seasonal_periods=4,\n",
    "    trend=\"add\",\n",
    "    seasonal=\"mul\",\n",
    "    initialization_method=\"estimated\",\n",
    ").fit()\n",
    "simulations = fit.simulate(\n",
    "    16, anchor=\"2009-01-01\", repetitions=100, error=\"mul\", random_errors=\"bootstrap\"\n",
    ")\n",
    "\n",
    "ax = aust.plot(\n",
    "    figsize=(10, 6),\n",
    "    marker=\"o\",\n",
    "    color=\"black\",\n",
    "    title=\"Forecasts and simulations from Holt-Winters' multiplicative method\",\n",
    ")\n",
    "ax.set_ylabel(\"International visitor night in Australia (millions)\")\n",
    "ax.set_xlabel(\"Year\")\n",
    "fit.fittedvalues.plot(ax=ax, style=\"--\", color=\"green\")\n",
    "simulations.plot(ax=ax, style=\"-\", alpha=0.05, color=\"grey\", legend=False)\n",
    "fit.forecast(8).rename(\"Holt-Winters (add-mul-seasonal)\").plot(\n",
    "    ax=ax, style=\"--\", marker=\"o\", color=\"green\", legend=True\n",
    ")\n",
    "plt.show()"
   ]
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "hide_input": false,
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.12.2"
  },
  "latex_envs": {
   "LaTeX_envs_menu_present": true,
   "autocomplete": true,
   "bibliofile": "biblio.bib",
   "cite_by": "apalike",
   "current_citInitial": 1,
   "eqLabelWithNumbers": true,
   "eqNumInitial": 1,
   "hotkeys": {
    "equation": "Ctrl-E",
    "itemize": "Ctrl-I"
   },
   "labels_anchors": false,
   "latex_user_defs": false,
   "report_style_numbering": false,
   "user_envs_cfg": false
  },
  "toc": {
   "colors": {
    "hover_highlight": "#DAA520",
    "navigate_num": "#000000",
    "navigate_text": "#333333",
    "running_highlight": "#FF0000",
    "selected_highlight": "#FFD700",
    "sidebar_border": "#EEEEEE",
    "wrapper_background": "#FFFFFF"
   },
   "moveMenuLeft": true,
   "nav_menu": {
    "height": "98px",
    "width": "252px"
   },
   "navigate_menu": true,
   "number_sections": false,
   "sideBar": true,
   "threshold": 4,
   "toc_cell": false,
   "toc_section_display": "block",
   "toc_window_display": true,
   "widenNotebook": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
