我正在尝试在财务数据上使用arima模型,但我收到错误:
arima中的错误(spReturnsOffset,order = c(p,d,q)):非静止 来自CSS的AR部分
代码如下:
library(quantmod)
getSymbols("^GSPC", from="1950-01-01")
spReturns = diff(log(Cl(GSPC)))
#differenced logarithmic returns of the "Closing Price" of the S&P500 and strip out the initial NA value:
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="character", length=foreLength)
for (f in 0:foreLength) {
# Obtain the S&P500 rolling window for this day
spReturnsOffset<- spReturns[(1+f):(windowLength+f)]
order.matrix <- matrix(0, nrow = 3, ncol = 4 * 4)
aic.vec <- numeric(4 * 4)
k <- 1
for (p in 1:4) for (q in 1:4) {
order.matrix[, k] <- c(p,0,q)
aic.vec[k] <- AIC(arima(spReturnsOffset, order=c(p, 0, q)))
k <- k+1
}
ind <- order(aic.vec, decreasing = FALSE)
aic.vec <- aic.vec[ind]
order.matrix <- order.matrix[, ind]
rownames(order.matrix) <- c("p", "d", "q")
order.matrix <- t(order.matrix)
result <- cbind(order.matrix, aic.vec)
colnames(result) <- c("p", "d", "q", "AIC")
}
我在arima函数中也尝试过MLE方法,但我收到错误消息:
solve.default中的错误(res $ hessian * n.used,A):Lapack例程 dgesv:系统完全是单数:U [1,1] = 0
我也尝试过使用trycatch!代码一直在运行!
我该如何解决这个问题?
回应Hack-R的评论
以下代码可行:
# Obtain the S&P500 returns and truncate the NA value
getSymbols("^GSPC", from="1950-01-01")
spReturns = diff(log(Cl(GSPC)))
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="character", length=foreLength)
for (d in 0:foreLength) {
# Obtain the S&P500 rolling window for this day
spReturnsOffset = spReturns[(1+d):(windowLength+d)]
# Fit the ARIMA model
final.aic <- Inf
final.order <- c(0,0,0)
for (p in 0:5) for (q in 0:5) {
if ( p == 0 && q == 0) {
next
}
arimaFit = tryCatch( arima(spReturnsOffset, order=c(p, 0, q)),
error=function( err ) FALSE,
warning=function( err ) FALSE )
if( !is.logical( arimaFit ) ) {
current.aic <- AIC(arimaFit)
if (current.aic < final.aic) {
final.aic <- current.aic
final.order <- c(p, 0, q)
final.arima <- arima(spReturnsOffset, order=final.order)
}
} else {
next
}
}
答案 0 :(得分:0)
以下代码完成了我的要求,感谢您阅读和建议。
#Get S&P 500
getSymbols("^GSPC", from = "2000-01-01")
#Compute the daily returns
gspcRet<-diff(log(Cl(GSPC)))
#Use only the last two years of returns
gspcTail<-as.ts(tail(gspcRet,500))
#Searching for the best models
order.matrix<-matrix(0,nrow = 3, ncol = 6 * 6)
aic.vec<- numeric(6 * 6)
k<-1
for(p in 0:5) for(q in 0:5){
order.matrix[,k]<-c(p,0,q)
aic.vec[k]<- AIC(arima(gspcTail, order=c(p,0,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")