# Load libraries and datasets
library(TSstudio)
library(plotly)
## Loading required package: ggplot2
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
library(tidyr)
library(forecast)
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(dplyr)
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(Quandl)
## Loading required package: xts
## Loading required package: zoo
## 
## Attaching package: 'zoo'
## The following objects are masked from 'package:base':
## 
##     as.Date, as.Date.numeric
## 
## ######################### Warning from 'xts' package ##########################
## #                                                                             #
## # The dplyr lag() function breaks how base R's lag() function is supposed to  #
## # work, which breaks lag(my_xts). Calls to lag(my_xts) that you type or       #
## # source() into this session won't work correctly.                            #
## #                                                                             #
## # Use stats::lag() to make sure you're not using dplyr::lag(), or you can add #
## # conflictRules('dplyr', exclude = 'lag') to your .Rprofile to stop           #
## # dplyr from breaking base R's lag() function.                                #
## #                                                                             #
## # Code in packages is not affected. It's protected by R's namespace mechanism #
## # Set `options(xts.warn_dplyr_breaks_lag = FALSE)` to suppress this warning.  #
## #                                                                             #
## ###############################################################################
## 
## Attaching package: 'xts'
## The following objects are masked from 'package:dplyr':
## 
##     first, last
# Load Coffee_Prices dataset
data("Coffee_Prices")
ts_info(Coffee_Prices)
##  The Coffee_Prices series is a mts object with 2 variables and 701 observations
##  Frequency: 12 
##  Start time: 1960 1 
##  End time: 2018 5
# Extract Robusta Coffee Prices
robusta <- Coffee_Prices[, 1]

# Plot Coffee Prices
ts_plot(robusta,
        title = "The Robusta Coffee Monthly Prices",
        Ytitle = "Price in USD",
        Xtitle = "Year")
# Define sma_forecast function
sma_forecast <- function(df, h, m, w = NULL) {
  
  if(h > nrow(df)) {
    stop("The length of the forecast horizon must be shorter than the length of the series")
  }
  
  if(m > nrow(df)) {
    stop("The length of the rolling window must be shorter than the length of the series")
  }
  
  if(!is.null(w)) {
    if(length(w) != m) {
      stop("The weight argument is not aligned with the length of the rolling window")
    } else if(sum(w) != 1) {
      stop("The sum of the average weight is different than 1")
    }
  }
  
  if(is.null(w)) {
    w <- rep(1/m, m)
  }
  
  names(df)[1] <- "date"
  df$type <- c(rep("train", nrow(df) - h), rep("test", h))
  df1 <- df %>% spread(key = type, value = y)
  
  df1$yhat <- df1$train
  
  for(i in (nrow(df1) - h + 1):nrow(df1)) {
    r <- (i - m):(i - 1)
    df1$yhat[i] <- sum(df1$yhat[r] * w)
  }
  
  df1$yhat <- ifelse(is.na(df1$test), NA, df1$yhat)
  df1$y <- ifelse(is.na(df1$test), df1$train, df1$test)
  
  return(df1)
}

# Forecast Robusta Coffee Prices
robusta_df <- ts_to_prophet(robusta)
robusta_fc_m1 <- sma_forecast(robusta_df, h = 24, m = 1)
robusta_fc_m6 <- sma_forecast(robusta_df, h = 24, m = 6)
robusta_fc_m12 <- sma_forecast(robusta_df, h = 24, m = 12)
robusta_fc_m24 <- sma_forecast(robusta_df, h = 24, m = 24)
robusta_fc_m36 <- sma_forecast(robusta_df, h = 24, m = 36)
# Plot Robusta Coffee Price Forecast
plot_ly(data = robusta_df[650:nrow(robusta_df),], x = ~ ds, y = ~ y,
        type = "scatter", mode = "lines", name = "Actual") %>%
  add_lines(x = robusta_fc_m1$date, y = robusta_fc_m1$yhat, name = "SMA - 1", line = list(dash = "dash")) %>%
  add_lines(x = robusta_fc_m6$date, y = robusta_fc_m6$yhat, name = "SMA - 6", line = list(dash = "dash")) %>%
  add_lines(x = robusta_fc_m12$date, y = robusta_fc_m12$yhat, name = "SMA - 12", line = list(dash = "dash")) %>%
  add_lines(x = robusta_fc_m24$date, y = robusta_fc_m24$yhat, name = "SMA - 24", line = list(dash = "dash")) %>%
  add_lines(x = robusta_fc_m36$date, y = robusta_fc_m36$yhat, name = "SMA - 36", line = list(dash = "dash")) %>%
  layout(title = "Forecasting the Robusta Coffee Monthly Prices",
         xaxis = list(title = ""),
         yaxis = list(title = "USD per Kg."))
