Tarea ETS

library(tidyverse)
── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
✔ dplyr     1.1.4     ✔ readr     2.1.5
✔ forcats   1.0.0     ✔ stringr   1.5.1
✔ ggplot2   3.4.4     ✔ tibble    3.2.1
✔ lubridate 1.9.3     ✔ tidyr     1.3.0
✔ purrr     1.0.2     
── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
✖ dplyr::filter() masks stats::filter()
✖ dplyr::lag()    masks stats::lag()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(tsibble)

Attaching package: 'tsibble'

The following object is masked from 'package:lubridate':

    interval

The following objects are masked from 'package:base':

    intersect, setdiff, union
library(feasts)
Loading required package: fabletools
library(fable)
library(tsibbledata)
library(fpp3)
library(plotly)

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
aus_production
# A tsibble: 218 x 7 [1Q]
   Quarter  Beer Tobacco Bricks Cement Electricity   Gas
     <qtr> <dbl>   <dbl>  <dbl>  <dbl>       <dbl> <dbl>
 1 1956 Q1   284    5225    189    465        3923     5
 2 1956 Q2   213    5178    204    532        4436     6
 3 1956 Q3   227    5297    208    561        4806     7
 4 1956 Q4   308    5681    197    570        4418     6
 5 1957 Q1   262    5577    187    529        4339     5
 6 1957 Q2   228    5651    214    604        4811     7
 7 1957 Q3   236    5317    227    603        5259     7
 8 1957 Q4   320    6152    222    582        4735     6
 9 1958 Q1   272    5758    199    554        4608     5
10 1958 Q2   233    5641    229    620        5196     7
# ℹ 208 more rows
global_economy
# A tsibble: 15,150 x 9 [1Y]
# Key:       Country [263]
   Country     Code   Year         GDP Growth   CPI Imports Exports Population
   <fct>       <fct> <dbl>       <dbl>  <dbl> <dbl>   <dbl>   <dbl>      <dbl>
 1 Afghanistan AFG    1960  537777811.     NA    NA    7.02    4.13    8996351
 2 Afghanistan AFG    1961  548888896.     NA    NA    8.10    4.45    9166764
 3 Afghanistan AFG    1962  546666678.     NA    NA    9.35    4.88    9345868
 4 Afghanistan AFG    1963  751111191.     NA    NA   16.9     9.17    9533954
 5 Afghanistan AFG    1964  800000044.     NA    NA   18.1     8.89    9731361
 6 Afghanistan AFG    1965 1006666638.     NA    NA   21.4    11.3     9938414
 7 Afghanistan AFG    1966 1399999967.     NA    NA   18.6     8.57   10152331
 8 Afghanistan AFG    1967 1673333418.     NA    NA   14.2     6.77   10372630
 9 Afghanistan AFG    1968 1373333367.     NA    NA   15.2     8.90   10604346
10 Afghanistan AFG    1969 1408888922.     NA    NA   15.0    10.1    10854428
# ℹ 15,140 more rows
gdp <- tidyquant::tq_get(
  x    = "NGDPRSAXDCBRQ",
  get  = "economic.data",
  from = "1997-01-01"
)
Registered S3 method overwritten by 'quantmod':
  method            from
  as.zoo.data.frame zoo 
gdp <- gdp |> 
  mutate(date = yearquarter(date)) |> 
  as_tsibble(
    index = date,
    key   = symbol
  )

gdp_train <- gdp |> 
  filter_index(. ~ "2020 Q4")

gdp_train
# A tsibble: 96 x 3 [1Q]
# Key:       symbol [1]
   symbol           date   price
   <chr>           <qtr>   <dbl>
 1 NGDPRSAXDCBRQ 1997 Q1 183938.
 2 NGDPRSAXDCBRQ 1997 Q2 185608.
 3 NGDPRSAXDCBRQ 1997 Q3 187566.
 4 NGDPRSAXDCBRQ 1997 Q4 189084 
 5 NGDPRSAXDCBRQ 1998 Q1 185663.
 6 NGDPRSAXDCBRQ 1998 Q2 188338.
 7 NGDPRSAXDCBRQ 1998 Q3 188495.
 8 NGDPRSAXDCBRQ 1998 Q4 186331.
 9 NGDPRSAXDCBRQ 1999 Q1 186906 
10 NGDPRSAXDCBRQ 1999 Q2 187512.
# ℹ 86 more rows
p <- gdp_train |> 
  autoplot(price) +
  labs(
    title = "Time series plot of the Real GDP for Mexico",
    y = "GDP"
  )
 
