This function takes a while to run. So, I would like to know how to improve its performance.
The purpose of this function is to compute several gjr garch dcc regressions and then store the standard deviations and the correlations in a list.
sigma_function<-function(index_ret, ret){
sigma<-data.frame(Date=index_ret[,1])
rho<-data.frame(Date=index_ret[,1])
for (i in c(2:ncol(ret))){
x<-data.frame(index_ret, ret[,i])
gjrgarch.spec <- ugarchspec(variance.model = list(model = "gjrGARCH", garchOrder = c(1, 1)), mean.model = list(armaOrder = c(0,0), include.mean = TRUE), distribution.model = "norm")
dcc.gjrgarch.spec = dccspec(uspec = multispec(replicate(2,gjrgarch.spec)), dccOrder = c(1, 1), distribution = "mvnorm")
dcc.fit <- dccfit(dcc.gjrgarch.spec, data = na.omit(x[,-1]))
h<-dcc.fit@model[["sigma"]] #this are the conditional standard deviations
h_1<-data.frame(na.omit(x),h)
names(h_1)[c(4,5)]<-c(paste("sigma_rm",i), paste("sigma",names(ret)[i]))
sigma<-merge(sigma,h_1[,c(1,4,5)], all = TRUE, by="Date")
p<-dcc.fit@mfit$R #this is the conditional correlation matrices (3D matrices)
#each matrix corresponds to one date
rho_1<-c()
for (j in c(1:nrow(na.omit(x)))){
rho_1[j]<-p[[j]][1,2] #extract the correlation between the index and the stock for each date
}
p_1<-data.frame(na.omit(x),rho_1)
names(p_1)[4]<-paste("rho",i)
rho<-merge(rho,p_1[,c(1,4)], all = TRUE, by="Date")
}
return(list(sigma, rho))
}