TimeSeries with R 发表于 2018-11-30 | 阅读次数: 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121#一、数据读取ts(data,start,end,frequency)##文件是矩阵时按列读入,可以通过先转置再线性化为向量,代码如下D=read.table('zz.txt')D=t(D)#转置D=as.vector(D)#将矩阵线性化为向量#数据读取结束#二、描述时间序列ts.plot(D)#ts(D);plot(D)#三、自相关和偏相关acf(D,lag,type,plot=True)pacf()#四、平稳性检验#(1)时间序列图检验#(2)自相关图检验#1.确定性时间序列x=seq(0.1,5,0.02)y=0.8*x+2D=jitter(y,amount=0.2)#加入随机扰动D=ts(D)par(mfrow=c(1,3))plot(D)#以上是时间序列图检验,下面进行自相关图检验 acf(D)pacf(D)#2.周期性时间序列x=seq(0.1,15,0.1)y=sin(x)par(mfrow=c(3,1))D=jitter(y,amount=0.2)ts.plot(D)acf(D)pacf(D)#3.伪周期时间序列x=seq(0.1,20,0.1)y=100*sin(x)/xD=jitter(y,amount=3)par(mfrow=c(3,1))plot(D)acf(D)pacf(D)#五、纯随机性检验#H0:是白噪声序列(acf,pacf基本为0)D=rnorm(300,0)D=ts(D)par(mfrow=c(3,1))plot(D)acf(D)pacf(D)#接下来利用Box.test()进行检验#result=0;lag=0;lb=0;p=0;for(i in 1:12){ btest=Box.test(D,type="Ljung-Box",lag=i) lag[i]=i lb[i]=btest$statistic p[i]=btest$p.value result=cbind(lag,lb,p)}print(result)#六、ARMA模型拟合与识别 #arima.sim(model,n),model是模型 ,n是序列的长度 #1.AR(1):X(t)=0.8*X(t-1)+E(t)D=arima.sim(list(order=c(1,0,0),ar=0.8),n=200)#order的三个参数分别对应AR,I,MA的阶数plot(D)par(mfrow=c(1,2))acf(D) pacf(D)#2.AR(2):X(t)=0.8*X(t-1)+0.1X(t-2)+E(t)D=arima.sim(list(order=c(2,0,0),ar=c(0.8,0.1)),n=200)#order的三个参数分别对应AR,I,MA的阶数plot(D)par(mfrow=c(1,2))acf(D) pacf(D)#3.MA(2):x(t)=E(t)-0.7*E(t-1)-0.2*E(t-2)D=arima.sim(list(order=c(0,0,2),ma=c(0.7,0.2)),n=200)plot(D)par(mfrow=c(1,2))acf(D)pacf(D)#ARMA(2,2):X(t)=0.3*X(t-1)+0.4*X(t-2)+E(t)-0.5*E(t-1)-0.4*E(t-2)D=arima.sim(list(order=c(2,0,2),ar=c(0.3,0.4)ma=c(0.5,0.4)),n=200)plot(D)par(mfrow=c(1,2))acf(D)pacf(D)#七、ARMA模型的估计D=arima.sim(list(order=c(2,0,2),ar=c(-0.5,0.4),ma=c(0.5,0.4)),n=1000)ARIMA=arima(D,order=c(2,0,2),method="ML")summary(ARIMA)ARIMA$coef#八、ARMA模型的预测D=arima.sim(list(order=c(2,0,2),ar=c(0.5,-0.2),ma=c(0.5,0.2)),n=100)plot(D)par(mfrow=c(1,2))acf(D)pacf(D)ARIMA=arima(D,order=c(2,0,2),method="ML",include.mean=FALSE)summary(ARIMA)resid=ARIMA$residualBox.test(resid,lag=6)Box.test(resid,lag=12)pre=predict(ARIMA,n.ahead=10)U=pre$pred+1.96*pre$se#置信上限L=pre$pred-1.96*pre$se#置信下限ts.plot(pre$pred,col=1:2)lines(U,col="blue",lty="dashed")lines(L.col="blue",lty="dashed") 喜欢所以热爱,坚持干货分享,欢迎订阅我的微信公众号 呐,请我吃辣条 打赏 微信支付 支付宝