Time Series Analysis with R | Towards Data Science

Time Series data is data that is observed at a fixed interval time and it could be measured daily, monthly, annually, etc. Time series has a lot of applications, especially on finance and also weather forecasting. In this article, I will introduce to you how to analyze and also forecast time series data using R. For the data itself, I will give you an example from Bank Indonesia consumer price index (CPI) data from December 2002 until April 2020.
Before we begin the analysis, I will give you what steps that we have to do. The steps are like this,
First, We have to gather and pre-process the data, and also, we should know the domain knowledge of the data that we use,
Then, We analyze the time series, visually and statistically,
Then, We identify the perfect model based on its autocorrelation,
Then, We diagnose the model whether it meets the independence assumption and finally,
We can use the model for doing forecasting
As I said before, we will do time series analysis on Indonesia’s CPI data starts from December 2002 until April 2020. We can get the data from Bank Indonesia. Unfortunately, we have to copy the data first from the website onto the spreadsheet, then make a .csv data from it. The data looks like this after we import it,
library(tidyverse)data <- read.csv("data.csv")colnames(data) <- c("Time", "InflationRate")head(data)
Before we can make an analysis, we have to pre-process it first. Especially on the “InflationRate” column where we have to remove the ‘%’ symbol and convert it to numeric type like this,
# Pre-process the datadata$InflationRate <- gsub(" %$", "", data$InflationRate)data$InflationRate <- as.numeric(data$InflationRate)data <- data[order(nrow(data):1), ]tail(data)
Then, the data that we have will look like this,
With that, we can make a time-series object from the “InflationRate” column using ts function
cpi <- ts(data$InflationRate, frequency = 12, start = c(2002, 12))
With cpi variable, we can conduct the time series analysis.
First, let’s introduce the consumer price index (CPI). CPI is an index that measures the price change of consumer goods at a certain time from its base year. The formula looks like this,
Each CPI values is measured every month. Here is the code and also the plot as the results from this code,
library(ggplot2)# Make the DataFrametidy_data <- data.frame(  date = seq(as.Date("2002-12-01"), as.Date("2020-04-01"), by = "month"),  cpi = cpi)tidy_data# Make the plotp <- ggplot(tidy_data, aes(x=date, y=cpi)) +  geom_line(color="red", size=1.1) +  theme_minimal() +  xlab("") +  ylab("Consumer Price Index") +  ggtitle("Indonesia's Consumer Price Index", subtitle = "From December 2002 Until April 2020")p# Get the statistical summary# Returns data frame and sort based on the CPItidy_data %>%  arrange(desc(cpi))tidy_data %>%  arrange(cpi)
Based on the graph, We cannot see any trend or seasonal pattern. Despite it looks seasonal, the peak of each year is not in the same month, so it’s not seasonal. Then, this graph also don’t have an increasing or decreasing trend on it. Therefore, this graph is stationary because the statistical properties of the data, such as mean and variance, don’t have any effect because of the time.
Beside of the graph, we can measure statistical summary from the data. We can see that the maximum inflation occurs in November 2005 with the rate of CPI is 18.38. Then, the minimum inflation occurs in November 2009 with the rate of CPI is 2.41. With that information, we can conclude that the data doesn’t have a seasonal pattern on it.
After we analyze the data, then we can do modelling based on the data. There are 2 models that we will consider for this case, there are Auto Regression (AR) model and also the Moving Average (MA) model. Before we use the model, we have to identify which model that perfectly fits on the data based on its autocorrelation and which lag suits the model. To identify this, we will make the Auto Correlation Function (ACF) plot and also Partial Auto Correlation Function (PACF) plot like this one below and here is the code,
acf(cpi, plot = T, main = "ACF Plot of CPI", xaxt="n")pacf(cpi, plot = T, main = "ACF Plot of CPI", xaxt="n")
Based on the plot above, how we can choose the perfect model for this data. To choose between AR and MA model, we can see this summary below,
The summary says that AR(p) will fit the model if the ACF plot tails off and PACF plot cuts off to nearly 0 after lag p. Then, the MA(q) model will fit if the ACF plot cuts off to nearly 0 after lag Q and the PACF plot tails off. If both plots are tailing off, then we can use the ARMA(p, q) model to it. For those who still confused about tail off and cut off, tail off means that the value is decreasing gradually and not drop to nearly 0. Then cut off means that the autocorrelation decrease to nearly 0 after the previous lag.
Based on that information, we can see that the ACF plot decreases gradually (tail off) and the PACF plot decreases to nearly 0 after lag-1. Therefore, for this model, we will use the AR(1) model for the next step.
To make sure that the model can be used for forecasting and the other measurement, we have to test the model using Ljung Box Test. Here is the code to do that,
library(FitAR)acf(ar1$residuals)res <- LjungBoxTest(ar1$residuals, k=2, StartLag=1)plot(res[,3],main= "Ljung-Box Q Test", ylab= "P-values", xlab= "Lag")qqnorm(ar1$residuals)qqline(ar1$residuals)
Based on these plots, we can see that the Q-test plot have p-values above 0.05, then the ACF plot shows no significance between another lag, and finally, we can see that the QQ-Plot is almost fit into the line, so we can assume that is already normal. Therefore, we can use the model to do the forecast.
After we make the model and taking the test, now we can do the forecasting by using this code below,
library(forecast)futurVal <- forecast(ar1, h=10, level=c(99.5))plot(futurVal)
And here is the result,
Forecasting is the last work that I can show you. I hope, with this study case on time series analysis, you can make a time series analysis based on your problem. This article is just showing the fundamentals on how to do the analysis and not tackling a problem that is using the ARIMA model and the data that I used still stationary data. I hope that I can share with you talking on how to analyze non-stationary time series data later on.
[1] Chatterjee, S. , Time Series Analysis Using ARIMA Model In R (2018), datascienceplus.com.[2] Hyndman, R.J., & Athanasopoulos, G. (2018) Forecasting: principles and practice, 2nd edition, OTexts.