Day 6

Import

Homework: pick a different stock and a different time period and run this again

rm(list=ls())

library(fpp3)
── Attaching packages ──────────────────────────────────────────── fpp3 1.0.3 ──
✔ tibble      3.3.1     ✔ tsibble     1.2.0
✔ dplyr       1.2.1     ✔ tsibbledata 0.4.1
✔ tidyr       1.3.2     ✔ ggtime      0.2.0
✔ lubridate   1.9.5     ✔ feasts      0.5.0
✔ ggplot2     4.0.3     ✔ fable       0.5.0
── 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()
library(tidyquant)
Registered S3 method overwritten by 'quantmod':
  method            from
  as.zoo.data.frame zoo 
── Attaching core tidyquant packages ─────────────────────── tidyquant 1.0.12 ──
✔ PerformanceAnalytics 2.1.0      ✔ TTR                  0.24.4
✔ quantmod             0.4.29     ✔ xts                  0.14.2
── Conflicts ────────────────────────────────────────── tidyquant_conflicts() ──
✖ zoo::as.Date()                 masks base::as.Date()
✖ zoo::as.Date.numeric()         masks base::as.Date.numeric()
✖ dplyr::filter()                masks stats::filter()
✖ xts::first()                   masks dplyr::first()
✖ zoo::index()                   masks tsibble::index()
✖ tsibble::interval()            masks lubridate::interval()
✖ dplyr::lag()                   masks stats::lag()
✖ xts::last()                    masks dplyr::last()
✖ PerformanceAnalytics::legend() masks graphics::legend()
✖ quantmod::summary()            masks base::summary()
✖ tidyquant::VAR()               masks fable::VAR()
ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors

Attaching package: 'tidyquant'


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

    VAR
df_daily <-
tq_get(x = "MSFT",
       get = "stock.prices",
       from - "1992-01-01")

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

write.csv(x = stock_data_monthly,
          file = "stock_monthly.csv")
train <- stock_data_monthly[1:101, ] # 80%
test <- stock_data_monthly[102:127, ]  # 20%
?fabletools
starting httpd help server ... done
?NAIVE

models_stock <- model(.data = train, 
                      naive = NAIVE(value),
                      snaive = SNAIVE(value),
                      drift = RW(value ~ drift())
                    
                      )

h <- nrow(test)

forecast_stock <- forecast(models_stock, h = 26, level = 95)

autoplot(forecast_stock)