Forcasting

#|message: false

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(fpp3)
── Attaching packages ────────────────────────────────────────────── fpp3 0.5 ──
✔ tsibble     1.1.3     ✔ fable       0.3.3
✔ tsibbledata 0.4.1     ✔ fabletools  0.3.4
✔ feasts      0.3.1     
── Conflicts ───────────────────────────────────────────────── fpp3_conflicts ──
✖ lubridate::date()    masks base::date()
✖ dplyr::filter()      masks stats::filter()
✖ tsibble::intersect() masks base::intersect()
✖ tsibble::interval()  masks lubridate::interval()
✖ dplyr::lag()         masks stats::lag()
✖ tsibble::setdiff()   masks base::setdiff()
✖ tsibble::union()     masks base::union()
mex<- global_economy |> 
  filter(Country=='Mexico') |> 
  drop_na() |> 
  select(-c(Country,Code))
mex
# A tsibble: 57 x 7 [1Y]
    Year         GDP Growth    CPI Imports Exports Population
   <dbl>       <dbl>  <dbl>  <dbl>   <dbl>   <dbl>      <dbl>
 1  1961 14160000000   5.00 0.0131   10.6     8.41   39394126
 2  1962 15200000000   4.66 0.0133   10.1     8.57   40649588
 3  1963 16960000000   8.11 0.0133    9.95    8.32   41939880
 4  1964 20080000000  11.9  0.0137    9.85    7.63   43264272
 5  1965 21840000000   7.10 0.0141    9.52    7.63   44623043
 6  1966 24320000000   6.10 0.0147    9.01    7.47   46011038
 7  1967 26560000000   5.85 0.0152    9.01    6.87   47429812
 8  1968 29360000000   9.42 0.0155    9.35    7.04   48894019
 9  1969 32480000000   3.42 0.0161    9.27    7.55   50423481
10  1970 35520000000   6.50 0.0169    9.66    7.75   52029861
# ℹ 47 more rows
mex |> 
  features(Growth,features=guerrero)
# A tibble: 1 × 1
  lambda_guerrero
            <dbl>
1           0.725
mex |> 
  autoplot(Growth)

mex |> 
  autoplot(box_cox(Growth,lambda=0.7249915))

mex_fit <- mex |> 
  model(
    media=MEAN(box_cox(Growth,lambda=0.7249915)),
    naive=NAIVE(box_cox(Growth,lambda=0.7249915)),
    drift=RW(box_cox(Growth,lambda=0.7249915)~drift())
  )
mex_fit
# A mable: 1 x 3
    media   naive         drift
  <model> <model>       <model>
1  <MEAN> <NAIVE> <RW w/ drift>
## Diagnostico de residuos (enfocar en innovaciones)

mex_fit |> 
  augment()
# A tsibble: 171 x 6 [1Y]
# Key:       .model [3]
   .model  Year Growth .fitted  .resid  .innov
   <chr>  <dbl>  <dbl>   <dbl>   <dbl>   <dbl>
 1 media   1961   5.00    3.45  1.55    1.04  
 2 media   1962   4.66    3.45  1.21    0.826 
 3 media   1963   8.11    3.45  4.65    2.90  
 4 media   1964  11.9     3.45  8.45    4.92  
 5 media   1965   7.10    3.45  3.65    2.33  
 6 media   1966   6.10    3.45  2.64    1.73  
 7 media   1967   5.85    3.45  2.40    1.58  
 8 media   1968   9.42    3.45  5.97    3.63  
 9 media   1969   3.42    3.45 -0.0339 -0.0242
10 media   1970   6.50    3.45  3.05    1.97  
# ℹ 161 more rows
mex_fit |> 
  augment() |> 
  features(.innov, ljung_box, lag = 10, dof=0)
# A tibble: 3 × 3
  .model lb_stat lb_pvalue
  <chr>    <dbl>     <dbl>
1 drift     16.5    0.0863
2 media     15.1    0.128 
3 naive     16.5    0.0863

Como el p-value de los tres modelos es mayor a nuestra \(\alpha\) ; \(p_{value} = 0.05\) , NO RECHAZAMOS \(H_0 :: \text {'los residuos son ruido blanco'}\)

mex_fit |> 
  select(media) |> 
  gg_tsresiduals()

mex_fit |> 
  select(naive) |> 
  gg_tsresiduals()
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()`).

mex_fit |> 
  select(drift) |> 
  gg_tsresiduals()
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()`).

##Forecast

mex_fc <- mex_fit |> 
  forecast(h= '6 years')

mex_fc
# A fable: 18 x 4 [1Y]
# Key:     .model [3]
   .model  Year         Growth .mean
   <chr>  <dbl>         <dist> <dbl>
 1 media   2018     t(N(2, 8))  4.08
 2 media   2019     t(N(2, 8))  4.08
 3 media   2020     t(N(2, 8))  4.08
 4 media   2021     t(N(2, 8))  4.08
 5 media   2022     t(N(2, 8))  4.08
 6 media   2023     t(N(2, 8))  4.08
 7 naive   2018 t(N(0.93, 11))  3.15
 8 naive   2019 t(N(0.93, 22))  4.26
 9 naive   2020 t(N(0.93, 33))  5.37
