library(vars) # カナダの予測 data(Canada) Canada # Canadaの1999以降は切って、予測をテストする Canada.1998<-window(Canada,end=c(1998,4)) Canada.1998 Canada plot(Canada) # 次数の決定 VARselect(Canada.1998, lag.max = 5, type="const") # constで定数 VARselect(Canada.1998, lag.max = 5, type="both") # トレンド入り lag1<-VARselect(Canada.1998, lag.max = 5, type="const")$selection[1] var.1<-VAR(Canada.1998,p=lag1,type="const") var.1 yosoku<-predict(var.1, n.ahead = 8, ci = 0.95, dumvar = NULL) yosoku kekka<-ts(yosoku$fcst$e[,1],start=1999,frequency=4) kekka sita<-ts(yosoku$fcst$e[,2],start=1999,frequency=4) ue<-ts(yosoku$fcst$e[,3],start=1999,frequency=4) win.graph() ts.plot(Canada[,1]) lines(kekka,type="l",col=1,lwd=2) lines(ue,type="l",col=2,lwd=2) lines(sita,type="l",col=2,lwd=2) yosoku<-predict(var.1, n.ahead = 100, ci = 0.95, dumvar = NULL) yosoku kekka<-ts(yosoku$fcst$e[,1],start=1999,frequency=4) kekka plot(kekka) # U の結果 yosoku<-predict(var.1, n.ahead = 8, ci = 0.95, dumvar = NULL) yosoku kekka<-ts(yosoku$fcst$U[,1],start=1999,frequency=4) kekka sita<-ts(yosoku$fcst$U[,2],start=1999,frequency=4) ue<-ts(yosoku$fcst$U[,3],start=1999,frequency=4) win.graph() ts.plot(Canada[,4],ylim=c(5,13)) lines(kekka,type="l",col=1,lwd=2) lines(ue,type="l",col=2,lwd=2) lines(sita,type="l",col=2,lwd=2) yosoku<-predict(var.1, n.ahead = 100, ci = 0.95, dumvar = NULL) kekka<-ts(yosoku$fcst$U[,1],start=1999,frequency=4) plot(kekka) # modelをトレンド付にする lag2<-VARselect(Canada.1998, lag.max = 5, type="both")$selection[1] var.2<-VAR(Canada.1998,p=lag2,type="both") var.2 yosoku2<-predict(var.2,n.ahead = 8, ci = 0.95, dumvar = NULL) yosoku2 kekka2<-ts(yosoku2$fcst$e[,1],start=1999,frequency=4) kekka2 sita2<-ts(yosoku2$fcst$e[,2],start=1999,frequency=4) ue2<-ts(yosoku2$fcst$e[,3],start=1999,frequency=4) win.graph() ts.plot(Canada[,1]) lines(kekka2,type="l",col=1,lwd=2) lines(ue2,type="l",col=2,lwd=2) lines(sita2,type="l",col=2,lwd=2) yosoku2<-predict(var.2, n.ahead = 100, ci = 0.95, dumvar = NULL) yosoku2 kekka2<-ts(yosoku2$fcst$e[,1],start=1999,frequency=4) kekka2 plot(kekka2) # U の結果 yosoku2<-predict(var.2, n.ahead = 8, ci = 0.95, dumvar = NULL) yosoku2 kekka2<-ts(yosoku2$fcst$U[,1],start=1999,frequency=4) kekka2 sita2<-ts(yosoku2$fcst$U[,2],start=1999,frequency=4) ue2<-ts(yosoku2$fcst$U[,3],start=1999,frequency=4) win.graph() ts.plot(Canada[,4],ylim=c(5,13)) lines(kekka2,type="l",col=1,lwd=2) lines(ue2,type="l",col=2,lwd=2) lines(sita2,type="l",col=2,lwd=2) yosoku2<-predict(var.2, n.ahead = 100, ci = 0.95, dumvar = NULL) yosoku2 kekka2<-ts(yosoku2$fcst$U[,1],start=1999,frequency=4) kekka2 plot(kekka2)