# Load USgas dataset
data("USgas")
USgas_df <- ts_to_prophet(USgas)

# Forecast US Gas Consumption
USgas_fc_m12a <- sma_forecast(USgas_df, h = 24, m = 12, w = c(1, rep(0, 11)))
USgas_fc_m12b <- sma_forecast(USgas_df, h = 24, m = 12, w = c(0.8, rep(0, 10), 0.2))
# Plot US Gas Consumption Forecast
plot_ly(data = USgas_df[190:nrow(USgas_df),], x = ~ ds, y = ~ y,
        type = "scatter", mode = "lines", name = "Actual") %>%
  add_lines(x = USgas_fc_m12a$date, y = USgas_fc_m12a$yhat, name = "WMA - Seasonal Lag", line = list(dash = "dash")) %>%
  add_lines(x = USgas_fc_m12b$date, y = USgas_fc_m12b$yhat, name = "WMA - 12 (0.2/0.8)", line = list(dash = "dash")) %>%
  layout(title = "Forecasting the Monthly Consumption of Natural Gas in the US",
         xaxis = list(title = ""),
         yaxis = list(title = "Billion Cubic Feet"))
# Calculate SES model alpha values
alpha_df <- data.frame(index = seq(from = 1, to = 15, by = 1),
                       power = seq(from = 14, to = 0, by = -1))

alpha_df$alpha_0.01 <- 0.01 * (1 - 0.01) ^ alpha_df$power
alpha_df$alpha_0.2 <- 0.2 * (1 - 0.2) ^ alpha_df$power
alpha_df$alpha_0.4 <- 0.4 * (1 - 0.4) ^ alpha_df$power
alpha_df$alpha_0.6 <- 0.6 * (1 - 0.6) ^ alpha_df$power
alpha_df$alpha_0.8 <- 0.8 * (1 - 0.8) ^ alpha_df$power
alpha_df$alpha_1 <- 1 * (1 - 1) ^ alpha_df$power
# Plot alpha values
plot_ly(data = alpha_df) %>%
  add_lines(x = ~ index, y = ~ alpha_0.01, name = "alpha = 0.01") %>%
  add_lines(x = ~ index, y = ~ alpha_0.2, name = "alpha = 0.2") %>%
  add_lines(x = ~ index, y = ~ alpha_0.4, name = "alpha = 0.4") %>%
  add_lines(x = ~ index, y = ~ alpha_0.6, name = "alpha = 0.6") %>%
  add_lines(x = ~ index, y = ~ alpha_0.8, name = "alpha = 0.8") %>%
  add_lines(x = ~ index, y = ~ alpha_1, name = "alpha = 1") %>%
  layout(title = "Decay Rate of the SES Weights",
         xaxis = list(title = "Index"),
         yaxis = list(title = "Weight"))
# Split Robusta Coffee data
robusta_par <- ts_split(robusta, sample.out = 12)
train1 <- robusta_par$train
test1 <- robusta_par$test

# Fit SES model to Robusta Coffee data
fc_ses <- ses(train1, h = 12, initial = "optimal")
fc_ses$model
## Simple exponential smoothing 
## 
## Call:
##  ses(y = train1, h = 12, initial = "optimal") 
## 
##   Smoothing parameters:
##     alpha = 0.9999 
## 
##   Initial states:
##     l = 0.6957 
## 
##   sigma:  0.161
## 
##      AIC     AICc      BIC 
## 1989.646 1989.681 2003.252
# Evaluate SES model on test data
test_forecast(actual = robusta,
              forecast.obj = fc_ses,
              test = test1) %>%
  layout(title = "Robusta Coffee Prices Forecast vs. Actual",
         xaxis = list(range = c(2010, max(time(robusta))),
         yaxis = list(range = c(1, 3))))
# Plot SES model forecast
plot_forecast(fc_ses) %>%
  add_lines(x = time(test1) + deltat(test1),
            y = as.numeric(test1),
            name = "Testing Partition") %>%
  layout(title = "Robusta Coffee Prices Forecast vs. Actual",
         xaxis = list(range = c(2010, max(time(robusta)) + deltat(robusta))),
         yaxis = list(range = c(0, 4)))
# Decompose US Gas Consumption data
decompose(USgas) %>% plot()