ggplotly(p, dynamicTicks = TRUE) |> 
  rangeslider()
gdp_train |> 
  gg_season(price) |> 
  ggplotly()
gdp_train |> 
  model(stl = STL(price, robust = TRUE)) |> 
  components() |> 
  autoplot() |> 
  ggplotly()
gdp_train |> 
  autoplot(log(price)) +
  ggtitle("Log of the Real GDP of Brazil")

gdp_train |> 
  model(stl = STL(log(price) ~ season(window = "periodic"), robust = TRUE)) |> 
  components() |> 
  autoplot() |> 
  ggplotly()
gdp_fit <- gdp_train |> 
  model(
    snaive = SNAIVE(log(price)),
    drift  = RW(log(price) ~ drift())
  )
gdp_fit |> 
  select(snaive) |> 
  gg_tsresiduals() +
  ggtitle("Residuals Diagnostics for the Seasonal Naïve Model")
Warning: Removed 4 rows containing missing values (`geom_line()`).
Warning: Removed 4 rows containing missing values (`geom_point()`).
Warning: Removed 4 rows containing non-finite values (`stat_bin()`).

gdp_fit |> 
  select(drift) |> 
  gg_tsresiduals() +
  ggtitle("Residuals Diagnostics for the Drift Model")
Warning: Removed 1 row containing missing values (`geom_line()`).
Warning: Removed 1 rows containing missing values (`geom_point()`).
Warning: Removed 1 rows containing non-finite values (`stat_bin()`).

gdp_fit |> 
  augment() |> 
  features(.innov, ljung_box, lag = 24, dof = 0)
# A tibble: 2 × 4
  symbol        .model lb_stat lb_pvalue
  <chr>         <chr>    <dbl>     <dbl>
1 NGDPRSAXDCBRQ drift     7.84     0.999
2 NGDPRSAXDCBRQ snaive  139.       0    
gdp_train_accu <- accuracy(gdp_fit) |> 
  arrange(MAPE)
gdp_train_accu |> 
  select(symbol:.type, MAPE, RMSE, MAE, MASE)
# A tibble: 2 × 7
  symbol        .model .type     MAPE  RMSE   MAE  MASE
  <chr>         <chr>  <chr>    <dbl> <dbl> <dbl> <dbl>
1 NGDPRSAXDCBRQ drift  Training  1.10 4793. 2851. 0.366
2 NGDPRSAXDCBRQ snaive Training  3.02 9724. 7786. 1    
gdp_fit_dcmp <- gdp_train |> 
      model(
        stlf = decomposition_model(
          STL(log(price) ~ season(window = "periodic"), robust = TRUE),
          RW(season_adjust ~ drift())
        )
      )

gdp_fit_dcmp
# A mable: 1 x 2
# Key:     symbol [1]
  symbol                             stlf
  <chr>                           <model>
1 NGDPRSAXDCBRQ <STL decomposition model>
gdp_fit <- gdp_fit |> 
  left_join(gdp_fit_dcmp)
Joining with `by = join_by(symbol)`
gdp_fit |> 
  accuracy() |> 
  select(symbol:.type, MAPE, RMSE, MAE, MASE) |> 
  arrange(MAPE)
# A tibble: 3 × 7
  symbol        .model .type     MAPE  RMSE   MAE  MASE
  <chr>         <chr>  <chr>    <dbl> <dbl> <dbl> <dbl>
1 NGDPRSAXDCBRQ drift  Training  1.10 4793. 2851. 0.366
2 NGDPRSAXDCBRQ stlf   Training  1.12 4886. 2920. 0.375
3 NGDPRSAXDCBRQ snaive Training  3.02 9724. 7786. 1    
gdp_fit |> 
  select(stlf) |> 
  gg_tsresiduals()
Warning: Removed 4 rows containing missing values (`geom_line()`).
Warning: Removed 4 rows containing missing values (`geom_point()`).
Warning: Removed 4 rows containing non-finite values (`stat_bin()`).

gdp_fit |> 
  augment() |> 
  features(.innov, ljung_box)
# A tibble: 3 × 4
  symbol        .model lb_stat lb_pvalue
  <chr>         <chr>    <dbl>     <dbl>
1 NGDPRSAXDCBRQ drift    0.232  6.30e- 1
2 NGDPRSAXDCBRQ snaive  58.3    2.20e-14
3 NGDPRSAXDCBRQ stlf     0.202  6.53e- 1
gdp_fc <- gdp_fit |> 
  forecast(h = 6) 

