假设我有下面的"for“循环。具体地说,我构建的这段代码首先计算所有指定风格的ARCH(1)模型的AIC,然后计算上述风格的GARCH(1,1)模型的AIC。
library(rugarch)
bchain_2012_logreturns=diff(log(prices))
aic_2012=matrix(NA,14,1)
garch_flavor=c("GARCH","AVGARCH","TGARCH","GJRGARCH","NGARCH","NAGARCH","APARCH")
k=1
for (i in 0:1){
for (j in garch_flavor){
model_2012=ugarchspec(variance.model = list(model="fGARCH", submodel = j, garchOrder = c(1, i)),mean.model = list(armaOrder = c(0, 0)))
modelfit_2012=ugarchfit(spec=model_2012, data=bchain_2012_logreturns, solver="hybrid")
aic_2012[k,]=infocriteria(modelfit_2012)[1]
k=k+1
}
}正如R CRAN上的"rugarch“包vignette所述(参见链接:https://cran.r-project.org/web/packages/rugarch/vignette/Introduction_to_the_rugarch_package.pdf),"eGARCH”模型风格不包括在GARCH族(即"fGARCH")子模型中。使用"rugarch“包估计eGARCH模型所需的命令如下:
model_2012=ugarchspec(variance.model = list(model="eGARCH",garchOrder = c(1, 1)),mean.model = list(armaOrder = c(0, 0)))
modelfit_2012=ugarchfit(spec=model_2012, data=bchain_2012_logreturns, solver="hybrid") 我需要同时做的是:
1)将最后一个用于eGARCH估计的命令集成到循环中,以便我只有一个命令来计算所有8种GARCH型模型的AIC。
2)将“统一”循环设置为仅在(1,1)阶的eGARCH上迭代。
我是R编程的新手,这对我来说不是个小问题。
提前谢谢你。
发布于 2017-01-19 01:15:24
使用lapply和条件句你可以这样做:
#Combine all model names into one vector
model_names =c("eGARCH","GARCH","AVGARCH","TGARCH","GJRGARCH","NGARCH","NAGARCH","APARCH")
#If model name equals "eGARCH" use formula1 else formula2, compute for order (1,1) only
#for other models compute for orders (1,0) and (1,1)
#calculate AIC for each model and rbind to form a combined data.frame
AIC_2012 = do.call(rbind,lapply(model_names,function( x ) {
if ( x=="eGARCH" ){
model_2012_0 = ugarchspec(variance.model = list(model= x,garchOrder = c(1, 1)),mean.model = list(armaOrder = c(0, 0)))
modelfit_2012_0 =ugarchfit(spec=model_2012_0 , data=bchain_2012_logreturns, solver="hybrid")
DF = data.frame(model_name = x,order= "1,1" ,AIC = infocriteria(modelfit_2012_0)[1])
}else {
model_2012_0 = ugarchspec(variance.model = list(model="fGARCH", submodel = x, garchOrder = c(1, 0)),mean.model = list(armaOrder = c(0, 0)))
model_2012_1 = ugarchspec(variance.model = list(model="fGARCH", submodel = x, garchOrder = c(1, 1)),mean.model = list(armaOrder = c(0, 0)))
modelfit_2012_0 =ugarchfit(spec=model_2012_0 , data=bchain_2012_logreturns, solver="hybrid")
modelfit_2012_1 =ugarchfit(spec=model_2012_1, data=bchain_2012_logreturns, solver="hybrid")
DF_0 = data.frame(model_name = x, order= "1,0" , AIC = infocriteria(modelfit_2012_0)[1])
DF_1 = data.frame(model_name = x, order= "1,1" , AIC = infocriteria(modelfit_2012_1)[1])
DF = rbind(DF_0,DF_1)
}
return(DF)
}))https://stackoverflow.com/questions/41723575
复制相似问题