Time Series Analysis – R Code

This is a simple R code on time series analysis. For a random time series, we plot the data, run an acf and pacf analysis (autocorrelation and partial autocorrelation functions), fit an ARIMA model, test the residuals, and finally create a forecast. By using the auto.arima function we select the optimal ARIMA model based on the corresponding information criteria.

## Time Series Analysis

# clear environment and console
rm(list = ls())

# install required packages

# load required packages

# create a random time series
t_series = matrix(runif(100, 20, 120), nrow = 100, ncol = 1)

# plot time series
plot(t_series, type="l",col="blue", xlab="Time", ylab="Values")
title('Values Over Time')

# run acf and pacf

# fit ARIMA model
fit <- auto.arima(t_series, lambda = 0, seasonal = TRUE, stepwise=FALSE, trace =TRUE,
allowdrift = TRUE, approximation=FALSE)

# perform tests on residuals
Box.test(residuals(fit), type = "Ljung-Box") # p-value should be greater than 0.05

# create forecast - 5 periods
plot(forecast(fit, h=5))

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s