Time Series Analysis

Author

SB

# clear envirmonment 
remove(list = ls())

#load packages
#install.packages("tidyquant")
library(tidyquant)
Registered S3 method overwritten by 'quantmod':
  method            from
  as.zoo.data.frame zoo 
── Attaching core tidyquant packages ─────────────────────── tidyquant 1.0.11 ──
✔ PerformanceAnalytics 2.0.8      ✔ TTR                  0.24.4
✔ quantmod             0.4.28     ✔ xts                  0.14.1
── Conflicts ────────────────────────────────────────── tidyquant_conflicts() ──
✖ zoo::as.Date()                 masks base::as.Date()
✖ zoo::as.Date.numeric()         masks base::as.Date.numeric()
✖ PerformanceAnalytics::legend() masks graphics::legend()
✖ quantmod::summary()            masks base::summary()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
#install.packages(fpp3)
library(fpp3)
Registered S3 method overwritten by 'tsibble':
  method               from 
  as_tibble.grouped_df dplyr
── Attaching packages ──────────────────────────────────────────── fpp3 1.0.1 ──
✔ tibble      3.3.0     ✔ tsibble     1.1.6
✔ dplyr       1.1.4     ✔ tsibbledata 0.4.1
✔ tidyr       1.3.1     ✔ feasts      0.4.1
✔ lubridate   1.9.4     ✔ fable       0.4.1
✔ ggplot2     3.5.2     
── Conflicts ───────────────────────────────────────────────── fpp3_conflicts ──
✖ lubridate::date()    masks base::date()
✖ dplyr::filter()      masks stats::filter()
✖ dplyr::first()       masks xts::first()
✖ tsibble::index()     masks zoo::index()
✖ tsibble::intersect() masks base::intersect()
✖ tsibble::interval()  masks lubridate::interval()
✖ dplyr::lag()         masks stats::lag()
✖ dplyr::last()        masks xts::last()
✖ tsibble::setdiff()   masks base::setdiff()
✖ tsibble::union()     masks base::union()
✖ fable::VAR()         masks tidyquant::VAR()

Attaching package: 'fpp3'

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

    prices
tq_get("PG", get = "stock.price")
# A tibble: 2,661 × 8
   symbol date        open  high   low close  volume adjusted
   <chr>  <date>     <dbl> <dbl> <dbl> <dbl>   <dbl>    <dbl>
 1 PG     2015-01-02  90.8  91    89.9  90.4 7251400     67.0
 2 PG     2015-01-05  90.2  91    89.8  90.0 8626100     66.7
 3 PG     2015-01-06  90.3  90.6  89.3  89.6 7791200     66.4
 4 PG     2015-01-07  89.9  90.4  89.6  90.1 5986600     66.7
 5 PG     2015-01-08  90.5  91.2  90.1  91.1 6823300     67.5
 6 PG     2015-01-09  91.2  91.2  90.1  90.2 4872800     66.8
 7 PG     2015-01-12  90.5  90.6  89.5  89.9 5250900     66.6
 8 PG     2015-01-13  90.8  91.5  89.8  90.3 6727100     66.9
 9 PG     2015-01-14  89.7  90.2  89.4  90.0 6418200     66.7
10 PG     2015-01-15  90.5  90.5  89.3  89.9 6768200     66.6
# ℹ 2,651 more rows
sp_500 <- tq_index("SP500") %>%
  tq_get(get = "stock.prices")
Getting holdings for SP500
Warning: There was 1 warning in `dplyr::mutate()`.
ℹ In argument: `data.. = purrr::map(...)`.
Caused by warning:
! x = '-', get = 'stock.prices': Error in getSymbols.yahoo(Symbols = "-", env = <environment>, verbose = FALSE, : Unable to import "-".
cannot open the connection
 Removing -.
?as_tsibble
Help on topic 'as_tsibble' was found in the following packages:

  Package               Library
  tsibble               /Library/Frameworks/R.framework/Versions/4.5-arm64/Resources/library
  fable                 /Library/Frameworks/R.framework/Versions/4.5-arm64/Resources/library
  feasts                /Library/Frameworks/R.framework/Versions/4.5-arm64/Resources/library
  fabletools            /Library/Frameworks/R.framework/Versions/4.5-arm64/Resources/library


Using the first match ...
df_daily <- 
tq_get(x = "PG",
       get = "stock.prices", 
        from = "1992-01-01")

PG_data_monthly <- df_daily %>%
  mutate(month = yearmonth(date)
         ) %>%
  group_by(month) %>%
  summarise(adjusted = mean(adjusted)
            ) %>%
as_tsibble(index = month)

write.csv(x = PG_data_monthly, file = "PG_monthly_data.csv")
train <- PG_data_monthly[1:323,]
test <- PG_data_monthly[324:404,]
# fit models
models_PG <- model(
  train,
  ETS = ETS(adjusted),
  NAIVE = NAIVE(adjusted),
  SNAIVE = SNAIVE(adjusted)
)
h <- nrow(test)
fc_PG <- forecast(models_PG, h = h)
autoplot(fc_PG, train)