data(mtcars)
# Bivariate regression
model1 <- lm(mpg ~ wt, data = mtcars)
coef(model1)["wt"] wt
-5.344472
cov(mtcars$wt, mtcars$mpg) / var(mtcars$wt)[1] -5.344472
# Multivariate regression
model2 <- lm(mpg ~ wt + hp, data = mtcars)
coef(model2)["wt"] wt
-3.877831
cov(mtcars$wt, mtcars$mpg) / var(mtcars$wt)[1] -5.344472
# 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.2.1 ✔ tsibble 1.2.0
✔ dplyr 1.1.2 ✔ tsibbledata 0.4.1
✔ tidyr 1.3.0 ✔ ggtime 0.2.0
✔ lubridate 1.9.2 ✔ 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 = "IBM",
get = "stock.prices",
from = "1992-01-01")
# Aggregate to monthly
aapl_data_monthly <- df_daily %>%
mutate(month = yearmonth(date)
) %>%
group_by(month) %>%
summarise(adjusted = mean(adjusted)
) %>%
as_tsibble(index = month)
write.csv(x = aapl_data_monthly,
file = "aapl_monthly_data.csv"
)
train <- aapl_data_monthly[1:323,] # 80% of original data
test <- aapl_data_monthly[324:404,] # 20% of original data
?fabletools::model
?fabletools
# Fit models
models_aapl <- model(
.data = train,
# ETS = ETS(adjusted),
Drift = RW(adjusted ~ drift()),
NAIVE = NAIVE(adjusted),
SNAIVE = SNAIVE(adjusted)
)
# Forecast
h <- nrow(test)
fc_aapl <- forecast(models_aapl, h = h)
autoplot(object = fc_aapl,
data = train) + labs(title = "My Forecasts", xlab = "Time", ylab = "Adjusted Prices")Ignoring unknown labels:
• xlab : "Time"
• ylab : "Adjusted Prices"