gdp_fc
# A fable: 18 x 5 [1Q]
# Key:     symbol, .model [3]
   symbol        .model    date             price   .mean
   <chr>         <chr>    <qtr>            <dist>   <dbl>
 1 NGDPRSAXDCBRQ snaive 2021 Q1  t(N(13, 0.0014)) 297054.
 2 NGDPRSAXDCBRQ snaive 2021 Q2  t(N(13, 0.0014)) 270458.
 3 NGDPRSAXDCBRQ snaive 2021 Q3  t(N(13, 0.0014)) 292060.
 4 NGDPRSAXDCBRQ snaive 2021 Q4  t(N(13, 0.0014)) 302765.
 5 NGDPRSAXDCBRQ snaive 2022 Q1  t(N(13, 0.0029)) 297266.
 6 NGDPRSAXDCBRQ snaive 2022 Q2  t(N(13, 0.0029)) 270651.
 7 NGDPRSAXDCBRQ drift  2021 Q1 t(N(13, 0.00031)) 304186.
 8 NGDPRSAXDCBRQ drift  2021 Q2 t(N(13, 0.00063)) 305832.
 9 NGDPRSAXDCBRQ drift  2021 Q3 t(N(13, 0.00095)) 307487.
10 NGDPRSAXDCBRQ drift  2021 Q4  t(N(13, 0.0013)) 309153.
11 NGDPRSAXDCBRQ drift  2022 Q1  t(N(13, 0.0016)) 310829.
12 NGDPRSAXDCBRQ drift  2022 Q2   t(N(13, 0.002)) 312515.
13 NGDPRSAXDCBRQ stlf   2021 Q1 t(N(13, 0.00031)) 304309.
14 NGDPRSAXDCBRQ stlf   2021 Q2 t(N(13, 0.00063)) 305936.
15 NGDPRSAXDCBRQ stlf   2021 Q3 t(N(13, 0.00096)) 307197.
16 NGDPRSAXDCBRQ stlf   2021 Q4  t(N(13, 0.0013)) 309160.
17 NGDPRSAXDCBRQ stlf   2022 Q1  t(N(13, 0.0016)) 310962.
18 NGDPRSAXDCBRQ stlf   2022 Q2   t(N(13, 0.002)) 312628.
gdp_fc |> 
  autoplot(gdp) +
  facet_wrap(~.model, ncol = 1)

gdp_fc |> 
  filter(.model == "stlf") |> 
  autoplot(gdp)

gdp_fc |> 
  accuracy(gdp) |> 
  select(.model:.type, MAPE, RMSE, MAE, MASE) |> 
  arrange(MAPE)
# A tibble: 3 × 7
  .model symbol        .type  MAPE   RMSE    MAE  MASE
  <chr>  <chr>         <chr> <dbl>  <dbl>  <dbl> <dbl>
1 stlf   NGDPRSAXDCBRQ Test  0.602  1969.  1845. 0.237
2 drift  NGDPRSAXDCBRQ Test  0.617  2046.  1892. 0.243
3 snaive NGDPRSAXDCBRQ Test  6.20  23818. 19134. 2.46 
gdp_fit2 <- gdp |> 
  model(
    stlf = decomposition_model(
          STL(log(price) ~ season(window = "periodic"), robust = TRUE),
          RW(season_adjust ~ drift())
        )
  )
gdp_fit2
# A mable: 1 x 2
# Key:     symbol [1]
  symbol                             stlf
  <chr>                           <model>
1 NGDPRSAXDCBRQ <STL decomposition model>
gdp_fc_fut <- gdp_fit2 |> 
  forecast(h = "3 years")
gdp_fc_fut
# A fable: 12 x 5 [1Q]
# Key:     symbol, .model [1]
   symbol        .model    date             price   .mean
   <chr>         <chr>    <qtr>            <dist>   <dbl>
 1 NGDPRSAXDCBRQ stlf   2023 Q4 t(N(13, 0.00028)) 327224.
 2 NGDPRSAXDCBRQ stlf   2024 Q1 t(N(13, 0.00057)) 329471.
 3 NGDPRSAXDCBRQ stlf   2024 Q2 t(N(13, 0.00087)) 331257.
 4 NGDPRSAXDCBRQ stlf   2024 Q3  t(N(13, 0.0012)) 332607.
 5 NGDPRSAXDCBRQ stlf   2024 Q4  t(N(13, 0.0015)) 334560.
 6 NGDPRSAXDCBRQ stlf   2025 Q1  t(N(13, 0.0018)) 336861.
 7 NGDPRSAXDCBRQ stlf   2025 Q2  t(N(13, 0.0021)) 338691.
 8 NGDPRSAXDCBRQ stlf   2025 Q3  t(N(13, 0.0024)) 340075.
 9 NGDPRSAXDCBRQ stlf   2025 Q4  t(N(13, 0.0027)) 342075.