# Split US Gas Consumption data
USgas_par <- ts_split(USgas, 12)
train2 <- USgas_par$train
valid <- USgas_par$test

# Fit Holt-Winters model to US Gas Consumption data
md_hw <- HoltWinters(train2)
md_hw
## Holt-Winters exponential smoothing with trend and additive seasonal component.
## 
## Call:
## HoltWinters(x = train2)
## 
## Smoothing parameters:
##  alpha: 0.371213
##  beta : 0
##  gamma: 0.4422456
## 
## Coefficients:
##             [,1]
## a   2491.9930104
## b     -0.1287005
## s1    32.0972651
## s2   597.1088003
## s3   834.9628439
## s4   353.8593860
## s5   318.1927058
## s6  -173.0721496
## s7  -346.6229990
## s8  -329.7169608
## s9  -112.1664217
## s10 -140.3186476
## s11 -324.5343787
## s12 -243.9334551
# Generate and evaluate Holt-Winters model forecast
fc_hw <- forecast(md_hw, h = 12)
accuracy(fc_hw, valid)
##                     ME     RMSE      MAE       MPE     MAPE      MASE
## Training set  7.828361 115.2062 87.67420 0.2991952 4.248131 0.7614222
## Test set     51.013877 115.1555 98.06531 1.7994297 3.766099 0.8516656
##                     ACF1 Theil's U
## Training set  0.21911103        NA
## Test set     -0.01991923 0.3652142
# Perform grid search for SES model
alpha <- seq(from = 0, to = 1, by = 0.01)
alpha[1] <- 0.001
ses_grid <- lapply(alpha, function(i) {
  md1 <- md_accuracy1 <- md2 <- md_accuracy2 <- results <- NULL
  md1 <- ses(train1, h = 12, alpha = i, initial = "simple")
  md_accuracy1 <- accuracy(md1, test1)
  
  md2 <- ses(train2, h = 12, alpha = i, initial = "simple")
  md_accuracy2 <- accuracy(md2, valid)
  
  results <- data.frame(alpha = i,
                        train = md_accuracy1[9],
                        test = md_accuracy1[10],
                        valid = md_accuracy2[10])
}) %>% bind_rows()
# Plot grid search results
plot_ly(data = ses_grid, x = ~ alpha, y = ~ train, 
        line = list(color = 'rgb(205, 12, 24)'),
        type = "scatter", mode = "lines", name = "Training") %>%
  add_lines(x = ~ alpha, y = ~ test, line = list(color = "rgb(22, 96, 167)", dash = "dash"), name = "Testing") %>%
  add_lines(x = ~ alpha, y = ~ valid, line = list(color = "green", dash = "dot"), name = "Validation") %>%
  layout(title = "SES Model Grid Search Results",
         yaxis = list(title = "MAPE (%)"))
# Load GDP data from Quandl
gdp <- Quandl("FRED/GDP", start_date = "2010-01-01", type = "ts")
ts_info(gdp)
##  The gdp series is a ts object with 1 variable and 48 observations
##  Frequency: 4 
##  Start time: 2010 1 
##  End time: 2021 4
# Plot GDP data
ts_plot(gdp, 
        title = "Gross Domestic Product",
        Ytitle = "Billions of Dollars",
        Xtitle = "Source: U.S. Bureau of Economic Analysis / fred.stlouisfed.org")
# Split GDP data
gdp_par <- ts_split(gdp, sample.out = 8)
train3 <- gdp_par$train
test3 <- gdp_par$test