10 naive   2021 t(N(0.93, 44))  6.48
11 naive   2022 t(N(0.93, 56))  7.59
12 naive   2023 t(N(0.93, 67))  8.69
13 drift   2018  t(N(0.9, 12))  3.16
14 drift   2019 t(N(0.86, 23))  4.34
15 drift   2020 t(N(0.82, 36))  5.59
16 drift   2021 t(N(0.78, 49))  6.90
17 drift   2022 t(N(0.75, 62))  8.30
18 drift   2023 t(N(0.71, 75))  9.76
mex_fc |> 
  autoplot(mex) +
  facet_wrap(~.model)

 # theme(legend.position = 'none')

Repaso

aus_livestock |> 
  distinct(Animal)
# A tibble: 7 × 1
  Animal                    
  <fct>                     
1 Bulls, bullocks and steers
2 Calves                    
3 Cattle (excl. calves)     
4 Cows and heifers          
5 Lambs                     
6 Pigs                      
7 Sheep                     
ovejas <- aus_livestock |> 
  filter(Animal == 'Sheep',
         State == 'New South Wales')

ovejas
# A tsibble: 558 x 4 [1M]
# Key:       Animal, State [1]
       Month Animal State            Count
       <mth> <fct>  <fct>            <dbl>
 1 1972 jul. Sheep  New South Wales 669400
 2 1972 ago. Sheep  New South Wales 581100
 3 1972 sep. Sheep  New South Wales 468100
 4 1972 oct. Sheep  New South Wales 515300
 5 1972 nov. Sheep  New South Wales 564500
 6 1972 dic. Sheep  New South Wales 565400
 7 1973 ene. Sheep  New South Wales 630300
 8 1973 feb. Sheep  New South Wales 528900
 9 1973 mar. Sheep  New South Wales 594500
10 1973 abr. Sheep  New South Wales 443000
# ℹ 548 more rows
ovejas |> 
  autoplot(Count)

Trains/test

ovejas_train <- ovejas |>
  filter_index(.~'Dec. 2012')

ovejas_train
# A tsibble: 486 x 4 [1M]
# Key:       Animal, State [1]
       Month Animal State            Count
       <mth> <fct>  <fct>            <dbl>
 1 1972 jul. Sheep  New South Wales 669400
 2 1972 ago. Sheep  New South Wales 581100
 3 1972 sep. Sheep  New South Wales 468100
 4 1972 oct. Sheep  New South Wales 515300
 5 1972 nov. Sheep  New South Wales 564500
 6 1972 dic. Sheep  New South Wales 565400
 7 1973 ene. Sheep  New South Wales 630300
 8 1973 feb. Sheep  New South Wales 528900
 9 1973 mar. Sheep  New South Wales 594500
10 1973 abr. Sheep  New South Wales 443000
# ℹ 476 more rows
ovejas_train |> 
  autoplot(Count)

lambda<- ovejas_train |> 
  features(Count, features= guerrero) |> 
  pull(lambda_guerrero)
lambda
[1] 0.5806898
ovejas_train |> 
  autoplot(box_cox(Count, lambda))

Season plot

ovejas_train |> 
  gg_season(Count)

ovejas_train |> 
  gg_season(box_cox(Count, lambda))

ovejas_train |> 
  features(Count, feat_stl)
# A tibble: 1 × 11
  Animal State          trend_strength seasonal_strength_year seasonal_peak_year
  <fct>  <fct>                   <dbl>                  <dbl>              <dbl>
1 Sheep  New South Wal…          0.914                  0.584                  9
# ℹ 6 more variables: seasonal_trough_year <dbl>, spikiness <dbl>,
#   linearity <dbl>, curvature <dbl>, stl_e_acf1 <dbl>, stl_e_acf10 <dbl>

STL Decomposition

ovejas_train |> 
  model(
    stl = STL(box_cox(Count, lambda), robust= TRUE)
  ) |> 
  components() |> 
  autoplot()

ovejas_fit <- ovejas_train |> 
  model(
    snaive_bc = SNAIVE(box_cox(Count, lambda)),
    snaive = SNAIVE(Count),
    combi_bc= decomposition_model(
      STL(box_cox(Count, lambda), robust= TRUE),
      SNAIVE(season_year),
      RW(season_adjust ~ drift())
    ),
    combi=decomposition_model(
      STL(Count, robust= TRUE),
      SNAIVE(season_year),
      RW(season_adjust ~ drift())
    )
  )

ovejas_fit
# A mable: 1 x 6
# Key:     Animal, State [1]
  Animal State           snaive_bc   snaive                  combi_bc
  <fct>  <fct>             <model>  <model>                   <model>
