library(forecast)
## Registered S3 method overwritten by 'quantmod':
##   method            from
##   as.zoo.data.frame zoo
library(tseries)
library(ggplot2)
library(gridExtra)

# Load the dataset
data("AirPassengers")
# Convert the dataset to a time series object
ts_data <- ts(AirPassengers, start = c(1949, 1), frequency = 12)
# Plot the time series
plot(ts_data, main = "AirPassengers Time Series", ylab = "Passengers", xlab = "Time")

## Time series Decomposition Decomposing a time series involves breaking it down into its fundamental components: trend, seasonality, and residuals.

# Decompose the time series
decomposed <- decompose(ts_data)
# Plot the decomposed components
plot(decomposed)

## Stationarity and Differencing

A stationary time series has constant mean and variance over time

# Perform the Augmented Dickey-Fuller test
adf.test(ts_data)
## Warning in adf.test(ts_data): p-value smaller than printed p-value
## 
##  Augmented Dickey-Fuller Test
## 
## data:  ts_data
## Dickey-Fuller = -7.3186, Lag order = 5, p-value = 0.01
## alternative hypothesis: stationary
diff_ts_data <- diff(ts_data)

plot(diff_ts_data, main="Differenced AirPassengers Time Series", ylab="Differenced Passengers")

Autocorrelation and Partial Autocorrelation

Autocorrelation Function (ACF) and Partial Autocorrelation Function (PACF) are used to identify the order of autoregressive (AR) and moving average (MA) components in an ARIMA model.

# Plot ACF and PACF
acf(ts_data, main = "ACF of AirPassengers")

pacf(ts_data, main = "PACF of AirPassengers")

## Time Series Modeling: ARIMA

library(forecast)
# Fit an ARIMA model
fit <- auto.arima(ts_data)
# Summary of the model
 summary(fit)
## Series: ts_data 
## ARIMA(2,1,1)(0,1,0)[12] 
## 
## Coefficients:
##          ar1     ar2      ma1
##       0.5960  0.2143  -0.9819
## s.e.  0.0888  0.0880   0.0292
## 
## sigma^2 = 132.3:  log likelihood = -504.92
## AIC=1017.85   AICc=1018.17   BIC=1029.35
## 
## Training set error measures:
##                  ME     RMSE     MAE      MPE     MAPE     MASE        ACF1
## Training set 1.3423 10.84619 7.86754 0.420698 2.800458 0.245628 -0.00124847

Forecasting

# Forecast the future values
forecasted <- forecast(fit, h = 24)
# Plot the forecast
plot(forecasted, main = "AirPassengers Forecast")