R_timeseries

#timeseries_R

#1.读取数据

births <- scan("http://robjhyndman.com/tsdldata/data/nybirths.dat")
birthstimeseries <- ts(births, frequency=12, start=c(1946,1))
plot.ts(birthstimeseries)


#2.分解时间序列

library("TTR")

#2.1非季节性序列
kingstimeseriesSMA8 <- SMA(kingstimeseries,n=8)
plot.ts(kingstimeseriesSMA8)

#2.2季节性序列
birthstimeseriescomponents <- decompose(birthstimeseries)
plot(birthstimeseriescomponents)


#3.1 Holt-Winters 指数平滑法

#3.1.1 建模
logsouvenirtimeseries <- log(souvenirtimeseries)
souvenirtimeseriesforecasts <- HoltWinters(logsouvenirtimeseries)
plot(souvenirtimeseriesforecasts)

#3.1.2预测
library(forecast)
souvenirtimeseriesforecasts2 <- forecast.HoltWinters(souvenirtimeseriesforecasts, h=48)
plot.forecast(souvenirtimeseriesforecasts2)

#3.1.3检验
acf(souvenirtimeseriesforecasts2$residuals, lag.max=20)
Box.test(souvenirtimeseriesforecasts2$residuals, lag=20, type="Ljung-Box")
plot.ts(souvenirtimeseriesforecasts2$residuals)
plotForecastErrors(souvenirtimeseriesforecasts2$residuals)


#3.2 ARIMA 模型

#3.2.1 参数选择
skirtsseriesdiff1 <- diff(skirtsseries, differences=1)
plot.ts(skirtsseriesdiff1)

acf(kingtimeseriesdiff1, lag.max=20)
pacf(kingtimeseriesdiff1, lag.max=20)

auto.arima(kings)

#3.2.2 建模
kingstimeseriesarima <- arima(kingstimeseries, order=c(0,1,1))

#3.2.3 预测
kingstimeseriesforecasts <- forecast.Arima(kingstimeseriesarima, h=5)
plot.forecast(kingstimeseriesforecasts)

#3.2.4 检验
acf(kingstimeseriesforecasts$residuals, lag.max=20)
Box.test(kingstimeseriesforecasts$residuals, lag=20, type="Ljung-Box")
plot.ts(kingstimeseriesforecasts$residuals)
plotForecastErrors(kingstimeseriesforecasts$residuals)


#读书笔记之R语言时间序列--原文地址:http://doc.datapanda.net/a-Little-Book-of-R-for-Time-Series.pdf

 

posted @ 2015-06-09 20:27  枫叶漂漂  Views(515)  Comments(0)    收藏  举报