最近在做时间序列有关的论文,学习了DCC-GARCH模型。
发现R里面可以实现基于T分布建模
需要用到rugarch rmgarch包
代码:
library(ggplot2)
#画出时序图
ggplot(data = df)+
geom_line(aes(date, variable1),size=0.3) +
theme_classic()+
labs(title = "Insurance", # 定义主标题
x = "Date", # 定义x轴文本
y = "Return") + # 定义y轴文本
theme(plot.title = element_text(hjust = 0.5))
ggsave(filename = "rins.png",
width = 14, # 宽
height = 7, # 高
units = "in", # 单位
dpi = 300 ) # 分辨率DPI
#描述性统计
library(pastecs)
summ <- stat.desc(df,basic=TRUE,desc=TRUE,norm=TRUE,p=0.95)
write.table(summ,"summary.csv",sep=",")
#ACF单位根检验
library(tseries)
Dickey_Fuller = 0 #(保存Dickey_Fuller的向量)
ADF_p = 0 #(保存p值的向量)
for( i in 1:5){
adf = adf.test(return[,i])
Dickey_Fuller[i] = adf$statistic[1] #(提取Dickey_Fuller)
ADF_p[i] = adf$p.value[1] #(提取p值)
}
name <- c("variable1","variable2","variable3","variable4","variable5")
adf_result = cbind(name,Dickey_Fuller,ADF_p)
write.csv(adf_result,"adf.csv") # 结果储存
# LM检验
library(FinTS)
Lmtest = function(series,nm,max_lag){
chi = 0
lm_p = 0
chi[1] = nm
lm_p[1] = nm
chi[2] = "chi"
lm_p[2] = "p"
for( lags in 1:max_lag){
lm = ArchTest(x=series,lag=lags)
chi[lags+2] = lm$statistic[1]
lm_p[lags+2] = lm$p.value[1]
}
once_mat = rbind(chi,lm_p)
}
max_lag = 5
lm_mat = matrix(nrow=(2*length(x)),ncol=(max_lag+2))
for (j in 1:length(x)){
start = 1+2*(j-1)
end = 2*j
lm_mat[start:end,] = Lmtest(x[,j],name[j],max_lag)
}
colnames(lm_mat) = append(c("变量","参数"),seq(from = 1, to = max_lag, by = 1))
write.csv(lm_mat,"lm_mat.csv")
library(rugarch)
library(rmgarch)
#dcc 模型
#设置基于T分布的模型,distribution是调整分布的参数,如果是正太分布写为"norm"
spec1 = ugarchspec(variance.model = list(model="sGARCH",garchOrder=c(1,1)),
mean.model = list(armaOrder=c(0,0)),distribution.model = "std")
spec2 = ugarchspec(variance.model = list(model="sGARCH",garchOrder=c(1,1)),
mean.model = list(armaOrder=c(0,0)),distribution.model = "std")
mspec = multispec( c( spec1, spec2 ) )
spec = dccspec(mspec, VAR = FALSE, robust = FALSE,external.regressors = NULL,
dccOrder = c(1,1), model = "DCC", distribution = "mvt")
#建立模型带入数据
xt<-ts(data,start=1) #设置简单的时间序列
#ts是一个函数,将数据变为时间序列数据,但是我的数据不连续,所以按照简单的从1开始,如果数据是连续的,可以调整参数
#也可以不转化成时间序列数据,但之后plot时横坐标会不符合数据是从1960开始的
m1=dccfit(spec,xt[,1:2], out.sample = 0, solver = "solnp", solver.control = list(),
fit.control = list(eval.se = TRUE, stationarity = TRUE, scale = FALSE),
cluster = NULL, fit = NULL, VAR.fit = NULL, realizedVol = NULL)
show(m1)
plot(m1)