10 NGDPRSAXDCBRQ stlf   2026 Q1  t(N(13, 0.0031)) 344432.
11 NGDPRSAXDCBRQ stlf   2026 Q2  t(N(13, 0.0034)) 346306.
12 NGDPRSAXDCBRQ stlf   2026 Q3  t(N(13, 0.0038)) 347726.
gdp_fc_fut |> 
  autoplot(gdp)

cement <- aus_production |> 
  select(Cement)

recent_production <- cement %>% filter(year(Quarter) >= 1985)
cement_train <- recent_production %>% filter(year(Quarter) <= 2003)
cement_train
# A tsibble: 76 x 2 [1Q]
   Cement Quarter
    <dbl>   <qtr>
 1   1251 1985 Q1
 2   1456 1985 Q2
 3   1631 1985 Q3
 4   1555 1985 Q4
 5   1375 1986 Q1
 6   1546 1986 Q2
 7   1568 1986 Q3
 8   1561 1986 Q4
 9   1332 1987 Q1
10   1458 1987 Q2
# ℹ 66 more rows
c <- cement_train |> 
  autoplot(Cement)
ggplotly(c, dynamicTicks = TRUE) |> 
  rangeslider()
cement_train |> 
  gg_season(Cement) |> 
  ggplotly()
cement_train|> 
  model(stl = STL(Cement, robust = TRUE)) |> 
  components() |> 
  autoplot() |> 
  ggplotly()
cement_fit <- cement_train |> 
  model(
    snaive = SNAIVE(Cement),
    naive = NAIVE(Cement),
    drift  = RW(Cement ~ drift()),
    stlf = decomposition_model(
          STL(Cement ~ season(window = "periodic"), robust = TRUE),
          RW(season_adjust ~ drift())
        ),
    ets_MAdA = ETS(Cement ~ error("M") + trend("Ad") + season("A")),
    ets_ANM = ETS(Cement ~ error("A") + trend("N") + season("M")),
    ets_AAdN = ETS(Cement ~ error("A") + trend("Ad") + season("N")),
    stl_ets_A = decomposition_model(
      STL(Cement, robust=TRUE),
      ETS(season_year ~ error("A") + trend("N") + season("M")),
      ETS(season_adjust ~ error("A") + trend("N") + season("A"))
    ),
    stl_ets_M = decomposition_model(
      STL(Cement, robust=TRUE),
      ETS(season_year ~ error("A") + trend("N") + season("A")),
      ETS(season_adjust ~ error("A") + trend("Ad") + season("M"))
    )
  )

cement_fit |> 
  select(snaive) |> 
  gg_tsresiduals() +
  ggtitle("Residuals Diagnostics for the Seasonal Naïve Model")
Warning: Removed 4 rows containing missing values (`geom_line()`).
Warning: Removed 4 rows containing missing values (`geom_point()`).
Warning: Removed 4 rows containing non-finite values (`stat_bin()`).

cement_fit |> 
  select(drift) |> 
  gg_tsresiduals() +
  ggtitle("Residuals Diagnostics for the Drift Model")
Warning: Removed 1 row containing missing values (`geom_line()`).
Warning: Removed 1 rows containing missing values (`geom_point()`).
Warning: Removed 1 rows containing non-finite values (`stat_bin()`).

cement_fit |> 
  select(stlf) |> 
  gg_tsresiduals() +
  ggtitle("Residuals Diagnostics for the stlf Model")
Warning: Removed 4 rows containing missing values (`geom_line()`).
Warning: Removed 4 rows containing missing values (`geom_point()`).
Warning: Removed 4 rows containing non-finite values (`stat_bin()`).

cement_fit |> 
  select(ets_MAdA) |> 
  gg_tsresiduals() +
  ggtitle("Residuals Diagnostics for the ets_ANA Model")

cement_fit |> 
  select(ets_ANM) |> 
  gg_tsresiduals() +
  ggtitle("Residuals Diagnostics for the ets_AAdA Model")

cement_fit |> 
  select(ets_AAdN) |> 
  gg_tsresiduals() +
  ggtitle("Residuals Diagnostics for the ets_MAdM Model")

cement_fit |> 
  select(stl_ets_A) |> 
  gg_tsresiduals() +
  ggtitle("Residuals Diagnostics for the stl_ets_A Model")

cement_fit |> 
  select(stl_ets_M) |> 
  gg_tsresiduals() +
  ggtitle("Residuals Diagnostics for the stl_ets_M Model")

