用于循环AR模型

时间:2017-10-15 10:17:26

标签: r for-loop forecasting

我希望使用具有不同时间序列的AR(4)模型进行预测。

模型本身:

X(t)-X(t-1)=a(1)(X(t-1)-X(t-2))+...+a(4)(X(t-4)-X(t-5))

=> X(t)=X(t-1)+a(1)(X(t-1)-X(t-2))+...+a(4)(X(t-4)-X(t-5))

首次预测:

X(t+1)-X(t)=a(1)(X(t)-X(t-1))+...+a(4)(X(t-3)-X(t-4))

=> X(t+1)=X(t)+a(1)(X(t)-X(t-1))+...+a(4)(X(t-3)-X(t-4))

第二次预测:

X(t+2)-X(t+1)=a(1)(X(t+1)-X(t))+...+a(4)(X(t-2)-X(t-3))

=> X(t+2)=X(t+1)+a(1)(X(t+1)-X(t))+...+a(4)(X(t-2)-X(t-3))

我已经尝试使用代码

N<-50
arkoef<-0
ar<-0
ARforecast<-numeric(0)
arkoef<-c(closingkursu[2518],closingkursu[2517],closingkursu[2516],closingkursu[2515],closingkursu[2514])
ar<-arkoef
for(i in 1:N){
ARforecast<-c(ARforecast,arkoef[1]+arfit$coef[1]*(arkoef[1]-arkoef[2])+arfit$coef[2]*(arkoef[2]-arkoef[3])+arfit$coef[3]*(arkoef[3]-arkoef[4])+arfit$coef[4]*(arkoef[4]-arkoef[5]))
ar = c(tail(ARforecast, 1), head(ar, -1))}

此代码的输出为:

ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1 
10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 
     ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1 
10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 
     ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1      ar1 
10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 10.19656 

第一个预测似乎是正确的,但循环不起作用。

1 个答案:

答案 0 :(得分:0)

您忘记在循环中递增ARforecast向量的值。

N<-50 ;  arkoef<-0  ;  ar<-0 ;  ARforecast<-numeric(0)
arkoef <- c(closingkursu[2518],closingkursu[2517],closingkursu[2516],closingkursu[2515],closingkursu[2514])
ar <- arkoef

for(i in 1:N){
  ARforecast[i+1] <- c(ARforecast[i], arkoef[i]+arfit$coef[i]*(arkoef[i]-arkoef[i+1])+arfit$coef[i+1]*(arkoef[i+1]-arkoef[i+2])+arfit$coef[i+2]*(arkoef[i+2]-arkoef[i+3])+arfit$coef[i+3]*(arkoef[i+3]-arkoef[i+4]))
  ar = c(tail(ARforecast, 1), head(ar, -1))
}

但我实际上并不了解您代码的某些部分(ar在循环中做了什么?)