{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "block_hidden": true
   },
   "outputs": [],
   "source": [
    "%load_ext rpy2.ipython\n",
    "%matplotlib inline\n",
    "\n",
    "from prophet import Prophet\n",
    "from matplotlib import pyplot as plt\n",
    "import pandas as pd\n",
    "import logging\n",
    "import warnings\n",
    "\n",
    "logging.getLogger('prophet').setLevel(logging.ERROR)\n",
    "warnings.filterwarnings(\"ignore\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "block_hidden": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:numexpr.utils:NumExpr defaulting to 8 threads.\n"
     ]
    }
   ],
   "source": [
    "df = pd.read_csv('https://raw.githubusercontent.com/facebook/prophet/main/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": [
      "R[write to console]: Loading required package: Rcpp\n",
      "\n",
      "R[write to console]: Loading required package: rlang\n",
      "\n",
      "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('https://raw.githubusercontent.com/facebook/prophet/main/examples/example_wp_log_peyton_manning.csv')\n",
    "m <- prophet(df)\n",
    "future <- make_future_dataframe(m, periods=366)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Modeling Holidays and Special Events\n",
    "If you have holidays or other recurring events that you'd like to model, you must create a dataframe for them. It has two columns (`holiday` and `ds`) and a row for each occurrence of the holiday. It must include all occurrences of the holiday, both in the past (back as far as the historical data go) and in the future (out as far as the forecast is being made). If they won't repeat in the future, Prophet will model them and then not include them in the forecast.\n",
    "\n",
    "You can also include columns `lower_window` and `upper_window` which extend the holiday out to `[lower_window, upper_window]` days around the date. For instance, if you wanted to include Christmas Eve in addition to Christmas you'd include `lower_window=-1,upper_window=0`. If you wanted to use Black Friday in addition to Thanksgiving, you'd include `lower_window=0,upper_window=1`. You can also include a column `prior_scale` to set the prior scale separately for each holiday, as described below.\n",
    "\n",
    "Here we create a dataframe that includes the dates of all of Peyton Manning's playoff appearances:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "output_hidden": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "R[write to console]: \n",
      "Attaching package: ‘dplyr’\n",
      "\n",
      "\n",
      "R[write to console]: The following objects are masked from ‘package:stats’:\n",
      "\n",
      "    filter, lag\n",
      "\n",
      "\n",
      "R[write to console]: The following objects are masked from ‘package:base’:\n",
      "\n",
      "    intersect, setdiff, setequal, union\n",
      "\n",
      "\n"
     ]
    }
   ],
   "source": [
    "%%R\n",
    "library(dplyr)\n",
    "playoffs <- data_frame(\n",
    "  holiday = 'playoff',\n",
    "  ds = as.Date(c('2008-01-13', '2009-01-03', '2010-01-16',\n",
    "                 '2010-01-24', '2010-02-07', '2011-01-08',\n",
    "                 '2013-01-12', '2014-01-12', '2014-01-19',\n",
    "                 '2014-02-02', '2015-01-11', '2016-01-17',\n",
    "                 '2016-01-24', '2016-02-07')),\n",
    "  lower_window = 0,\n",
    "  upper_window = 1\n",
    ")\n",
    "superbowls <- data_frame(\n",
    "  holiday = 'superbowl',\n",
    "  ds = as.Date(c('2010-02-07', '2014-02-02', '2016-02-07')),\n",
    "  lower_window = 0,\n",
    "  upper_window = 1\n",
    ")\n",
    "holidays <- bind_rows(playoffs, superbowls)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "playoffs = pd.DataFrame({\n",
    "  'holiday': 'playoff',\n",
    "  'ds': pd.to_datetime(['2008-01-13', '2009-01-03', '2010-01-16',\n",
    "                        '2010-01-24', '2010-02-07', '2011-01-08',\n",
    "                        '2013-01-12', '2014-01-12', '2014-01-19',\n",
    "                        '2014-02-02', '2015-01-11', '2016-01-17',\n",
    "                        '2016-01-24', '2016-02-07']),\n",
    "  'lower_window': 0,\n",
    "  'upper_window': 1,\n",
    "})\n",
    "superbowls = pd.DataFrame({\n",
    "  'holiday': 'superbowl',\n",
    "  'ds': pd.to_datetime(['2010-02-07', '2014-02-02', '2016-02-07']),\n",
    "  'lower_window': 0,\n",
    "  'upper_window': 1,\n",
    "})\n",
    "holidays = pd.concat((playoffs, superbowls))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Above we have included the superbowl days as both playoff games and superbowl games. This means that the superbowl effect will be an additional additive bonus on top of the playoff effect.\n",
    "\n",
    "Once the table is created, holiday effects are included in the forecast by passing them in with the `holidays` argument. Here we do it with the Peyton Manning data from the [Quickstart](https://facebook.github.io/prophet/docs/quick_start.html):"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "output_hidden": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "R[write to console]: Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "%%R\n",
    "m <- prophet(df, holidays = holidays)\n",
    "forecast <- predict(m, future)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "m = Prophet(holidays=holidays)\n",
    "forecast = m.fit(df).predict(future)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The holiday effect can be seen in the `forecast` dataframe:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "output_hidden": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "           ds  playoff superbowl\n",
      "17 2014-02-02 1.219646  1.211218\n",
      "18 2014-02-03 1.913081  1.359259\n",
      "19 2015-01-11 1.219646  0.000000\n",
      "20 2015-01-12 1.913081  0.000000\n",
      "21 2016-01-17 1.219646  0.000000\n",
      "22 2016-01-18 1.913081  0.000000\n",
      "23 2016-01-24 1.219646  0.000000\n",
      "24 2016-01-25 1.913081  0.000000\n",
      "25 2016-02-07 1.219646  1.211218\n",
      "26 2016-02-08 1.913081  1.359259\n"
     ]
    }
   ],
   "source": [
    "%%R\n",
    "forecast %>% \n",
    "  select(ds, playoff, superbowl) %>% \n",
    "  filter(abs(playoff + superbowl) > 0) %>%\n",
    "  tail(10)"
   ]
  },
  {
   "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>playoff</th>\n",
       "      <th>superbowl</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2190</th>\n",
       "      <td>2014-02-02</td>\n",
       "      <td>1.223965</td>\n",
       "      <td>1.201517</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2191</th>\n",
       "      <td>2014-02-03</td>\n",
       "      <td>1.901742</td>\n",
       "      <td>1.460471</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2532</th>\n",
       "      <td>2015-01-11</td>\n",
       "      <td>1.223965</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2533</th>\n",
       "      <td>2015-01-12</td>\n",
       "      <td>1.901742</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2901</th>\n",
       "      <td>2016-01-17</td>\n",
       "      <td>1.223965</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2902</th>\n",
       "      <td>2016-01-18</td>\n",
       "      <td>1.901742</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2908</th>\n",
       "      <td>2016-01-24</td>\n",
       "      <td>1.223965</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2909</th>\n",
       "      <td>2016-01-25</td>\n",
       "      <td>1.901742</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2922</th>\n",
       "      <td>2016-02-07</td>\n",
       "      <td>1.223965</td>\n",
       "      <td>1.201517</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2923</th>\n",
       "      <td>2016-02-08</td>\n",
       "      <td>1.901742</td>\n",
       "      <td>1.460471</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "             ds   playoff  superbowl\n",
       "2190 2014-02-02  1.223965   1.201517\n",
       "2191 2014-02-03  1.901742   1.460471\n",
       "2532 2015-01-11  1.223965   0.000000\n",
       "2533 2015-01-12  1.901742   0.000000\n",
       "2901 2016-01-17  1.223965   0.000000\n",
       "2902 2016-01-18  1.901742   0.000000\n",
       "2908 2016-01-24  1.223965   0.000000\n",
       "2909 2016-01-25  1.901742   0.000000\n",
       "2922 2016-02-07  1.223965   1.201517\n",
       "2923 2016-02-08  1.901742   1.460471"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "forecast[(forecast['playoff'] + forecast['superbowl']).abs() > 0][\n",
    "        ['ds', 'playoff', 'superbowl']][-10:]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The holiday effects will also show up in the components plot, where we see that there is a spike on the days around playoff appearances, with an especially large spike for the superbowl:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "output_hidden": true
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 69376 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%%R -w 9 -h 12 -u in\n",
    "prophet_plot_components(m, forecast)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 85048 characters]",
      "text/plain": [
       "<Figure size 648x864 with 4 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "fig = m.plot_components(forecast)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Individual holidays can be plotted using the `plot_forecast_component` function (imported from `prophet.plot` in Python) like `plot_forecast_component(m, forecast, 'superbowl')` to plot just the superbowl holiday component."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Built-in Country Holidays\n",
    "\n",
    "You can use a built-in collection of country-specific holidays using the `add_country_holidays` method (Python) or function (R). The name of the country is specified, and then major holidays for that country will be included in addition to any holidays that are specified via the `holidays` argument described above:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "output_hidden": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "R[write to console]: Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.\n",
      "\n"
     ]
    }
   ],
   "source": [
    "%%R\n",
    "m <- prophet(holidays = holidays)\n",
    "m <- add_country_holidays(m, country_name = 'US')\n",
    "m <- fit.prophet(m, df)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "output_hidden": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<prophet.forecaster.Prophet at 0x7f2a61da1850>"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "m = Prophet(holidays=holidays)\n",
    "m.add_country_holidays(country_name='US')\n",
    "m.fit(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can see which holidays were included by looking at the `train_holiday_names` (Python) or `train.holiday.names` (R) attribute of the model:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      " [1] \"playoff\"                     \"superbowl\"                  \n",
      " [3] \"New Year's Day\"              \"Martin Luther King Jr. Day\" \n",
      " [5] \"Washington's Birthday\"       \"Memorial Day\"               \n",
      " [7] \"Independence Day\"            \"Labor Day\"                  \n",
      " [9] \"Columbus Day\"                \"Veterans Day\"               \n",
      "[11] \"Veterans Day (Observed)\"     \"Thanksgiving\"               \n",
      "[13] \"Christmas Day\"               \"Independence Day (Observed)\"\n",
      "[15] \"Christmas Day (Observed)\"    \"New Year's Day (Observed)\"  \n"
     ]
    }
   ],
   "source": [
    "%%R\n",
    "m$train.holiday.names"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0                         playoff\n",
       "1                       superbowl\n",
       "2                  New Year's Day\n",
       "3      Martin Luther King Jr. Day\n",
       "4           Washington's Birthday\n",
       "5                    Memorial Day\n",
       "6                Independence Day\n",
       "7                       Labor Day\n",
       "8                    Columbus Day\n",
       "9                    Veterans Day\n",
       "10                   Thanksgiving\n",
       "11                  Christmas Day\n",
       "12       Christmas Day (Observed)\n",
       "13        Veterans Day (Observed)\n",
       "14    Independence Day (Observed)\n",
       "15      New Year's Day (Observed)\n",
       "dtype: object"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "m.train_holiday_names"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The holidays for each country are provided by the `holidays` package in Python. A list of available countries, and the country name to use, is available on their page: https://github.com/vacanza/python-holidays/.\n",
    "\n",
    "In Python, most holidays are computed deterministically and so are available for any date range; a warning will be raised if dates fall outside the range supported by that country. In R, holiday dates are computed for 1995 through 2044 and stored in the package as `data-raw/generated_holidays.csv`. If a wider date range is needed, this script can be used to replace that file with a different date range: https://github.com/facebook/prophet/blob/main/python/scripts/generate_holidays_file.py.\n",
    "\n",
    "As above, the country-level holidays will then show up in the components plot:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "output_hidden": true
   },
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 77040 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%%R -w 9 -h 12 -u in\n",
    "forecast <- predict(m, future)\n",
    "prophet_plot_components(m, forecast)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 89112 characters]",
      "text/plain": [
       "<Figure size 648x864 with 4 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "forecast = m.predict(future)\n",
    "fig = m.plot_components(forecast)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Holidays for subdivisions (Python)\n",
    "\n",
    "We can use the utility function `make_holidays_df` to easily create custom holidays DataFrames, e.g. for certain states, using data from the [holidays](https://pypi.org/project/holidays/) package. This can be passed directly to the `Prophet()` constructor."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "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>holiday</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>2019-01-26</td>\n",
       "      <td>Australia Day</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2019-01-28</td>\n",
       "      <td>Australia Day (Observed)</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>2019-04-25</td>\n",
       "      <td>Anzac Day</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2019-12-25</td>\n",
       "      <td>Christmas Day</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>2019-12-26</td>\n",
       "      <td>Boxing Day</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>2019-04-20</td>\n",
       "      <td>Easter Saturday</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>2019-04-21</td>\n",
       "      <td>Easter Sunday</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>2019-10-07</td>\n",
       "      <td>Labour Day</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>2019-06-10</td>\n",
       "      <td>Queen's Birthday</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>2019-08-05</td>\n",
       "      <td>Bank Holiday</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "          ds                   holiday\n",
       "0 2019-01-26             Australia Day\n",
       "1 2019-01-28  Australia Day (Observed)\n",
       "2 2019-04-25                 Anzac Day\n",
       "3 2019-12-25             Christmas Day\n",
       "4 2019-12-26                Boxing Day\n",
       "5 2019-04-20           Easter Saturday\n",
       "6 2019-04-21             Easter Sunday\n",
       "7 2019-10-07                Labour Day\n",
       "8 2019-06-10          Queen's Birthday\n",
       "9 2019-08-05              Bank Holiday"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from prophet.make_holidays import make_holidays_df\n",
    "\n",
    "nsw_holidays = make_holidays_df(\n",
    "    year_list=[2019 + i for i in range(10)], country='AU', province='NSW'\n",
    ")\n",
    "nsw_holidays.head(n=10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "from prophet import Prophet\n",
    "\n",
    "m_nsw = Prophet(holidays=nsw_holidays)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Fourier Order for Seasonalities\n",
    "\n",
    "Seasonalities are estimated using a partial Fourier sum. See [the paper](https://peerj.com/preprints/3190/) for complete details, and [this figure on Wikipedia](https://en.wikipedia.org/wiki/Fourier_series#/media/File:Fourier_Series.svg) for an illustration of how a partial Fourier sum can approximate an arbitrary periodic signal. The number of terms in the partial sum (the order) is a parameter that determines how quickly the seasonality can change. To illustrate this, consider the Peyton Manning data from the [Quickstart](https://facebook.github.io/prophet/docs/quick_start.html). The default Fourier order for yearly seasonality is 10, which produces this fit:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "output_hidden": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "R[write to console]: Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.\n",
      "\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 22176 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%%R -w 9 -h 3 -u in\n",
    "m <- prophet(df)\n",
    "prophet:::plot_yearly(m)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 38064 characters]",
      "text/plain": [
       "<Figure size 720x432 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from prophet.plot import plot_yearly\n",
    "m = Prophet().fit(df)\n",
    "a = plot_yearly(m)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The default values are often appropriate, but they can be increased when the seasonality needs to fit higher-frequency changes, and generally be less smooth. The Fourier order can be specified for each built-in seasonality when instantiating the model, here it is increased to 20:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "output_hidden": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "R[write to console]: Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.\n",
      "\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 22804 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%%R -w 9 -h 3 -u in\n",
    "m <- prophet(df, yearly.seasonality = 20)\n",
    "prophet:::plot_yearly(m)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 35768 characters]",
      "text/plain": [
       "<Figure size 720x432 with 1 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "from prophet.plot import plot_yearly\n",
    "m = Prophet(yearly_seasonality=20).fit(df)\n",
    "a = plot_yearly(m)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Increasing the number of Fourier terms allows the seasonality to fit faster changing cycles, but can also lead to overfitting: N Fourier terms corresponds to 2N variables used for modeling the cycle\n",
    "\n",
    "### Specifying Custom Seasonalities\n",
    "\n",
    "Prophet will by default fit weekly and yearly seasonalities, if the time series is more than two cycles long. It will also fit daily seasonality for a sub-daily time series. You can add other seasonalities (monthly, quarterly, hourly) using the `add_seasonality` method (Python) or function (R).\n",
    "\n",
    "The inputs to this function are a name, the period of the seasonality in days, and the Fourier order for the seasonality. For reference, by default Prophet uses a Fourier order of 3 for weekly seasonality and 10 for yearly seasonality. An optional input to `add_seasonality` is the prior scale for that seasonal component - this is discussed below.\n",
    "\n",
    "As an example, here we fit the Peyton Manning data from the [Quickstart](https://facebook.github.io/prophet/docs/quick_start.html), but replace the weekly seasonality with monthly seasonality. The monthly seasonality then will appear in the components plot:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "output_hidden": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "R[write to console]: Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.\n",
      "\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 59444 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%%R -w 9 -h 9 -u in\n",
    "m <- prophet(weekly.seasonality=FALSE)\n",
    "m <- add_seasonality(m, name='monthly', period=30.5, fourier.order=5)\n",
    "m <- fit.prophet(m, df)\n",
    "forecast <- predict(m, future)\n",
    "prophet_plot_components(m, forecast)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 73644 characters]",
      "text/plain": [
       "<Figure size 648x648 with 3 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "m = Prophet(weekly_seasonality=False)\n",
    "m.add_seasonality(name='monthly', period=30.5, fourier_order=5)\n",
    "forecast = m.fit(df).predict(future)\n",
    "fig = m.plot_components(forecast)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Seasonalities that depend on other factors\n",
    "In some instances the seasonality may depend on other factors, such as a weekly seasonal pattern that is different during the summer than it is during the rest of the year, or a daily seasonal pattern that is different on weekends vs. on weekdays. These types of seasonalities can be modeled using conditional seasonalities.\n",
    "\n",
    "Consider the Peyton Manning example from the [Quickstart](https://facebook.github.io/prophet/docs/quick_start.html). The default weekly seasonality assumes that the pattern of weekly seasonality is the same throughout the year, but we'd expect the pattern of weekly seasonality to be different during the on-season (when there are games every Sunday) and the off-season. We can use conditional seasonalities to construct separate on-season and off-season weekly seasonalities.\n",
    "\n",
    "First we add a boolean column to the dataframe that indicates whether each date is during the on-season or the off-season:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%R\n",
    "is_nfl_season <- function(ds) {\n",
    "  dates <- as.Date(ds)\n",
    "  month <- as.numeric(format(dates, '%m'))\n",
    "  return(month > 8 | month < 2)\n",
    "}\n",
    "df$on_season <- is_nfl_season(df$ds)\n",
    "df$off_season <- !is_nfl_season(df$ds)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "def is_nfl_season(ds):\n",
    "    date = pd.to_datetime(ds)\n",
    "    return (date.month > 8 or date.month < 2)\n",
    "\n",
    "df['on_season'] = df['ds'].apply(is_nfl_season)\n",
    "df['off_season'] = ~df['ds'].apply(is_nfl_season)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then we disable the built-in weekly seasonality, and replace it with two weekly seasonalities that have these columns specified as a condition. This means that the seasonality will only be applied to dates where the `condition_name` column is `True`. We must also add the column to the `future` dataframe for which we are making predictions."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "output_hidden": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "R[write to console]: Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.\n",
      "\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 78152 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%%R -w 9 -h 12 -u in\n",
    "m <- prophet(weekly.seasonality=FALSE)\n",
    "m <- add_seasonality(m, name='weekly_on_season', period=7, fourier.order=3, condition.name='on_season')\n",
    "m <- add_seasonality(m, name='weekly_off_season', period=7, fourier.order=3, condition.name='off_season')\n",
    "m <- fit.prophet(m, df)\n",
    "\n",
    "future$on_season <- is_nfl_season(future$ds)\n",
    "future$off_season <- !is_nfl_season(future$ds)\n",
    "forecast <- predict(m, future)\n",
    "prophet_plot_components(m, forecast)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 97644 characters]",
      "text/plain": [
       "<Figure size 648x864 with 4 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "m = Prophet(weekly_seasonality=False)\n",
    "m.add_seasonality(name='weekly_on_season', period=7, fourier_order=3, condition_name='on_season')\n",
    "m.add_seasonality(name='weekly_off_season', period=7, fourier_order=3, condition_name='off_season')\n",
    "\n",
    "future['on_season'] = future['ds'].apply(is_nfl_season)\n",
    "future['off_season'] = ~future['ds'].apply(is_nfl_season)\n",
    "forecast = m.fit(df).predict(future)\n",
    "fig = m.plot_components(forecast)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Both of the seasonalities now show up in the components plots above. We can see that during the on-season when games are played every Sunday, there are large increases on Sunday and Monday that are completely absent during the off-season."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Prior scale for holidays and seasonality\n",
    "If you find that the holidays are overfitting, you can adjust their prior scale to smooth them using the parameter `holidays_prior_scale`. By default this parameter is 10, which provides very little regularization. Reducing this parameter dampens holiday effects:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "output_hidden": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "R[write to console]: Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.\n",
      "\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "           ds playoff superbowl\n",
      "17 2014-02-02 1.21154 0.9481949\n",
      "18 2014-02-03 1.85564 0.9925750\n",
      "19 2015-01-11 1.21154 0.0000000\n",
      "20 2015-01-12 1.85564 0.0000000\n",
      "21 2016-01-17 1.21154 0.0000000\n",
      "22 2016-01-18 1.85564 0.0000000\n",
      "23 2016-01-24 1.21154 0.0000000\n",
      "24 2016-01-25 1.85564 0.0000000\n",
      "25 2016-02-07 1.21154 0.9481949\n",
      "26 2016-02-08 1.85564 0.9925750\n"
     ]
    }
   ],
   "source": [
    "%%R\n",
    "m <- prophet(df, holidays = holidays, holidays.prior.scale = 0.05)\n",
    "forecast <- predict(m, future)\n",
    "forecast %>% \n",
    "  select(ds, playoff, superbowl) %>% \n",
    "  filter(abs(playoff + superbowl) > 0) %>%\n",
    "  tail(10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "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>playoff</th>\n",
       "      <th>superbowl</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>2190</th>\n",
       "      <td>2014-02-02</td>\n",
       "      <td>1.206086</td>\n",
       "      <td>0.964914</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2191</th>\n",
       "      <td>2014-02-03</td>\n",
       "      <td>1.852077</td>\n",
       "      <td>0.992634</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2532</th>\n",
       "      <td>2015-01-11</td>\n",
       "      <td>1.206086</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2533</th>\n",
       "      <td>2015-01-12</td>\n",
       "      <td>1.852077</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2901</th>\n",
       "      <td>2016-01-17</td>\n",
       "      <td>1.206086</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2902</th>\n",
       "      <td>2016-01-18</td>\n",
       "      <td>1.852077</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2908</th>\n",
       "      <td>2016-01-24</td>\n",
       "      <td>1.206086</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2909</th>\n",
       "      <td>2016-01-25</td>\n",
       "      <td>1.852077</td>\n",
       "      <td>0.000000</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2922</th>\n",
       "      <td>2016-02-07</td>\n",
       "      <td>1.206086</td>\n",
       "      <td>0.964914</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2923</th>\n",
       "      <td>2016-02-08</td>\n",
       "      <td>1.852077</td>\n",
       "      <td>0.992634</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "             ds   playoff  superbowl\n",
       "2190 2014-02-02  1.206086   0.964914\n",
       "2191 2014-02-03  1.852077   0.992634\n",
       "2532 2015-01-11  1.206086   0.000000\n",
       "2533 2015-01-12  1.852077   0.000000\n",
       "2901 2016-01-17  1.206086   0.000000\n",
       "2902 2016-01-18  1.852077   0.000000\n",
       "2908 2016-01-24  1.206086   0.000000\n",
       "2909 2016-01-25  1.852077   0.000000\n",
       "2922 2016-02-07  1.206086   0.964914\n",
       "2923 2016-02-08  1.852077   0.992634"
      ]
     },
     "execution_count": 15,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "m = Prophet(holidays=holidays, holidays_prior_scale=0.05).fit(df)\n",
    "forecast = m.predict(future)\n",
    "forecast[(forecast['playoff'] + forecast['superbowl']).abs() > 0][\n",
    "    ['ds', 'playoff', 'superbowl']][-10:]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The magnitude of the holiday effect has been reduced compared to before, especially for superbowls, which had the fewest observations. There is a parameter `seasonality_prior_scale` which similarly adjusts the extent to which the seasonality model will fit the data.\n",
    "\n",
    "Prior scales can be set separately for individual holidays by including a column `prior_scale` in the holidays dataframe. Prior scales for individual seasonalities can be passed as an argument to `add_seasonality`. For instance, the prior scale for just weekly seasonality can be set using:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "%%R\n",
    "m <- prophet()\n",
    "m <- add_seasonality(\n",
    "  m, name='weekly', period=7, fourier.order=3, prior.scale=0.1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {
    "output_hidden": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<prophet.forecaster.Prophet at 0x7f2a62813f40>"
      ]
     },
     "execution_count": 16,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "m = Prophet()\n",
    "m.add_seasonality(\n",
    "    name='weekly', period=7, fourier_order=3, prior_scale=0.1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "### Additional regressors\n",
    "Additional regressors can be added to the linear part of the model using the `add_regressor` method or function. A column with the regressor value will need to be present in both the fitting and prediction dataframes. For example, we can add an additional effect on Sundays during the NFL season. On the components plot, this effect will show up in the 'extra_regressors' plot:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "output_hidden": true
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "R[write to console]: Disabling daily seasonality. Run prophet with daily.seasonality=TRUE to override this.\n",
      "\n"
     ]
    },
    {
     "data": {
      "image/png": "[encoded data, 79280 characters]"
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "%%R -w 9 -h 12 -u in\n",
    "nfl_sunday <- function(ds) {\n",
    "  dates <- as.Date(ds)\n",
    "  month <- as.numeric(format(dates, '%m'))\n",
    "  as.numeric((weekdays(dates) == \"Sunday\") & (month > 8 | month < 2))\n",
    "}\n",
    "df$nfl_sunday <- nfl_sunday(df$ds)\n",
    "\n",
    "m <- prophet()\n",
    "m <- add_regressor(m, 'nfl_sunday')\n",
    "m <- fit.prophet(m, df)\n",
    "\n",
    "future$nfl_sunday <- nfl_sunday(future$ds)\n",
    "\n",
    "forecast <- predict(m, future)\n",
    "prophet_plot_components(m, forecast)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "[encoded data, 87476 characters]",
      "text/plain": [
       "<Figure size 648x864 with 4 Axes>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "def nfl_sunday(ds):\n",
    "    date = pd.to_datetime(ds)\n",
    "    if date.weekday() == 6 and (date.month > 8 or date.month < 2):\n",
    "        return 1\n",
    "    else:\n",
    "        return 0\n",
    "df['nfl_sunday'] = df['ds'].apply(nfl_sunday)\n",
    "\n",
    "m = Prophet()\n",
    "m.add_regressor('nfl_sunday')\n",
    "m.fit(df)\n",
    "\n",
    "future['nfl_sunday'] = future['ds'].apply(nfl_sunday)\n",
    "\n",
    "forecast = m.predict(future)\n",
    "fig = m.plot_components(forecast)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "NFL Sundays could also have been handled using the \"holidays\" interface described above, by creating a list of past and future NFL Sundays. The `add_regressor` function provides a more general interface for defining extra linear regressors, and in particular does not require that the regressor be a binary indicator. Another time series could be used as a regressor, although its future values would have to be known.\n",
    "\n",
    "[This notebook](https://nbviewer.jupyter.org/github/nicolasfauchereau/Auckland_Cycling/blob/master/notebooks/Auckland_cycling_and_weather.ipynb) shows an example of using weather factors as extra regressors in a forecast of bicycle usage, and provides an excellent illustration of how other time series can be included as extra regressors.\n",
    "\n",
    "The `add_regressor` function has optional arguments for specifying the prior scale (holiday prior scale is used by default) and whether or not the regressor is standardized - see the docstring with `help(Prophet.add_regressor)` in Python and `?add_regressor` in R. Note that regressors must be added prior to model fitting. Prophet will also raise an error if the regressor is constant throughout the history, since there is nothing to fit from it.\n",
    "\n",
    "The extra regressor must be known for both the history and for future dates. It thus must either be something that has known future values (such as `nfl_sunday`), or something that has separately been forecasted elsewhere. The weather regressors used in the notebook linked above is a good example of an extra regressor that has forecasts that can be used for future values. \n",
    "\n",
    "One can also use as a regressor another time series that has been forecasted with a time series model, such as Prophet. For instance, if `r(t)` is included as a regressor for `y(t)`, Prophet can be used to forecast `r(t)` and then that forecast can be plugged in as the future values when forecasting `y(t)`. A note of caution around this approach: This will probably not be useful unless `r(t)` is somehow easier to forecast than `y(t)`. This is because error in the forecast of `r(t)` will produce error in the forecast of `y(t)`. One setting where this can be useful is in hierarchical time series, where there is top-level forecast that has higher signal-to-noise and is thus easier to forecast. Its forecast can be included in the forecast for each lower-level series.\n",
    "\n",
    "Extra regressors are put in the linear component of the model, so the underlying model is that the time series depends on the extra regressor as either an additive or multiplicative factor (see the next section for multiplicativity).\n",
    "\n",
    "#### Coefficients of additional regressors\n",
    "\n",
    "To extract the beta coefficients of the extra regressors, use the utility function `regressor_coefficients` (`from prophet.utilities import regressor_coefficients` in Python, `prophet::regressor_coefficients` in R) on the fitted model. The estimated beta coefficient for each regressor roughly represents the increase in prediction value for a unit increase in the regressor value (note that the coefficients returned are always on the scale of the original data). If `mcmc_samples` is specified, a credible interval for each coefficient is also returned, which can help identify whether the regressor is meaningful to the model (a credible interval that includes the 0 value suggests the regressor is not meaningful)."
   ]
  }
 ],
 "metadata": {
  "celltoolbar": "Edit Metadata",
  "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.9.17"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