# Fit Holt model to GDP data
fc_holt <- holt(train3, h = 8, initial = "optimal") 
fc_holt$model
## Holt's method 
## 
## Call:
##  holt(y = train3, h = 8, initial = "optimal") 
## 
##   Smoothing parameters:
##     alpha = 0.9985 
##     beta  = 0.0941 
## 
##   Initial states:
##     l = 14603.0487 
##     b = 161.9411 
## 
##   sigma:  80.9869
## 
##      AIC     AICc      BIC 
## 504.8838 506.6485 513.3282
# Evaluate Holt model forecast
accuracy(fc_holt, test3)
##                      ME       RMSE      MAE         MPE      MAPE       MASE
## Training set   10.99164   76.83093  61.7626  0.05241543 0.3460477 0.08790283
## Test set     -665.87355 1141.19097 854.8069 -3.29699460 4.0874667 1.21659297
##                   ACF1 Theil's U
## Training set 0.0192117        NA
## Test set     0.2975704   1.08055
# Plot Holt model forecast
test_forecast(gdp, forecast.obj = fc_holt, test = test3)
# Fit exponential Holt model to GDP data
fc_holt_exp <- holt(train3, h = 8, beta = 0.75, initial = "optimal", exponential = TRUE) 
fc_holt_exp$model
## Holt's method with exponential trend 
## 
## Call:
##  holt(y = train3, h = 8, initial = "optimal", exponential = TRUE,  
## 
##  Call:
##      beta = 0.75) 
## 
##   Smoothing parameters:
##     alpha = 0.781 
##     beta  = 0.75 
## 
##   Initial states:
##     l = 14572.2291 
##     b = 1.0142 
## 
##   sigma:  0.0053
## 
##      AIC     AICc      BIC 
## 515.9291 517.0720 522.6847
# Evaluate exponential Holt model forecast
accuracy(fc_holt_exp, test3,)
##                       ME       RMSE       MAE         MPE      MAPE      MASE
## Training set   -2.792636   90.20753  74.14323 -0.01756593 0.4165413 0.1055234
## Test set     -703.014806 1151.21262 858.97402 -3.46212317 4.1130726 1.2225238
##                    ACF1 Theil's U
## Training set -0.1541725        NA
## Test set      0.2834645  1.090637
# Plot exponential Holt model forecast
test_forecast(gdp, forecast.obj = fc_holt_exp, test = test3)
data (USgas)
decompose (USgas) %>% plot ()

USgaspar <- ts_split (USgas, 12)
train<- USgas_par$train
test <- USgas_par$test

md_hw<- HoltWinters (train)

md_hw
## Holt-Winters exponential smoothing with trend and additive seasonal component.
## 
## Call:
## HoltWinters(x = train)
## 
## Smoothing parameters:
##  alpha: 0.371213
##  beta : 0
##  gamma: 0.4422456
## 
## Coefficients:
##             [,1]
## a   2491.9930104
## b     -0.1287005
## s1    32.0972651
## s2   597.1088003
## s3   834.9628439
## s4   353.8593860
## s5   318.1927058
## s6  -173.0721496
## s7  -346.6229990
## s8  -329.7169608
## s9  -112.1664217
## s10 -140.3186476
## s11 -324.5343787
## s12 -243.9334551
data (USgas)
decompose (USgas) %>% plot ()

# -------- Code Chunk 1 --------
set.seed(12345)

stationary_ts <- arima.sim(model = list(order = c(1,0,0), ar = 0.5 ), n = 500)

# -------- Code Chunk 2 --------
library(TSstudio)

ts_plot(stationary_ts, 
        title = "Stationary Time Series",
        Ytitle = "Value",
        Xtitle = "Index")
# -------- Code Chunk 3 --------
set.seed(12345)

non_stationary_ts <- arima.sim(model = list(order = c(1,1,0), ar = 0.3 ), n = 500)

ts_plot(non_stationary_ts, 
        title = "Non-Stationary Time Series",
        Ytitle = "Value",
        Xtitle = "Index")
# -------- Code Chunk 4 --------
data(AirPassengers)

ts_plot(AirPassengers,
        title = "Monthly Airline Passenger Numbers 1949-1960",
        Ytitle = "Thousands of Passengers",
        Xtitle = "Year")
# -------- Code Chunk 5 --------
ts_plot(diff(AirPassengers, lag = 1),
        title = "AirPassengers Series - First Differencing",
        Xtitle = "Year",
        Ytitle = "Differencing of Thousands of Passengers")
# -------- Code Chunk 6 --------
ts_plot(diff(diff(AirPassengers, lag = 1), 12),
        title = "AirPassengers Series - First and Seasonal Differencing",
        Xtitle = "Year",
        Ytitle = "Differencing of Thousands of Passengers")
# -------- Code Chunk 7 --------
ts_plot(diff(log(AirPassengers), lag = 1),
        title = "AirPassengers Series - First Differencing with Log Transformation",
        Xtitle = "Year",
        Ytitle = "Differencing/Log of Thousands of Passengers")
# -------- Code Chunk 8 --------
set.seed(12345)

library(plotly)

p1 <- plot_ly()
p2 <- plot_ly()

for(i in 1:20){
  rm <- NULL
  rw <- arima.sim(model = list(order = c(0, 1, 0)), n = 500)
  p1 <- p1 %>% add_lines(x = time(rw), y = as.numeric(rw))
  p2 <- p2 %>% add_lines(x = time(diff(rw)), y = as.numeric(diff(rw)))
}

# -------- Code Chunk 9 --------
p1 %>% layout(title = "Simulate Random Walk",
              yaxis = list(title = "Value"),
              xaxis = list(title = "Index")) %>%
  hide_legend()
