TSLA Time Series Analysis

Author

Dari

# Clear environment
remove(list = ls())

# Load packages
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()
✖ 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
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()
✖ 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
df_daily <-
tq_get(x = "TSLA", 
     get = "stock.prices", 
     from = "2010-06-01")


# Aggregate to monthly
tsla_data_monthly <- df_daily %>%
  mutate(month = yearmonth(date)
         ) %>%
  group_by(month) %>%
  summarise(adjusted = mean(adjusted)
            ) %>%
  as_tsibble(index = month)

write.csv(x = tsla_data_monthly, 
          file = "tsla_monthly_data.csv"
          )
train <- tsla_data_monthly[1:155,]    # 80% of original data
test  <- tsla_data_monthly[155:194,]  # 20% of original data 
?fabletools::model
?fabletools

models_stock <- model(
  .data = train,
#  ETS    = ETS(adjusted),
  Drift  = RW(adjusted ~ drift()),
  NAIVE  = NAIVE(adjusted),
  SNAIVE = SNAIVE(adjusted)
)


h <- nrow(test)
forecast_stock <- forecast(models_stock, h = 24, level = 95)

autoplot(forecast_stock)