# R语言实现：基于GARCH模型的股市危机预警

http://blog.csdn.net/huoz07/artile/details/48176587

1. #包载入
2. library(fGarch)
3. library(rugarch)#garch拟合与预测
4. library(TSA)#BIC准则确定arma阶数 eacf确定garch阶数
5. library(tseries)
6. library(zoo)#转换成时间序列类型
7. library(forecast)#auto.arima() arma阶数确定方法
8. library(psych)#数据描述统计分析
9. library(ggplot2)#绘图
10. library(ccgarch)#JB统计量
11. ###NASDAQ
12. #数据预处理
14. time<-as.Date(StockData\$'time',format="%Y/%m/%d")
15. closeprice<-StockData\$'closeprice'
16. data<-zoo(closeprice,time)
17. #选中局部数据
18. selectdata=window(data, start = as.Date("2005-01-01"), end = as.Date("2015-05-01"))
19. plot(selectdata,xlab="time",ylab="index",main="Shanghai Composite Index")
20. rlog=log(selectdata)
21. rlogdiff=diff(log(selectdata))*100 #数据转换
22. rlogdifftime=index(rlogdiff)
23. rlogdiffdata=coredata(rlogdiff)

（1）正态性检验

1. par(mfrow=c(1,3),oma=c(0.2,0.2,0.2,0.2))
2. hist(rlogdiff,main="Shanghai Composite Index Log Return Distribution",col="yellow",xlab="",ylim=c(0,0.4),probability=T)
3. lines(density(rlogdiff),lwd=1);rug(rlogdiff)#first graph
4. qqnorm(rlogdiff);qqline(rlogdiff)#second graph
5. plot(rlogdiff,ylab="value");abline(h=0,lty=2)#third graph

1. shapiro.test(rlogdiffdata)

#值越大，越表示不是正态，P越小越非正态

1. describe(rlogdiffdata)
2. jb.test(rlogdiffdata)

（2）平稳性检验

p<0.01序列为平稳序列

（3）ARCH 效应检验

1. #得先arima拟合模型，对残差进行LM检验
2. armamodel=auto.arima(rlogdiff) #自动基于AIC最小准则，寻找最佳拟合模型
3. armamodel
4. plot(residuals(armamodel))
5. par(mfrow=c(1,1))
6. lmresult=McLeod.Li.test(y=residuals(armamodel)) #残差arch效应很显著

1. myspec=ugarchspec(
2. variance.model = list(model = "eGARCH", garchOrder = c(1, 1)),
3. mean.model = list(armaOrder = c(0,0), include.mean = TRUE),
4. distribution.model = "std"
5. )
6. myfit=ugarchfit(myspec,data=rlogdiff,solver="gosolnp")
7. myfit

1. #残差正态性检验
2. plot(myfit,which=8)
3. plot(myfit,which=9)
4. shapiro.test(coredata(residuals(myfit))) #值越大，越表示不是正态，P越小越非正态
5. #残差相关性检验
6. acf(coredata(residuals(myfit)))
7. acf(residuals(myfit))
8. plot(myfit,which=10)
9. plot(myfit,which=11)
10. #系数是否显著
11. myfit #看P值是否够小
12. #拟合效果 残差如何
13. plot(myfit,which=3)
14. plot(residuals(myfit)) #看残差

1. plot(myfit,which=12)

1. spec = ugarchspec(variance.model = list(model = "sGARCH"), distribution.model = "std")
2. cl = makePSOCKcluster(10)
3. #滚动预测
4. roll = ugarchroll(spec, rlogdiff, n.start =300,refit.every = 300,
5. refit.window = "moving", solver = "hybrid", calculate.VaR = TRUE,
6. VaR.alpha = c(0.01, 0.025, 0.05), cluster = cl,keep.coef = TRUE)

1. report(roll, type = "fpm")

[plain] view plain copy

1. plot(roll,which=4,VaR.alpha=0.01)

822 篇文章215 人订阅

0 条评论

## 相关文章

1203

2318

2253

1052

942

5115

1923

4085

3846

### 人群运动--Scene-Independent Group Profiling in Crowd

Scene-Independent Group Profiling in Crowd CVPR2014 http://www.ee.cuhk.edu.hk/...

2319