Skip to content

Instantly share code, notes, and snippets.

@chenpanliao
Last active June 23, 2020 14:41
Show Gist options
  • Save chenpanliao/054c100fec5e2ee172ae7c8d313d7d2a to your computer and use it in GitHub Desktop.
Save chenpanliao/054c100fec5e2ee172ae7c8d313d7d2a to your computer and use it in GitHub Desktop.
時間序列 forecast()相關問題
library(tseries)
library(quantmod)
library(forecast)
library(car)
library(haven)
index3 <- getSymbols("^TWII", auto.assign = FALSE)
index.open <- na.omit(data.frame(index3[, 1]))
index.close <- na.omit(data.frame(index3[, 4]))
index.open.test <- data.frame(index.open[1:(nrow(index.open) - 365), ])
index.close.test <- data.frame(index.close[1:(nrow(index.open) - 365), ])
index.open.train <- data.frame(index.open[1:(nrow(index.open)), ])
index.close.train <- data.frame(index.close[1:(nrow(index.open)), ])
index.open.year <- data.frame(tail(index.open, 365))
index.close.year <- data.frame(tail(index.close, 365))
colnames(index.open.year) = "OP.value"
colnames(index.open.train) = "OP.value"
colnames(index.close.year) = "close.value"
colnames(index.close.train) = "close.value"
mod1 <-
auto.arima(
index.open.train,
seasonal = TRUE,
ic = "aic",
test = "adf",
seasonal.test = "seas",
allowdrift = TRUE,
allowmean = TRUE,
stepwise = FALSE,
approximation = FALSE
)
mod2 <-
auto.arima(
index.close.train,
seasonal = TRUE,
ic = "aic",
test = "adf",
seasonal.test = "seas",
allowdrift = TRUE,
allowmean = TRUE,
stepwise = FALSE,
approximation = FALSE
)
predict.open <-
forecast(
index.open.test[[1]],
model = mod1,
h = 365,
include.mean = TRUE
)
predict.close <-
forecast(
index.close.test[[1]],
model = mod2,
h = 365,
include.mean = TRUE
)
index.open.year[[1]]
index.close.year[[1]]
predict.close$mean
predict.open$mean
#上面四個向量都是365長,直接做向量運算即可不必 for loop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment