setwd('{{ wd }}')

library(forecast)
library(prophet)
library(lubridate)

df <-read.csv('{{ series_path }}', sep = ';')
df$date <- as.Date(parse_date_time(df$date,"ymd"))



start.date <- as.Date('2016-01-01')
first_date <- c(2016, 01)

validation_period <- 30
fc_p = 90
season_freq <- 7
season_freq_2 <- 365.25
result <- matrix(, ncol = 1, nrow = 90)

for (j in 2:ncol(df)){
  my_ts <- ts(df[, j], start = first_date, frequency = season_freq)
  my_ts_2seas <- msts(my_ts, seasonal.periods=c(season_freq,season_freq_2))
  
  fc_union <- matrix( , ncol = 4, nrow = 0)
  
  
  fit1 <- ets(my_ts)
  fc1 <- forecast(fit1, h=fc_p)$mean
  res1 <- as.data.frame(fc1)
  
  fit2 <- auto.arima(my_ts)
  fc2 <- forecast(fit2, h=fc_p)$mean
  res2 <- as.data.frame(fc2)
  
  fit3 <- tbats(my_ts_2seas)
  fc3 <- forecast(fit3, h=fc_p)$mean
  res3 <- as.data.frame(fc3)
  
  dp <- as.data.frame(cbind(as.data.frame(df[, 1]), as.data.frame(df[, j])))
  colnames(dp) <- c("ds", "y")
  
  m <- prophet(dp, daily.seasonality=TRUE)
  future <- make_future_dataframe(m, periods = fc_p)
  forecast <- predict(m, future)
  res4 <- as.data.frame(forecast$yhat)
  res4 <- tail(res4, fc_p)
  
  fc_union <- as.data.frame(as.matrix(cbind(res1,res2,res3,res4)))
  colnames(fc_union) <- c("ets", "ar", "tbats","prophet")
  fc_union$avg <- (fc_union$ets + fc_union$ar + fc_union$tbats + fc_union$prophet)/4
  result <- cbind(result, fc_union$avg)
  
}
result <- result[ , 2:ncol(result)]
colnames(result) <-  c(colnames(df[, 2: ncol(df)]))
write.table(result, '{{ forecast_path }}', sep = ';', row.names = F)

