Time series analysis is a way to analyze a sequence of data that has been collected over a period of time. The data points are registered at consistent intervals to examine the change in variables over time. Any metric that measures at regular time intervals can make a time series. Some example of include: stock data, weather data, census data, etc.
For this time series analysis we will be creating dummy data.
# Create 48 monthly observations form Jan 2020 to december 2022 and create a time series object.
data <- sample(x = 50:100, size = 48)
ts <- ts(data, start=c(2020, 1), end=c(2022, 12), frequency=12)
Create a subset of the time series using the ‘window’ function.
# Create a subset of the time series using the 'window' function (May 2020 to January 2021)
ts_sub <- window(ts, start=c(2020, 5), end=c(2021, 1))
Plot the time series
# plot the time series
plot(ts)
# Seasonal Decomposition
A time series with additive trend, seasonal, and irregular components can be decomposed using the stl() function.
decomp <- stl(ts, s.window = 'period')
plot(decomp)
# Forecast
The ‘forcast’ package in R provides function for automatic selection of exponential and ARIMA models.
library(forecast)
## Warning: package 'forecast' was built under R version 4.1.3
## Registered S3 method overwritten by 'quantmod':
## method from
## as.zoo.data.frame zoo
# Automated forecasting using exponential models
exp <- ets(ts)
exp
## ETS(M,N,N)
##
## Call:
## ets(y = ts)
##
## Smoothing parameters:
## alpha = 1e-04
##
## Initial states:
## l = 76.2754
##
## sigma: 0.2021
##
## AIC AICc BIC
## 329.8970 330.6470 334.6476
plot(exp)
# Automated forecasting using ARIMA models
arima <- auto.arima(ts)
arima
## Series: ts
## ARIMA(0,0,1) with non-zero mean
##
## Coefficients:
## ma1 mean
## -0.3534 76.5093
## s.e. 0.1649 1.5480
##
## sigma^2 = 211.6: log likelihood = -146.5
## AIC=299.01 AICc=299.76 BIC=303.76
plot(arima)