# -------- Code Chunk 10 --------
p2 %>% layout(title = "Simulate Random Walk with First-Order Differencing",
              yaxis = list(title = "Value"),
              xaxis = list(title = "Index")) %>%
  hide_legend()
# -------- Code Chunk 11 --------
set.seed(12345)

ar2 <- arima.sim(model = list(order = c(2,0,0), ar = c(0.9, -0.3)), n = 500)

# -------- Code Chunk 12 --------
ts_plot(ar2, 
        title = "Simulate AR(2) Series",
        Ytitle = "Value",
        Xtitle = "Index")
# -------- Code Chunk 13 --------
md_ar <- ar(ar2)
md_ar
## 
## Call:
## ar(x = ar2)
## 
## Coefficients:
##       1        2  
##  0.8851  -0.2900  
## 
## Order selected 2  sigma^2 estimated as  1.049
# -------- Code Chunk 14 --------
par(mfrow=c(1,2))
acf(ar2)
pacf(ar2)

# -------- Code Chunk 15 --------
set.seed(12345)

ma2 <- arima.sim(model = list(order = c(0, 0, 2), ma = c(0.5, -0.3)), n = 500)

# -------- Code Chunk 16 --------
ts_plot(ma2, 
        title = "Simulate MA(2) Series",
        Ytitle = "Value",
        Xtitle = "Index")
# -------- Code Chunk 17 --------
md_ma <- arima(ma2, order = c(0,0,2), method = "ML")
md_ma
## 
## Call:
## arima(x = ma2, order = c(0, 0, 2), method = "ML")
## 
## Coefficients:
##         ma1      ma2  intercept
##       0.530  -0.3454     0.0875
## s.e.  0.041   0.0406     0.0525
## 
## sigma^2 estimated as 0.9829:  log likelihood = -705.81,  aic = 1419.62
# -------- Code Chunk 18 --------
par(mfrow=c(1,2))
acf(ma2)
pacf(ma2)

# -------- Code Chunk 19 --------
set.seed(12345)

arma <- arima.sim(model = list(order = c(1,0,2), ar = c(0.7), ma = c(0.5,-0.3)), n = 500)

# -------- Code Chunk 20 --------
ts_plot(arma, 
        title = "Simulate ARMA(1,2) Series",
        Ytitle = "Value",
        Xtitle = "Index")
# -------- Code Chunk 21 --------
arma_md <- arima(arma, order = c(1,0,2))
arma_md
## 
## Call:
## arima(x = arma, order = c(1, 0, 2))
## 
## Coefficients:
##          ar1     ma1      ma2  intercept
##       0.7439  0.4785  -0.3954     0.2853
## s.e.  0.0657  0.0878   0.0849     0.1891
## 
## sigma^2 estimated as 1.01:  log likelihood = -713.18,  aic = 1436.36
# -------- Code Chunk 22 --------
par(mfrow=c(1,2))
acf(arma)
pacf(arma)

# -------- Code Chunk 23 --------
arima(arma, order = c(1, 0, 1), include.mean = FALSE)
## 
## Call:
## arima(x = arma, order = c(1, 0, 1), include.mean = FALSE)
## 
## Coefficients:
##          ar1     ma1
##       0.4144  0.8864
## s.e.  0.0432  0.0248
## 
## sigma^2 estimated as 1.051:  log likelihood = -723,  aic = 1452
# -------- Code Chunk 24 --------
arima(arma, order = c(2, 0, 1), include.mean = FALSE)
## 
## Call:
## arima(x = arma, order = c(2, 0, 1), include.mean = FALSE)
## 
## Coefficients:
##          ar1     ar2     ma1
##       0.3136  0.1918  0.9227
## s.e.  0.0486  0.0484  0.0183
## 
## sigma^2 estimated as 1.019:  log likelihood = -715.26,  aic = 1438.52
# -------- Code Chunk 25 --------
arima(arma, order = c(1, 0, 2), include.mean = FALSE)
## 
## Call:
## arima(x = arma, order = c(1, 0, 2), include.mean = FALSE)
## 
## Coefficients:
##          ar1     ma1      ma2
##       0.7602  0.4654  -0.4079
## s.e.  0.0626  0.0858   0.0832
## 
## sigma^2 estimated as 1.014:  log likelihood = -714.27,  aic = 1436.54
# -------- Code Chunk 26 --------
arima(arma, order = c(2, 0, 2), include.mean = FALSE)
## 
## Call:
## arima(x = arma, order = c(2, 0, 2), include.mean = FALSE)
## 
## Coefficients:
##          ar1     ar2     ma1      ma2
##       0.7239  0.0194  0.4997  -0.3783
## s.e.  0.2458  0.1257  0.2427   0.2134
## 
## sigma^2 estimated as 1.014:  log likelihood = -714.26,  aic = 1438.51
# -------- Code Chunk 27 --------
library(forecast)
best_arma <- arima(arma, order = c(1, 0, 2), include.mean = FALSE)

