{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "block_hidden": true
   },
   "outputs": [],
   "source": [
    "%load_ext rpy2.ipython\n",
    "%matplotlib inline\n",
    "from fbprophet import Prophet\n",
    "import pandas as pd\n",
    "from matplotlib import pyplot as plt\n",
    "import logging\n",
    "logging.getLogger('fbprophet').setLevel(logging.ERROR)\n",
    "import warnings\n",
    "warnings.filterwarnings(\"ignore\")\n",
    "df = pd.read_csv('../examples/example_wp_log_peyton_manning.csv')\n",
    "m = Prophet()\n",
    "m.fit(df)\n",
    "future = m.make_future_dataframe(periods=366)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "block_hidden": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING:rpy2.rinterface_lib.callbacks:R[write to console]: Loading required package: Rcpp\n",
      "\n",
      "WARNING:rpy2.rinterface_lib.callbacks:R[write to console]: Loading required package: rlang\n",
      "\n",
      "WARNING:rpy2.rinterface_lib.callbacks:R[write to console]: Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "%%R\n",
    "library(prophet)\n",
    "df <- read.csv('../examples/example_wp_log_peyton_manning.csv')\n",
    "m <- prophet(df)\n",
    "future <- make_future_dataframe(m, periods=366)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Prophet includes functionality for time series cross validation to measure forecast error using historical data. This is done by selecting cutoff points in the history, and for each of them fitting the model using data only up to that cutoff point. We can then compare the forecasted values to the actual values. This figure illustrates a simulated historical forecast on the Peyton Manning dataset, where the model was fit to a initial history of 5 years, and a forecast was made on a one year horizon."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "input_hidden": true
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 70476 characters]\n",
      "text/plain": [
       "<Figure size 720x432 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from fbprophet.diagnostics import cross_validation\n",
    "df_cv = cross_validation(\n",
    "    m, '365 days', initial='1825 days', period='365 days')\n",
    "cutoff = df_cv['cutoff'].unique()[0]\n",
    "df_cv = df_cv[df_cv['cutoff'].values == cutoff]\n",
    "\n",
    "fig = plt.figure(facecolor='w', figsize=(10, 6))\n",
    "ax = fig.add_subplot(111)\n",
    "ax.plot(m.history['ds'].values, m.history['y'], 'k.')\n",
    "ax.plot(df_cv['ds'].values, df_cv['yhat'], ls='-', c='#0072B2')\n",
    "ax.fill_between(df_cv['ds'].values, df_cv['yhat_lower'],\n",
    "                df_cv['yhat_upper'], color='#0072B2',\n",
    "                alpha=0.2)\n",
    "ax.axvline(x=pd.to_datetime(cutoff), c='gray', lw=4, alpha=0.5)\n",
    "ax.set_ylabel('y')\n",
    "ax.set_xlabel('ds')\n",
    "ax.text(x=pd.to_datetime('2010-01-01'),y=12, s='Initial', color='black',\n",
    "       fontsize=16, fontweight='bold', alpha=0.8)\n",
    "ax.text(x=pd.to_datetime('2012-08-01'),y=12, s='Cutoff', color='black',\n",
    "       fontsize=16, fontweight='bold', alpha=0.8)\n",
    "ax.axvline(x=pd.to_datetime(cutoff) + pd.Timedelta('365 days'), c='gray', lw=4,\n",
    "           alpha=0.5, ls='--')\n",
    "ax.text(x=pd.to_datetime('2013-01-01'),y=6, s='Horizon', color='black',\n",
    "       fontsize=16, fontweight='bold', alpha=0.8);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "[The Prophet paper](https://peerj.com/preprints/3190.pdf) gives further description of simulated historical forecasts.\n",
    "\n",
    "This cross validation procedure can be done automatically for a range of historical cutoffs using the `cross_validation` function. We specify the forecast horizon (`horizon`), and then optionally the size of the initial training period (`initial`) and the spacing between cutoff dates (`period`). By default, the initial training period is set to three times the horizon, and cutoffs are made every half a horizon.\n",
    "\n",
    "The output of `cross_validation` is a dataframe with the true values `y` and the out-of-sample forecast values `yhat`, at each simulated forecast date and for each cutoff date. In particular, a forecast is made for every observed point between `cutoff` and `cutoff + horizon`. This dataframe can then be used to compute error measures of `yhat` vs. `y`.\n",
    "\n",
    "Here we do cross-validation to assess prediction performance on a horizon of 365 days, starting with 730 days of training data in the first cutoff and then making predictions every 180 days. On this 8 year time series, this corresponds to 11 total forecasts."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "output_hidden": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "WARNING:rpy2.rinterface_lib.callbacks:R[write to console]: Making 11 forecasts with cutoffs between 2010-02-15 and 2015-01-20\n",
      "\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "          ds        y     yhat yhat_lower yhat_upper     cutoff\n",
       "1 2010-02-16 8.242493 8.954992   8.423614   9.496403 2010-02-15\n",
       "2 2010-02-17 8.008033 8.721365   8.226481   9.219106 2010-02-15\n",
       "3 2010-02-18 8.045268 8.605072   8.103985   9.104483 2010-02-15\n",
       "4 2010-02-19 7.928766 8.526855   8.023088   9.042035 2010-02-15\n",
       "5 2010-02-20 7.745003 8.268741   7.757920   8.779416 2010-02-15\n",
       "6 2010-02-21 7.866339 8.599935   8.084956   9.060284 2010-02-15\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%%R\n",
    "df.cv <- cross_validation(m, initial = 730, period = 180, horizon = 365, units = 'days')\n",
    "head(df.cv)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>ds</th>\n",
       "      <th>yhat</th>\n",
       "      <th>yhat_lower</th>\n",
       "      <th>yhat_upper</th>\n",
       "      <th>y</th>\n",
       "      <th>cutoff</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2010-02-16</td>\n",
       "      <td>8.956572</td>\n",
       "      <td>8.460049</td>\n",
       "      <td>9.460400</td>\n",
       "      <td>8.242493</td>\n",
       "      <td>2010-02-15</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2010-02-17</td>\n",
       "      <td>8.723004</td>\n",
       "      <td>8.200557</td>\n",
       "      <td>9.236561</td>\n",
       "      <td>8.008033</td>\n",
       "      <td>2010-02-15</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2010-02-18</td>\n",
       "      <td>8.606823</td>\n",
       "      <td>8.070835</td>\n",
       "      <td>9.123754</td>\n",
       "      <td>8.045268</td>\n",
       "      <td>2010-02-15</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2010-02-19</td>\n",
       "      <td>8.528688</td>\n",
       "      <td>8.034782</td>\n",
       "      <td>9.042712</td>\n",
       "      <td>7.928766</td>\n",
       "      <td>2010-02-15</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2010-02-20</td>\n",
       "      <td>8.270706</td>\n",
       "      <td>7.754891</td>\n",
       "      <td>8.739012</td>\n",
       "      <td>7.745003</td>\n",
       "      <td>2010-02-15</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          ds      yhat  yhat_lower  yhat_upper         y     cutoff\n",
       "0 2010-02-16  8.956572    8.460049    9.460400  8.242493 2010-02-15\n",
       "1 2010-02-17  8.723004    8.200557    9.236561  8.008033 2010-02-15\n",
       "2 2010-02-18  8.606823    8.070835    9.123754  8.045268 2010-02-15\n",
       "3 2010-02-19  8.528688    8.034782    9.042712  7.928766 2010-02-15\n",
       "4 2010-02-20  8.270706    7.754891    8.739012  7.745003 2010-02-15"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from fbprophet.diagnostics import cross_validation\n",
    "df_cv = cross_validation(m, initial='730 days', period='180 days', horizon = '365 days')\n",
    "df_cv.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In R, the argument `units` must be a type accepted by `as.difftime`, which is weeks or shorter. In Python, the string for `initial`, `period`, and `horizon` should be in the format used by Pandas Timedelta, which accepts units of days or shorter.\n",
    "\n",
    "The `performance_metrics` utility can be used to compute some useful statistics of the prediction performance (`yhat`, `yhat_lower`, and `yhat_upper` compared to `y`), as a function of the distance from the cutoff (how far into the future the prediction was). The statistics computed are mean squared error (MSE), root mean squared error (RMSE), mean absolute error (MAE), mean absolute percent error (MAPE), and coverage of the `yhat_lower` and `yhat_upper` estimates. These are computed on a rolling window of the predictions in `df_cv` after sorting by horizon (`ds` minus `cutoff`). By default 10% of the predictions will be included in each window, but this can be changed with the `rolling_window` argument."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "output_hidden": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "  horizon       mse      rmse       mae       mape  coverage\n",
       "1 37 days 0.4971086 0.7050593 0.5075009 0.05882459 0.6765646\n",
       "2 38 days 0.5029463 0.7091870 0.5125229 0.05940706 0.6765646\n",
       "3 39 days 0.5252677 0.7247535 0.5186555 0.06001158 0.6751942\n",
       "4 40 days 0.5326181 0.7298069 0.5215775 0.06032500 0.6788488\n",
       "5 41 days 0.5401377 0.7349406 0.5226521 0.06041353 0.6838739\n",
       "6 42 days 0.5438937 0.7374915 0.5230473 0.06043453 0.6891275\n"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%%R\n",
    "df.p <- performance_metrics(df.cv)\n",
    "head(df.p)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>horizon</th>\n",
       "      <th>mse</th>\n",
       "      <th>rmse</th>\n",
       "      <th>mae</th>\n",
       "      <th>mape</th>\n",
       "      <th>coverage</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>37 days</td>\n",
       "      <td>0.495378</td>\n",
       "      <td>0.703831</td>\n",
       "      <td>0.505713</td>\n",
       "      <td>0.058593</td>\n",
       "      <td>0.680448</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>38 days</td>\n",
       "      <td>0.501134</td>\n",
       "      <td>0.707908</td>\n",
       "      <td>0.510680</td>\n",
       "      <td>0.059169</td>\n",
       "      <td>0.679077</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>39 days</td>\n",
       "      <td>0.523334</td>\n",
       "      <td>0.723418</td>\n",
       "      <td>0.516755</td>\n",
       "      <td>0.059766</td>\n",
       "      <td>0.677707</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>40 days</td>\n",
       "      <td>0.530625</td>\n",
       "      <td>0.728440</td>\n",
       "      <td>0.519645</td>\n",
       "      <td>0.060075</td>\n",
       "      <td>0.678849</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>41 days</td>\n",
       "      <td>0.538117</td>\n",
       "      <td>0.733565</td>\n",
       "      <td>0.520663</td>\n",
       "      <td>0.060156</td>\n",
       "      <td>0.686386</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "  horizon       mse      rmse       mae      mape  coverage\n",
       "0 37 days  0.495378  0.703831  0.505713  0.058593  0.680448\n",
       "1 38 days  0.501134  0.707908  0.510680  0.059169  0.679077\n",
       "2 39 days  0.523334  0.723418  0.516755  0.059766  0.677707\n",
       "3 40 days  0.530625  0.728440  0.519645  0.060075  0.678849\n",
       "4 41 days  0.538117  0.733565  0.520663  0.060156  0.686386"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from fbprophet.diagnostics import performance_metrics\n",
    "df_p = performance_metrics(df_cv)\n",
    "df_p.head()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Cross validation performance metrics can be visualized with `plot_cross_validation_metric`, here shown for MAPE. Dots show the absolute percent error for each prediction in `df_cv`. The blue line shows the MAPE, where the mean is taken over a rolling window of the dots. We see for this forecast that errors around 5% are typical for predictions one month into the future, and that errors increase up to around 11% for predictions that are a year out."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "output_hidden": true
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 91292 characters]\n"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%%R -w 10 -h 6 -u in\n",
    "plot_cross_validation_metric(df.cv, metric = 'mape')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 89692 characters]\n",
      "text/plain": [
       "<Figure size 720x432 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from fbprophet.plot import plot_cross_validation_metric\n",
    "fig = plot_cross_validation_metric(df_cv, metric='mape')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The size of the rolling window in the figure can be changed with the optional argument `rolling_window`, which specifies the proportion of forecasts to use in each rolling window. The default is 0.1, corresponding to 10% of rows from `df_cv` included in each window; increasing this will lead to a smoother average curve in the figure.\n",
    "\n",
    "The `initial` period should be long enough to capture all of the components of the model, in particular seasonalities and extra regressors: at least a year for yearly seasonality, at least a week for weekly seasonality, etc."
   ]
  }
 ],
 "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.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