1 Sheep  New South Wales  <SNAIVE> <SNAIVE> <STL decomposition model>
# ℹ 1 more variable: combi <model>

Prueba autocorrelacion

ovejas_fit |> 
  select(snaive_bc) |> 
  gg_tsresiduals()
Warning: Removed 12 rows containing missing values (`geom_line()`).
Warning: Removed 12 rows containing missing values (`geom_point()`).
Warning: Removed 12 rows containing non-finite values (`stat_bin()`).

ovejas_fit |> 
  select(combi) |> 
  gg_tsresiduals() 
Warning: Removed 12 rows containing missing values (`geom_line()`).
Warning: Removed 12 rows containing missing values (`geom_point()`).
Warning: Removed 12 rows containing non-finite values (`stat_bin()`).

ovejas_fit |> 
  augment() |> 
  features(.innov, ljung_box, dof = 0, lag = 24)
# A tibble: 4 × 5
  Animal State           .model    lb_stat lb_pvalue
  <fct>  <fct>           <chr>       <dbl>     <dbl>
1 Sheep  New South Wales combi        145.         0
2 Sheep  New South Wales combi_bc     138.         0
3 Sheep  New South Wales snaive      1021.         0
4 Sheep  New South Wales snaive_bc   1098.         0
accuracy(ovejas_fit) |> 
  arrange(MAPE)
# A tibble: 4 × 12
  Animal State      .model .type      ME   RMSE    MAE     MPE  MAPE  MASE RMSSE
  <fct>  <fct>      <chr>  <chr>   <dbl>  <dbl>  <dbl>   <dbl> <dbl> <dbl> <dbl>
1 Sheep  New South… combi… Trai…    451. 4.70e4 34632.  -1.16   12.1 0.458 0.457
2 Sheep  New South… combi  Trai…    713. 4.73e4 34649.  -0.863  12.3 0.459 0.459
3 Sheep  New South… snaiv… Trai… -10469. 1.03e5 75551. -11.7    30.7 1     1    
4 Sheep  New South… snaive Trai… -10469. 1.03e5 75551. -11.7    30.7 1     1    
# ℹ 1 more variable: ACF1 <dbl>

Forecast

ovejas_fc <- ovejas_fit |> 
  forecast(h= '6 years')

ovejas_fc
# A fable: 288 x 6 [1M]
# Key:     Animal, State, .model [4]
   Animal State           .model        Month              Count   .mean
   <fct>  <fct>           <chr>         <mth>             <dist>   <dbl>
 1 Sheep  New South Wales snaive_bc 2013 ene. t(N(1435, 255334)) 115655.
 2 Sheep  New South Wales snaive_bc 2013 feb. t(N(1304, 255334))  99577.
 3 Sheep  New South Wales snaive_bc 2013 mar. t(N(1251, 255334))  93376.
 4 Sheep  New South Wales snaive_bc 2013 abr. t(N(1157, 255334))  82864.
 5 Sheep  New South Wales snaive_bc 2013 may. t(N(1293, 255334))  98198.
 6 Sheep  New South Wales snaive_bc 2013 jun. t(N(1020, 255334))  68775.
 7 Sheep  New South Wales snaive_bc 2013 jul. t(N(1163, 255334))  83551.
 8 Sheep  New South Wales snaive_bc 2013 ago. t(N(1355, 255334)) 105589.
 9 Sheep  New South Wales snaive_bc 2013 sep. t(N(1708, 255334)) 152765.
10 Sheep  New South Wales snaive_bc 2013 oct. t(N(2119, 255334)) 217309.
# ℹ 278 more rows
ovejas_fc |> 
  autoplot(ovejas |> filter_index('Jan. 2003'~ .) , level = NULL)

ovejas_fc |> 
  accuracy(ovejas) |> 
  arrange(MAPE)
# A tibble: 4 × 12
  .model  Animal State .type      ME   RMSE    MAE   MPE  MAPE  MASE RMSSE  ACF1
  <chr>   <fct>  <fct> <chr>   <dbl>  <dbl>  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1 combi_… Sheep  New … Test  -10324. 47074. 40622. -11.3  25.8 0.538 0.457 0.759
2 snaive… Sheep  New … Test   36872. 65520. 54675.  16.9  29.5 0.724 0.637 0.744
3 snaive  Sheep  New … Test   65819. 85025. 73106.  34.0  39.1 0.968 0.826 0.731
4 combi   Sheep  New … Test   80445. 94525. 80445.  42.2  42.2 1.06  0.918 0.797

Forecast a futuro

ovejas |> 
  model(
    combi_bc= decomposition_model(
      STL(box_cox(Count, lambda), robust= TRUE),
      SNAIVE(season_year),
      RW(season_adjust ~ drift()))
    
    
  ) |> 
  
  forecast(h='6 years') |> 
  autoplot(ovejas)