checkresiduals(best_arma)

## 
##  Ljung-Box test
## 
## data:  Residuals from ARIMA(1,0,2) with zero mean
## Q* = 5.3129, df = 7, p-value = 0.6218
## 
## Model df: 3.   Total lags used: 10
# -------- Code Chunk 28 --------
ar_fc <- forecast(md_ar, h = 100)

# -------- Code Chunk 29 --------
plot_forecast(ar_fc, 
              title = "Forecast AR(2) Model",
              Ytitle = "Value",
              Xtitle = "Year")
# -------- Code Chunk 30 --------
data(Coffee_Prices)

robusta_price <- window(Coffee_Prices[,1], start = c(2000, 1))

# -------- Code Chunk 31 --------
ts_plot(robusta_price,
        title = "The Robusta Coffee Monthly Prices",
        Ytitle = "Price in USD",
        Xtitle = "Year")
# -------- Code Chunk 32 --------
acf(robusta_price)

# -------- Code Chunk 33 --------
robusta_price_d1 <- diff(robusta_price)

# -------- Code Chunk 34 --------
par(mfrow=c(1,2))

acf(robusta_price_d1)
pacf(robusta_price_d1)

# -------- Code Chunk 35 --------
robusta_md <- arima(robusta_price, order = c(1, 1, 0))

# -------- Code Chunk 36 --------
summary(robusta_md)
## 
## Call:
## arima(x = robusta_price, order = c(1, 1, 0))
## 
## Coefficients:
##          ar1
##       0.2780
## s.e.  0.0647
## 
## sigma^2 estimated as 0.007142:  log likelihood = 231.38,  aic = -458.76
## 
## Training set error measures:
##                       ME       RMSE        MAE        MPE     MAPE     MASE
## Training set 0.002595604 0.08432096 0.06494772 0.08104715 4.254984 1.001542
##                     ACF1
## Training set 0.001526295
# -------- Code Chunk 37 --------
checkresiduals(robusta_md)

## 
##  Ljung-Box test
## 
## data:  Residuals from ARIMA(1,1,0)
## Q* = 26.896, df = 23, p-value = 0.2604
## 
## Model df: 1.   Total lags used: 24
# -------- Code Chunk 38 --------
data(USgas)

# -------- Code Chunk 39 --------
ts_plot(USgas,
        title = "US Monthly Natural Gas consumption", 
        Ytitle = "Billion Cubic Feet",
        Xtitle = "Year")
# -------- Code Chunk 40 --------
USgas_split <- ts_split(USgas, sample.out = 12)

train <- USgas_split$train
test <- USgas_split$test

# -------- Code Chunk 41 --------
par(mfrow=c(1,2))
acf(train, lag.max = 60)
pacf(train, lag.max = 60)

# -------- Code Chunk 42 --------
USgas_d12 <- diff(train, 12)

ts_plot(USgas_d12,
        title = "US Monthly Natural Gas consumption - First Seasonal Difference", 
        Ytitle = "Billion Cubic Feet (First Difference)",
        Xtitle = "Year")
# -------- Code Chunk 43 --------
USgas_d12_1 <- diff(diff(USgas_d12, 1))

ts_plot(USgas_d12_1,
        title = "US Monthly Natural Gas consumption - First Seasonal and Non-Seasonal Differencing", 
        Ytitle = "Billion Cubic Feet (Difference)",
        Xtitle = "Year")
# -------- Code Chunk 44 --------
par(mfrow=c(1,2))
acf(USgas_d12_1, lag.max = 60)
pacf(USgas_d12_1, lag.max = 60)

# -------- Code Chunk 45 --------
p <- q <- P <- Q <- 0:2

# -------- Code Chunk 46 --------
arima_grid <- expand.grid(p,q,P,Q)
names(arima_grid) <- c("p", "q", "P", "Q")
arima_grid$d <- 1
arima_grid$D <- 1

# -------- Code Chunk 47 --------
arima_grid$k <- rowSums(arima_grid)

# -------- Code Chunk 48 --------
library(dplyr)

