library(pacman)
p_load(tidyverse, fpp3)Forecasting Models
Models
global_economyglobal_economy |> filter(Country == "Italy") |>
autoplot()Plot variable not specified, automatically selected `.vars = GDP`
gdppc_Italy <- global_economy |>
filter(Country == "Italy") |>
mutate(GDP_per_capita = GDP / Population)
gdppc_Italy |> autoplot(GDP_per_capita)Train the model (estimate)
gdppc <- global_economy |>
mutate(GDP_per_capita = GDP / Population)
fit <- gdppc |>
model(trend_model = TSLM(GDP_per_capita ~ trend()))Warning: 7 errors (1 unique) encountered for trend_model
[7] 0 (non-NA) cases
fit Forecasts
fit |> forecast(h = "3 years")fit |>
forecast(h = "3 years") |>
filter(Country == "Italy") |>
autoplot(gdppc) +
labs(y = "$US", title = "GDP per capita for Sweden")Simple forecasting methods
aus_production |> filter_index("1970 Q1" ~ "2004 Q4")# Set training data from 1992 to 2006
train <- aus_production |>
filter_index("1992 Q1" ~ "2006 Q4")
# Fit the models
beer_fit <- train |>
model(
Mean = MEAN(Beer),
`Naïve` = NAIVE(Beer),
`Seasonal naïve` = SNAIVE(Beer)
)
# Generate forecasts for 14 quarters
beer_fc <- beer_fit |> forecast(h = 14)
# Plot forecasts against actual values
beer_fc |>
autoplot(train, level = NULL) +
autolayer(
filter_index(aus_production, "2007 Q1" ~ .),
color = "black"
) +
labs(
y = "Megalitres",
title = "Forecasts for quarterly beer production"
) +
guides(colour = guide_legend(title = "Forecast"))Plot variable not specified, automatically selected `.vars = Beer`
Residuals and Fitted Values
aug <- augment(beer_fit)
augautoplot(aug, .innov) +
labs(x = "Day", y = "Residual",
title = "Residuals")Warning: Removed 5 rows containing missing values or values outside the scale range
(`geom_line()`).
aug |>
ggplot(aes(x = .innov)) +
geom_histogram() +
labs(title = "Histogram of residuals")`stat_bin()` using `bins = 30`. Pick better value `binwidth`.
Warning: Removed 5 rows containing non-finite outside the scale range
(`stat_bin()`).
aug |>
ACF(.innov) |>
autoplot() +
labs(title = "ACF of residuals")aug |> features(.innov, box_pierce, lag = 10)aug |> features(.innov, ljung_box, lag = 10)