---
title: "Forecasting Models"
author: "Prof. Eric A. Suess"
date: "2/11/2026"
format: 
  html:
    embed-resources: true
    page-layout: full
    df-print: paged
---


## Models

```{r cars}
library(pacman)
p_load(tidyverse, fpp3)
```


```{r}
global_economy

global_economy |> filter(Country == "Italy") |> 
  autoplot()
```

```{r}
gdppc_Italy <- global_economy |>
  filter(Country == "Italy") |> 
  mutate(GDP_per_capita = GDP / Population) 

gdppc_Italy |> autoplot(GDP_per_capita)
```

Train the model (estimate)

```{r}
gdppc <- global_economy |>
  mutate(GDP_per_capita = GDP / Population) 

fit <- gdppc |>
  model(trend_model = TSLM(GDP_per_capita ~ trend()))
fit 
```

Forecasts

```{r}
fit |> forecast(h = "3 years")
```

```{r}
fit |>
  forecast(h = "3 years") |>
  filter(Country == "Italy") |>
  autoplot(gdppc) +
  labs(y = "$US", title = "GDP per capita for Sweden")
```

Simple forecasting methods

```{r}
aus_production |> filter_index("1970 Q1" ~ "2004 Q4")
```
```{r}
# 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"))
```

Residuals and Fitted Values

```{r}
aug <- augment(beer_fit)
aug
```
```{r}
autoplot(aug, .innov) +
  labs(x = "Day", y = "Residual", 
       title = "Residuals")
```


```{r}
aug |>
  ggplot(aes(x = .innov)) +
  geom_histogram() +
  labs(title = "Histogram of residuals")
```

```{r}
aug |>
  ACF(.innov) |>
  autoplot() +
  labs(title = "ACF of residuals")
```

```{r}
aug |> features(.innov, box_pierce, lag = 10)


aug |> features(.innov, ljung_box, lag = 10)
```