arima_grid <- arima_grid %>% filter(k <= 7)

# -------- Code Chunk 49 --------
# Create an empty data frame to collect the results
results_df <- data.frame(p = numeric(0), d = numeric(0), q = numeric(0), 
                         P = numeric(0), D = numeric(0), Q = numeric(0), AIC = numeric(0))

for (i in 1:nrow(arima_grid)) {
  md <- tryCatch({
    arima(train, order = c(arima_grid$p[i], 1, arima_grid$q[i]), 
          seasonal = list(order = c(arima_grid$P[i], 1, arima_grid$Q[i])))
  }, error = function(e) {
    return(NULL)
  })

  if (!is.null(md)) {
    # Extract AIC and parameters from the successful models
    result <- data.frame(
      p = arima_grid$p[i],
      d = 1,
      q = arima_grid$q[i],
      P = arima_grid$P[i],
      D = 1,
      Q = arima_grid$Q[i],
      AIC = md$aic
    )
    
    # Append the result to the results data frame
    results_df <- rbind(results_df, result)
  }
}

# Sort the results by AIC
arima_search <- results_df[order(results_df$AIC), ]


# -------- Code Chunk 50 --------
head(arima_search)
##    p d q P D Q      AIC
## 46 1 1 1 2 1 1 2597.915
## 47 0 1 2 2 1 1 2598.228
## 60 1 1 1 1 1 2 2603.512
## 52 1 1 1 0 1 2 2603.708
## 29 1 1 1 0 1 1 2604.240
## 61 0 1 2 1 1 2 2604.436
# -------- Code Chunk 51 --------
USgas_best_md <- arima(train, order = c(1,1,1), seasonal = list(order = c(2,1,1)))

USgas_best_md
## 
## Call:
## arima(x = train, order = c(1, 1, 1), seasonal = list(order = c(2, 1, 1)))
## 
## Coefficients:
##          ar1      ma1    sar1     sar2     sma1
##       0.4247  -0.9180  0.0132  -0.2639  -0.7449
## s.e.  0.0770   0.0376  0.0894   0.0834   0.0753
## 
## sigma^2 estimated as 10160:  log likelihood = -1292.96,  aic = 2597.91
# -------- Code Chunk 52 --------
USgas_test_fc <- forecast(USgas_best_md, h = 12)

# -------- Code Chunk 53 --------
accuracy(USgas_test_fc, test)
##                     ME      RMSE      MAE       MPE     MAPE      MASE
## Training set  6.081099  97.85701 73.36854 0.1298714 3.517097 0.6371821
## Test set     42.211253 104.79281 83.09943 1.4913412 3.314280 0.7216918
##                      ACF1 Theil's U
## Training set  0.004565602        NA
## Test set     -0.049999868 0.3469228
# -------- Code Chunk 54 --------
test_forecast(USgas, 
              forecast.obj = USgas_test_fc,
              test = test)
# -------- Code Chunk 55 --------
final_md <- arima(USgas, order = c(1,1,1), seasonal = list(order = c(2,1,1)))

# -------- Code Chunk 56 --------
checkresiduals(final_md)

## 
##  Ljung-Box test
## 
## data:  Residuals from ARIMA(1,1,1)(2,1,1)[12]
## Q* = 30.173, df = 19, p-value = 0.04964
## 
## Model df: 5.   Total lags used: 24
# -------- Code Chunk 57 --------
USgas_fc <- forecast(final_md, h = 12)

# -------- Code Chunk 58 --------
plot_forecast(USgas_fc,
              title = "US Natural Gas Consumption - Forecast",
              Ytitle = "Billion Cubic Feet",
              Xtitle = "Year")
# -------- Code Chunk 59 --------
USgas_auto_md1 <- auto.arima(train)
USgas_auto_md1
## Series: train 
## ARIMA(2,1,1)(2,1,1)[12] 
## 
## Coefficients:
##          ar1      ar2      ma1    sar1     sar2     sma1
##       0.4301  -0.0372  -0.9098  0.0117  -0.2673  -0.7431
## s.e.  0.0794   0.0741   0.0452  0.0887   0.0830   0.0751
## 
## sigma^2 = 10446:  log likelihood = -1292.83
## AIC=2599.67   AICc=2600.22   BIC=2623.2
# -------- Code Chunk 60 --------
USgas_auto_md2 <- auto.arima(train, 
                             max.order = 5,
                             D = 1,
                             d = 1,
                             ic = "aic",
                             stepwise = FALSE, 
                             approximation = FALSE)
