在R中拟合和预测Arima模型

时间:2016-06-27 23:48:52

标签: r time-series

该策略是在“滚动”的基础上进行的:

对于每天,n,股票市场指数的差异对数回报的前k天被用作拟合最优ARIMA模型的窗口。

#Install relevant packages  
install.packages("quantmod")
install.packages("forecast")

#Import the necessary libraries
library(quantmod)
library(forecast)

#Get S&P 500
getSymbols("^GSPC", from = "2000-01-01")

#Compute the daily returns 
gspcRet<-(log(Cl(GSPC)))

#Use only the last two years of returns 
gspc500<-tail(gspcRet,500)
spReturns<-diff(gspc500)
spReturns[as.character(head(index(Cl(GSPC)),1))] = 0

# Create the forecasts vector to store the predictions
windowLength<- 500
foreLength<-length(spReturns) - windowLength
forecasts <- vector(mode="list", length=foreLength)
fit1 <- vector(mode="list", length=foreLength)

for (d in 0:foreLength) {
    # Obtain the S&P500 rolling window for this day
    spReturnsOffset<- spReturns[(1+d):(windowLength+d)]

#Searching for the best models
order.matrix<-matrix(0,nrow = 3, ncol = 6 * 2 * 6)
aic.vec<- numeric(6 * 2 * 6)
k<-1
for(p in 0:5) for(d in 0:1) for(q in 0:5){
    order.matrix[,k]<-c(p,d,q)
    aic.vec[k]<- AIC(Arima( spReturnsOffset, order=c(p,d,q)))
    k<-k+1
}
ind<- order(aic.vec,decreasing=F)
aic.vec<- aic.vec[ind]
order.matrix<- order.matrix[,ind]
order.matrix<- t(order.matrix)
result<- cbind(order.matrix,aic.vec)
#colnames(result)<- c("p","d","q","AIC")

p1<- result[1,1]
p2<- result[2,1]
p3<- result[3,1]
p4<- result[4,1]

d1<- result[1,2]
d2<- result[2,2]
d3<- result[3,2]
d4<- result[4,2]

q1<- result[1,3]
q2<- result[2,3]
q3<- result[3,3]
q4<- result[4,3]

#I THINK CODE IS CORRECT TILL HERE PROBLEM IS WITH THE FOLLOWING CODE I GUESS

fit1[d+1]<- Arima(spReturnsOffset, order=c(p1,d1,q1))
forecasts[d+1]<- forecast(fit1,h=1)
#forecasts[d+1]<- unlist(fcast$mean[1])

}

我收到以下错误:

Error in x - fits : non-numeric argument to binary operator
In addition: Warning messages:
1: In fit1[d + 1] <- Arima(spReturnsOffset, order = c(p1, d1, q1)) :
  number of items to replace is not a multiple of replacement length
2: In mean.default(x, na.rm = TRUE) :
  argument is not numeric or logical: returning NA

有人可以建议修复吗?

0 个答案:

没有答案