Search code examples
rfacebook-prophet

Add country holidays to prophet model when using lists


I wish to add US holidays to my data for modelling using the Facebook prophet function.

I can add a predefined list of holidays i.e. NFL playoff and Super Bowl dates at model fitting time but it appears that country holidays need to be fit prior to model fitting.

From the documentation it shows that the country holidays are added to the prophet object and then fitted but I am unsure how to do this when using map as a data object (.x) needs to be specified when using map

How can I add US holidays to my model using a list of data frames?

This is what my code looks like so far:

#install.packages("pacman")
#library(pacman)

# LOAD LIBRARIES
pacman::p_load(tidyquant,tidyverse,prophet,purrr)

# SPECIFY STOCKS TO PULL
tickers = c("AAPL","AMZN")

# GET STOCK PRICE INFO
getSymbols(tickers, 
           from = '2013-01-01',
           to = '2016-06-30',
           warnings = FALSE,
           auto.assign = TRUE)

# MAP DATAFRAMES TO A LIST
dfList <- mget(tickers) %>%
  map(~ fortify.zoo(.x) %>% 
        select(1,5) %>% 
  rename(ds = 1,
         y = 2))

# SPECIFY NFL IMPORTANT DATES
playoffs <- tibble(
  holiday = 'playoff',
  ds = as.Date(c('2008-01-13', '2009-01-03', '2010-01-16',
                 '2010-01-24', '2010-02-07', '2011-01-08',
                 '2013-01-12', '2014-01-12', '2014-01-19',
                 '2014-02-02', '2015-01-11', '2016-01-17',
                 '2016-01-24', '2016-02-07')),
  lower_window = 0,
  upper_window = 1
)
superbowls <- tibble(
  holiday = 'superbowl',
  ds = as.Date(c('2010-02-07','2011-02-06','2012-02-05','2013-02-03','2014-02-02','2015-02-01','2016-02-07','2017-02-05','2018-02-04','2019-02-03','2020-02-02')),
  lower_window = 0,
  upper_window = 1
)

holidays <- bind_rows(playoffs, superbowls) %>% 
  filter(ds >= min(dfList$AAPL$ds) & ds <= max(dfList$AAPL$ds))

# CALL THE PROPHET FUNCTION TO FIT THE MODEL
model_list <- map(dfList,
                  prophet, 
                  holidays = holidays)

# TAKES THE MODEL ABOVE AND THE SPECIFIED FORECAST PERIOD TO PRODUCE A SUITABLE 
# DATA FRAME
future_list <- map(model_list,
                   make_future_dataframe,
                   periods = 365)

# USE THE GENERIC PREDICT FUNCTION TO GET OUR FORECAST
forecast_list <- map2(model_list,
                      future_list,
                      predict)

Solution

  • We can use the anonymous function call (function(x) shortform is ~)

    model_list <- map(dfList,
                    ~  {
                   m <- prophet(holidays = holidays)
                   m <- add_country_holidays(m, country_name = 'US')
                   m <- fit.prophet(m, .x)
                   return(m)
                  })
    

    and once we get the prediction, can check the components

    pdf("plottesting.pdf") 
    p1 <- map2(model_list, forecast_list, prophet_plot_components)
    dev.off()
    

    enter image description here