cement_fit |> 
  augment() |> 
  features(.innov, ljung_box, lag = 30, dof = 0)
# A tibble: 9 × 3
  .model    lb_stat lb_pvalue
  <chr>       <dbl>     <dbl>
1 drift       239.     0     
2 ets_AAdN    204.     0     
3 ets_ANM      41.2    0.0841
4 ets_MAdA     49.8    0.0130
5 naive       239.     0     
6 snaive      252.     0     
7 stl_ets_A    33.2    0.316 
8 stl_ets_M    49.2    0.0149
9 stlf         44.3    0.0446
cement_train_accu <- accuracy(cement_fit) |> 
  arrange(MAPE)
cement_train_accu |> 
  select(.model, .type, MAPE, RMSE, MAE, MASE)
# A tibble: 9 × 6
  .model    .type     MAPE  RMSE   MAE  MASE
  <chr>     <chr>    <dbl> <dbl> <dbl> <dbl>
1 stl_ets_M Training  4.28  94.4  72.9 0.505
2 ets_MAdA  Training  4.36  96.0  74.1 0.513
3 stlf      Training  4.36 101.   75.3 0.522
4 ets_ANM   Training  4.45  97.5  75.5 0.523
5 stl_ets_A Training  5.70 134.   92.0 0.638
6 ets_AAdN  Training  7.36 151.  122.  0.846
7 drift     Training  8.09 166.  135.  0.934
8 naive     Training  8.17 166.  137.  0.946
9 snaive    Training  8.45 170.  144.  1    
cement_fc <- cement_fit |> 
  forecast(h="7 years")
cement_fc
# A fable: 252 x 4 [1Q]
# Key:     .model [9]
   .model Quarter         Cement .mean
   <chr>    <qtr>         <dist> <dbl>
 1 snaive 2004 Q1 N(1831, 28963)  1831
 2 snaive 2004 Q2 N(1892, 28963)  1892
 3 snaive 2004 Q3 N(2227, 28963)  2227
 4 snaive 2004 Q4 N(2090, 28963)  2090
 5 snaive 2005 Q1 N(1831, 57926)  1831
 6 snaive 2005 Q2 N(1892, 57926)  1892
 7 snaive 2005 Q3 N(2227, 57926)  2227
 8 snaive 2005 Q4 N(2090, 57926)  2090
 9 snaive 2006 Q1 N(1831, 86890)  1831
10 snaive 2006 Q2 N(1892, 86890)  1892
# ℹ 242 more rows
cement_fc |> 
  autoplot(cement|> filter_index("1995 Q1" ~ .), size = 2) +
  facet_wrap(~ .model, ncol = 3) +
  theme(legend.position = "none")

cement_fc |> 
  accuracy(cement) |> 
  select(.model:.type, MAPE, RMSE, MAE, MASE) |> 
  arrange(MAPE)
Warning: The future dataset is incomplete, incomplete out-of-sample data will be treated as missing. 
2 observations are missing between 2010 Q3 and 2010 Q4
# A tibble: 9 × 6
  .model    .type  MAPE  RMSE   MAE  MASE
  <chr>     <chr> <dbl> <dbl> <dbl> <dbl>
1 stlf      Test   7.23  202.  170.  1.77
2 drift     Test   7.64  207.  173.  1.79
3 stl_ets_M Test   9.07  254.  216.  2.24
4 ets_MAdA  Test   9.39  261.  223.  2.32
5 ets_AAdN  Test   9.41  259.  222.  2.31
6 naive     Test   9.91  273.  234.  2.44
7 ets_ANM   Test  10.8   285.  253.  2.63
8 snaive    Test  11.9   323.  279.  2.90
9 stl_ets_A Test  12.4   352.  288.  2.99
cement_fit_fut <- cement_train |> 
  model(
    ets_ANM = ETS(Cement ~ error("A") + trend("N") + season("M"))
    )

cement_fc_fut <- cement_fit_fut |> 
  forecast(h = "6 years")

cement_fc_fut |> 
  autoplot(cement_train)

En este caso el modelo que se utiliza es el de ets_ANM debido a que es el mejor modelo que no rechaza la hipotesis. El modelo utiliza un error aditivo, no muestra tendencia y tiene estacionalidad multiplicativa. Este modelo es el 7mo que mejor se ajusta, sin embargo se utiliza este, ya que los 6 anteriores son rechazados, ya que su P-value es menor a 0.05. El error MAPE del modelo es de 10.80, por lo que se dice que aunque es el mejor modelo, cuenta con un error muy grande.