Leture2-15 code
>setwd("D://R")设置数据读取目录
>library(fBasics)读取fBasics这个package
>da=read.table("dgnp82.dat")读取GNP的数据
>x=da[,1]生成da这一列的数据为一个变量x
>par(mfcol=c(2,2))##put 4 plots on a page四张图画在一页上
###See Figure2 of thelecture note2.
>plot(x,type=’l’)# first plot 序列x的折线图
>plot(x[1:175],x[2:176])# 2nd plot 序列x滞后一期的散点图
>plot(x[1:174],x[3:176])# 3rd plot序列x滞后两期的散点图
>acf(x,lag=12) #4thplot序列x自相关图
>pacf(x,lag.max=12)#ComputePACF(not shown in this handout)
计算偏相关函数,未展示。
>Box.test(x,lag=10,type=’Ljung’)# Compute Q(10)statistics计算参数为10的Box-Ljung test检验结果,R语言直接输出p-value。
该统计量显著表明序列有很强的自相关性,不显著说明序列不存在自相关性。
小于显著性水平就是显著(因为小概率事件在一次事件中发生了,需要拒绝原假设)
大于显著性水平就不显著(因为小概率事件在一次试验中没有发生,正常,不用拒绝原假设)
Box-Ljung test
data:x
X-squared=43.2345,df=10, p-value=4.515e-06
序列有较强的自相关性。
>m1=ar(x,method=’mle’)#Automatic AR fitting using AIC criterion.
拟合AR1模型,使用AIC准则定阶(默认值是AIC=True)。
在ACF/PACF不能确定的情况下,还需要用AIC(Aikaike info Criterion)、BIC(Bayesian information criterion)的信息准则函数来确定阶数。
另外,R语言中ar()函数提供了多种自相关系数的估计(method),包括"yule-walker", "burg", "ols","mle", "yw",默认是用yule-walker方法,常用的方法还有最小二乘法(ols),极大似然法(mle)。
使用最小二乘法时,会出现一个截距项。
>m1
Call:ar(x=x,method="mle")
Coefficients:
1 2 3 % An AR(3) is specified.
0.3480 0.1793 -0.1423
Orderselected3sigma^2estimatedas9.427e-05
>names(m1)
>plot(m1$resid,type=’l’)#Plotresiduals of the fitted model(not shown)
画出残差的折线图
>Box.test(m1$resid,lag=10,type=’Ljung’)#Model checking
对残差序列进行Box-Ljungtest检验,见上文
Box-Ljung test
data:m1$resid
X-squared=7.0808, df=10,p-value=0.7178
>m2=arima(x,order=c(3,0,0))#Another approach with order given.
另一种方法,在给定阶数时的建模方法arima,ma的参数给0。
>m2
Call:
arima(x=x,order=c(3,0,0))
Coefficients:、
ar1 ar2 ar3 intercept # Fitted modelis
0.3480 0.1793 -0.1423 0.0077
#y(t)=0.348y(t-1)+0.179y(t-2)-0.142y(t-3)+a(t),
s.e.0.0745 0.0778 0.0745 0.0012
#where y(t)=x(t)-0.0077
sigma^2estimatedas9.427e-05: loglikelihood=565.84, aic=-1121.68
>Box.test (m2$residuals,lag=10,type=’Ljung’)
Box-Ljung test
data:m2$residuals
X-squared=7.0169, df=10,p-value=0.7239
直接上AR3,再检验残差已经没有相关性了。
>plot(m2$residuals,type=’l’)%Residualplot
> tsdiag(m2)# obtain3 plots of model checking(not shown in handout).
输出三张用于模型检验的图,标准化的残差序列,残差的自相关图(acf 0 阶截尾)Ljung- Box statistic统计量的p值显著不为0,不能拒绝原假设。
>p1=c(1,-m2$coef[1:3])#Further analysis of the fitted model.
>p1
ar1 ar2 ar3
1.0000000 -0.3480209 -0.1793027 0.1422638
>roots=polyroot(p1)
解1-0.3480209x-0.1793027x^2+0.1422638x^3=0
>roots
[1] 1.590253+1.063882i-1.920152+0.000000i 1.590253-1.063882i
解出单位根为上面三个
>Mod(roots)
[1]1.9133081.9201521.913308
>k=2*pi/acos(1.590253/1.913308)
>k
[1]10.65638
这段是计算Stochasticbusiness cycle今天没时间研究了。
>predict(m2,8)