├── README.md └── TimeSeriesExample.R /README.md: -------------------------------------------------------------------------------- 1 | # Master -------------------------------------------------------------------------------- /TimeSeriesExample.R: -------------------------------------------------------------------------------- 1 | #Load Libraries 2 | library("fUnitRoots") 3 | library(lmtest) 4 | library("forecast") 5 | library(FitAR) 6 | 7 | #import data 8 | data<-read.csv("data.csv",header=TRUE) 9 | #convert to time series 10 | tsData<- ts(data[2:35,2],start=c(2011,1),frequency=12) 11 | plot(tsData) 12 | #decompose into time series components 13 | timeseriescomponents <- decompose(tsData) 14 | plot(timeseriescomponents) 15 | #detemine stationarity of data 16 | urkpssTest(tsData, type = c("tau"), lags = c("short"),use.lag = NULL, doplot = TRUE) 17 | tsstationary<-diff(tsData, differences=1) 18 | plot(tsstationary) 19 | acf(tsData,lag.max=34) 20 | #remove seasonality 21 | timeseriesseasonallyadjusted <- tsData- timeseriescomponents$seasonal 22 | plot(timeseriesseasonallyadjusted) 23 | tsstationary <- diff(timeseriesseasonallyadjusted, differences=1) 24 | plot(tsstationary) 25 | par(mfrow=c(2,1)) 26 | acf(tsstationary, lag.max=34) 27 | pacf(tsstationary, lag.max=34) 28 | #fit the model 29 | fitARIMA<-arima(tsData, order=c(1,1,1),seasonal = list(order = c(1,0,0), period = 12),method="ML") 30 | fitARIMA 31 | #significance of coefficients 32 | coeftest(fitARIMA) 33 | par(mfrow=c(1,1)) 34 | acf(fitARIMA$residuals) 35 | #residual diagnostics 36 | boxresult<-LjungBoxTest (fitARIMA$residuals,k=2,StartLag=1) # residual?? or the original series? 37 | par(mfrow=c(2,1)) 38 | plot(boxresult[,3],main="Ljung-Box Q Test", ylab="P-values", xlab="Lag") 39 | qqnorm(fitARIMA$residuals) 40 | qqline(fitARIMA$residuals) 41 | 42 | auto.arima(tsData, trace=TRUE) 43 | 44 | #forcast future values 45 | par(mfrow=c(1,1)) 46 | predict(fitARIMA,n.ahead = 5) 47 | futurVal <- forecast.Arima(fitARIMA,h=10, level=c(99.5)) 48 | plot.forecast(futurVal) 49 | 50 | --------------------------------------------------------------------------------