library(fpp3)
library(fable)
library(ggplot2)
library(tsibble)
library(dplyr)
pigs_victoria <- aus_livestock |>
filter(Animal=='Pigs', State=='Victoria')|>
model(ETS(Count ~ error("A") + trend("N") + season("N")))
report(pigs_victoria)
## Series: Count
## Model: ETS(A,N,N)
## Smoothing parameters:
## alpha = 0.3221247
##
## Initial states:
## l[0]
## 100646.6
##
## sigma^2: 87480760
##
## AIC AICc BIC
## 13737.10 13737.14 13750.07
forec <- pigs_victoria |>
forecast(h = 4)
forec |>
autoplot(aus_livestock) +
labs(y="Count", title="Number of pigs slaughtered in Victoria") +
guides(colour = "none")
## Generated by R
forec %>% hilo() %>% pull(-1)
## <hilo[4]>
## [1] [76854.79, 113518.3]95 [75927.17, 114445.9]95 [75042.22, 115330.9]95
## [4] [74194.54, 116178.6]95
## Calculated by hand
residuals_std <- sd(augment(pigs_victoria)$`.resid`)
# Compute confidence interval
lower_bound <- forec$.mean[1] - (residuals_std * 1.96)
upper_bound <- forec$.mean[1] + (residuals_std * 1.96)
# Display calculated confidence interval
sprintf(
"Calculated confidence interval: [%f, %f]",
lower_bound,
upper_bound
)
## [1] "Calculated confidence interval: [76871.012478, 113502.102384]"
data("global_economy")
greece_exports <- global_economy %>% filter(Country == "Greece")
greece_exports %>% autoplot(Exports) +
labs(title = "Exports of Greece", y = "Exports (in USD)", x = "Year")
fit_ANN <- greece_exports %>%
model(ETS(Exports ~ error("A") + trend("N") + season("N")))
# Generate and plot forecasts
fc_ANN <- forecast(fit_ANN, h = "5 years")
autoplot(fc_ANN) +
labs(title = "Forecasts of Greece Exports (ETS(A,N,N))", y = "Exports (in USD)", x = "Year")
rmse_ANN <- accuracy(fit_ANN)$RMSE
cat("The RMSE for the ETS(A,N,N) model is:", rmse_ANN, "\n")
## The RMSE for the ETS(A,N,N) model is: 1.816383
fit_AAN <- greece_exports %>%
model(ETS(Exports ~ error("A") + trend("A") + season("N")))
# Generate and plot forecasts
fc_AAN <- forecast(fit_AAN, h = "5 years")
autoplot(fc_AAN) +
labs(title = "Forecasts of Greece Exports (ETS(A,A,N))", y = "Exports (in USD)", x = "Year")
rmse_AAN <- accuracy(fit_AAN)$RMSE
cat("The RMSE for the ETS(A,A,N) model is:", rmse_AAN, "\n")
## The RMSE for the ETS(A,A,N) model is: 1.765767
# Generate forecasts for the next periods
forecast_ANN <- forecast(fit_ANN, h = 4) # Forecast for the next 4 periods
forecast_AAN <- forecast(fit_AAN, h = 4)
## Calculated by R
forecast_ANN %>% hilo(95) %>% pull('95%') %>% head(1)
## <hilo[1]>
## [1] [29.5966, 36.84272]95
forecast_AAN %>% hilo(95) %>% pull('95%') %>% head(1)
## <hilo[1]>
## [1] [30.07503, 37.24849]95
## Calculated by hand
forecast_AAN <- fit_AAN %>% forecast(h = 4)
forecast_ANN <- fit_ANN %>% forecast(h = 4)
y_hat_AAN <- forecast_AAN$.mean[1]
rmse_AAN <- accuracy(fit_AAN)$RMSE
# Get the first forecast value and RMSE for ETS(A,N,N)
y_hat_ANN <- forecast_ANN$.mean[1]
rmse_ANN <- accuracy(fit_ANN)$RMSE
z <- 1.96
# Calculate prediction intervals for ETS(A,N,N)
lower_ANN <- y_hat_ANN - z * rmse_ANN
upper_ANN <- y_hat_ANN + z * rmse_ANN
# Calculate prediction intervals for ETS(A,A,N)
lower_AAN <- y_hat_AAN - z * rmse_AAN
upper_AAN <- y_hat_AAN + z * rmse_AAN
cat("Prediction Interval for ETS(A,N,N): [", lower_ANN, ", ", upper_ANN, "]\n")
## Prediction Interval for ETS(A,N,N): [ 29.65955 , 36.77977 ]
cat("Prediction Interval for ETS(A,A,N): [", lower_AAN, ", ", upper_AAN, "]\n")
## Prediction Interval for ETS(A,A,N): [ 30.20086 , 37.12266 ]
Lambda_china <- global_economy %>%
filter(Country == "China") %>%
features(GDP, features = guerrero) %>%
pull(lambda_guerrero)
China_fit <- global_economy %>%
filter(Country == "China") %>%
model(`Standard` = ETS(GDP ~ error("A") + trend("N") + season("N")),
`Holt's method` = ETS(GDP ~ error("A") + trend("A") + season("N")),
`Damped Holt's method` = ETS(GDP ~ error("A") + trend("Ad", phi = 0.8) + season("N")),
`Box-Cox` = ETS(box_cox(GDP,Lambda_china) ~ error("A") + trend("Ad") + season("N")),
`Damped Box-Cox` = ETS(box_cox(GDP,Lambda_china) ~ error("A") + trend("Ad", phi = 0.8) + season("N")))
China_fc <- China_fit %>%
forecast(h = 20)
China_fc %>%
autoplot(global_economy, level = NULL) +
labs(title="Chinese GDP") +
guides(colour = guide_legend(title = "Forecast"))
gas_data <- aus_production %>%
filter(Gas > 0)
aus_production %>%
autoplot(Gas)
# Fit different ETS models including multiplicative seasonality and damped trend
fitted_models <- gas_data %>%
model(
simple_additive = ETS(Gas ~ error('A') + trend("A") + season("N")),
simple_mult = ETS(Gas ~ error("M") + trend("A") + season("N")),
seasonality_add = ETS(Gas ~ error('A') + trend("A") + season("A")),
seasonality_mult = ETS(Gas ~ error("M") + trend("A") + season("M")),
mult_season_damp = ETS(Gas ~ error("M") + trend("Ad") + season("M"))
)
# Generate forecasts for the next 10 time periods
forecasts <- fitted_models %>% forecast(h = 10)
# Plot the forecasts with the original data
forecasts %>%
autoplot(gas_data, level = NULL) +
labs(y = "Gas Production", title = "Forecasts of Australian Gas Production") +
facet_wrap(~ .model, scales = "free_y")
accuracy(fitted_models)
## # A tibble: 5 × 10
## .model .type ME RMSE MAE MPE MAPE MASE RMSSE ACF1
## <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 simple_additive Traini… 0.442 15.7 11.7 1.05 14.3 2.11 2.07 0.118
## 2 simple_mult Traini… -0.0787 16.4 11.9 -1.32 13.5 2.14 2.16 0.0888
## 3 seasonality_add Traini… 0.00525 4.76 3.35 -4.69 10.9 0.600 0.628 0.0772
## 4 seasonality_mult Traini… -0.115 4.60 3.02 0.199 4.08 0.542 0.606 -0.0131
## 5 mult_season_damp Traini… -0.00439 4.59 3.03 0.326 4.10 0.544 0.606 -0.0217
set.seed(2601)
myseries <- aus_retail %>%
filter(`Series ID` == sample(aus_retail$`Series ID`,1))
myseries %>% autoplot()
## Plot variable not specified, automatically selected `.vars = Turnover`
# Fit the Holt-Winters’ multiplicative models
fit <- myseries %>% model(
Multi_Season = ETS(Turnover ~ error("M") + trend("A") + season("M")),
Multi_Season_Damp = ETS(Turnover ~ error("M") + trend("Ad") + season("M"))
)
# Forecast the next 32 months
fc <- fit %>% forecast(h = 32)
# Plot the forecasts for both models along with the original data
fc %>%
autoplot(myseries, level = NULL) +
labs(y = "AUD") +
theme_minimal()
accuracy(fit) %>%
select(.model, RMSE)
## # A tibble: 2 × 2
## .model RMSE
## <chr> <dbl>
## 1 Multi_Season 3.05
## 2 Multi_Season_Damp 3.07
best_fit <- myseries %>% model(
Multi_Season = ETS(Turnover ~ error("M") + trend("A") + season("M"))
)
gg_tsresiduals(best_fit)
set.seed(2601)
train <- myseries %>%
filter(year(Month) < 2011)
# Test data: from 2011 onwards
test <- myseries %>%
filter(year(Month) >= 2011)
fit <- train %>%
model(
'Holt Winters Multiplicative Method' = ETS(Turnover ~ error('M') + trend('A') + season('M')),
'Holt Winters Damped Method' = ETS(Turnover ~ error('M') + trend('Ad') + season('M')),
'Seasonal Naive' = SNAIVE(Turnover)
)
comp <- anti_join(myseries, train, by = c('State', 'Industry', 'Series ID', 'Month', 'Turnover'))
fc <- fit %>% forecast(comp)
autoplot(comp, Turnover) +
autolayer(fc, level = NULL) +
labs(title = 'Forecast Method Comparison')
# Extract forecasted values for each model and convert to a tibble
forecast_values <- fc %>%
as_tibble() %>%
select(Month, .model, .mean)
# Convert test data to tibble
test_tibble <- test %>%
select(Month, Turnover) %>%
as_tibble()
# Merge forecasted values with actual test values by 'Month'
comparison <- test_tibble %>%
left_join(forecast_values, by = "Month")
# Calculate squared errors between actual and forecasted values
comparison <- comparison %>%
mutate(squared_error = (Turnover - .mean)^2)
# Calculate RMSE manually for each model
rmse_manual <- comparison %>%
group_by(.model) %>%
summarise(RMSE = sqrt(mean(squared_error, na.rm = TRUE)))
rmse_manual
## # A tibble: 3 × 2
## .model RMSE
## <chr> <dbl>
## 1 Holt Winters Damped Method 10.2
## 2 Holt Winters Multiplicative Method 13.1
## 3 Seasonal Naive 6.12
lambda_train <- train %>%
features(Turnover, features = guerrero) %>%
pull(lambda_guerrero)
box_cox_myseries <- train %>%
mutate(
bc = box_cox(Turnover, lambda_train)
)
fit2 <- box_cox_myseries %>%
model(
'STL Box-Cox' = STL(bc ~ season(window = 'periodic'), robust = TRUE),
'ETS Box-Cox' = ETS(bc)
)
fit3 <- box_cox_myseries %>%
model(
'Holt Winters Multiplicative Method' = ETS(Turnover ~ error('M') + trend('A') + season('M'))
)
accuracy(fit2)
## # A tibble: 2 × 12
## State Industry .model .type ME RMSE MAE MPE MAPE MASE RMSSE
## <chr> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 Wester… Footwea… STL B… Trai… 0.00329 0.0562 0.0426 0.0570 1.24 0.354 0.375
## 2 Wester… Footwea… ETS B… Trai… -0.00123 0.0676 0.0529 -0.0545 1.52 0.440 0.451
## # ℹ 1 more variable: ACF1 <dbl>
accuracy(fit3)
## # A tibble: 1 × 12
## State Industry .model .type ME RMSE MAE MPE MAPE MASE RMSSE ACF1
## <chr> <chr> <chr> <chr> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
## 1 West… Footwea… Holt … Trai… 0.175 2.68 1.72 0.00277 4.63 0.473 0.500 0.0586