USgas_auto_md2
## Series: train 
## ARIMA(1,1,1)(2,1,1)[12] 
## 
## Coefficients:
##          ar1      ma1    sar1     sar2     sma1
##       0.4247  -0.9180  0.0132  -0.2639  -0.7449
## s.e.  0.0770   0.0376  0.0894   0.0834   0.0753
## 
## sigma^2 = 10405:  log likelihood = -1292.96
## AIC=2597.91   AICc=2598.32   BIC=2618.08
# -------- Code Chunk 61 --------
df <- ts_to_prophet(AirPassengers) %>% setNames(c("date", "y"))

df$lag12 <- dplyr::lag(df$y, n = 12)

library(lubridate)
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
df$month <- factor(month(df$date, label = TRUE), ordered = FALSE)

df$trend <- 1:nrow(df)

# -------- Code Chunk 62 --------
par <- ts_split(ts.obj = AirPassengers, sample.out = 12)

train <- par$train

test <- par$test

# -------- Code Chunk 63 --------
train_df <- df[1:(nrow(df) - 12), ]
test_df <- df[(nrow(df) - 12 + 1):nrow(df), ]

# -------- Code Chunk 64 --------
md1 <- tslm(train ~ season + trend + lag12, data = train_df)

# -------- Code Chunk 65 --------
checkresiduals(md1)

## 
##  Breusch-Godfrey test for serial correlation of order up to 24
## 
## data:  Residuals from Linear regression model
## LM test = 83.147, df = 24, p-value = 1.903e-08
# -------- Code Chunk 66 --------
md2 <- auto.arima(train, 
                  xreg = cbind(model.matrix(~ month,train_df)[,-1], 
                               train_df$trend, 
                               train_df$lag12), 
                  seasonal = TRUE, 
                  stepwise = FALSE, 
                  approximation = FALSE)

# -------- Code Chunk 67 --------
summary(md2)
## Series: train 
## Regression with ARIMA(2,0,0)(2,0,0)[12] errors 
## 
## Coefficients:
##          ar1     ar2     sar1     sar2  monthfeb  monthmar  monthabr  monthmay
##       0.5849  0.3056  -0.4421  -0.2063   -2.7523    0.8231    0.2066    2.8279
## s.e.  0.0897  0.0903   0.1050   0.1060    1.8417    2.3248    2.4162    2.5560
##       monthjun  monthjul  monthago  monthsept  monthoct  monthnov  monthdic
##         6.6057   11.2337   12.1909     3.8269    0.6350   -2.2723   -0.9918
## s.e.    3.2916    4.2324    4.1198     2.9243    2.3405    2.4211    1.9172
##                     
##       0.2726  1.0244
## s.e.  0.1367  0.0426
## 
## sigma^2 = 72.82:  log likelihood = -426.93
## AIC=889.86   AICc=896.63   BIC=940.04
## 
## Training set error measures:
##                     ME     RMSE      MAE       MPE     MAPE      MASE
## Training set 0.4117148 8.353629 6.397538 0.2571543 2.549682 0.2100998
##                     ACF1
## Training set 0.005966712
# -------- Code Chunk 68 --------
checkresiduals(md2)

## 
##  Ljung-Box test
## 
## data:  Residuals from Regression with ARIMA(2,0,0)(2,0,0)[12] errors
## Q* = 25.816, df = 20, p-value = 0.172
## 
## Model df: 4.   Total lags used: 24
# -------- Code Chunk 69 --------
fc1 <- forecast(md1, newdata = test_df)

fc2 <- forecast(md2, xreg = cbind(model.matrix(~ month,test_df)[,-1], 
                                  test_df$trend, 
                                  test_df$lag12))

# -------- Code Chunk 70 --------
accuracy(fc1, test)
##                         ME     RMSE      MAE        MPE     MAPE      MASE
## Training set -1.894492e-15 13.99206 11.47136 -0.1200023 4.472154 0.3541758
## Test set      1.079611e+01 20.82782 18.57391  1.9530865 3.828115 0.5734654
##                   ACF1 Theil's U
## Training set 0.7502578        NA
## Test set     0.1653119 0.4052175
accuracy(fc2, test)
##                       ME      RMSE       MAE        MPE     MAPE      MASE
## Training set   0.4117148  8.353629  6.397538  0.2571543 2.549682 0.2100998
## Test set     -11.2123706 17.928195 13.353910 -2.4898843 2.924174 0.4385521
##                      ACF1 Theil's U
## Training set  0.005966712        NA
## Test set     -0.325044929 0.3923795