• このページは公開されるので個人情報などは記載しないこと。
  • 課題が完成したらknitしPublishする。
n <- 24*7*2            # 時間数
t <- 1:n               # 時間
n.tr <- floor(n * 0.8) # 訓練期間数
n.te <- n - n.tr       # テスト期間数
ii.tr <- 1:n.tr        # 訓練期間インデックス
ii.te <- (n.tr+1):n    # テスト期間インデックス

set.seed(5)

y <- 100 + 0.1 * t + 0.02 * t^2 + 100 * sin(2 * pi * t / 24) + rnorm(n, sd = 5)

matplot(y, type = 'o', pch = 1, col = 2)

fq <- 24

d <- 1

dy <- diff(y[ii.tr], diff = d)

matplot(dy, type = 'o', pch = 1, col = 2, ylab = 'y')

library(forecast)
## Warning: パッケージ 'forecast' はバージョン 4.2.3 の R の下で造られました
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo

a <- acf(dy, lag.max = 50) # MA(q)
grid()
abline(v = fq, col = 3, lty = 3)

q <- 2

pa <- pacf(dy, lag.max = 50) # AR(p)【注意】acfと違いグラフが1次ラグから始まる。
grid()
abline(v = fq, col = 3, lty = 3)

p <- 4

fit.arima <- Arima(ts(y[ii.tr], frequency = fq), lambda = 'auto',
                   order    = c(p, d, q),
                   seasonal = c(1, 1, 0)) # SARIMA
## Warning in guerrero(x, lower, upper): Guerrero's method for selecting a Box-Cox
## parameter (lambda) is given for strictly positive data.
fit.arima
## Series: ts(y[ii.tr], frequency = fq) 
## ARIMA(4,1,2)(1,1,0)[24] 
## Box Cox transformation: lambda= 0.9290708 
## 
## Coefficients:
##           ar1     ar2     ar3     ar4      ma1      ma2     sar1
##       -0.2025  0.4510  0.4031  0.3483  -0.4719  -0.5231  -0.5337
## s.e.   0.1817  0.0922  0.0912  0.0685   0.1891   0.1890   0.0593
## 
## sigma^2 = 21.23:  log likelihood = -718.28
## AIC=1452.56   AICc=1453.18   BIC=1480.51
checkresiduals(fit.arima) # 残差分析グラフ

## 
##  Ljung-Box test
## 
## data:  Residuals from ARIMA(4,1,2)(1,1,0)[24]
## Q* = 77.671, df = 41, p-value = 0.0004733
## 
## Model df: 7.   Total lags used: 48
pred <- forecast(fit.arima, h = n.te, level = 95)

matplot(t, y, type = 'o', pch = 16, col = 2, xlim=c(250,350),ylim=c(1500,3000),main = pred$method)
grid()
abline(v = n.tr + 1, lty  = 3, col = 3)
matlines(t[ii.tr], fit.arima$fitted, type = 'o', pch = 16, lty = 2, col = 4)
matlines(t[ii.te], pred$mean,        type = 'o', pch =  1, lty = 2, col = 4)
matlines(t[ii.te], pred$lower, lty = 3, col = 'gray')
matlines(t[ii.te], pred$upper, lty = 3, col = 'gray')
legend('topleft', bg = 'white', lty = c(1, 2, 2, 3),
       col = c(2, 4, 4, 'gray'), pch = c(16, 16, 1, NA),
       legend = c('原系列', '1期先予測値', '予測値', '95%予測区間'))