---
title: "ARIMA Models"
subtitle: "Lecture 09"
author: "Dr. Colin Rundel"
footer: "Sta 344 - Fall 2022"
format:
  revealjs:
    theme: slides.scss
    transition: fade
    slide-number: true
execute:
  echo: true
  warning: false
  collapse: true
---

```{r setup, include=FALSE}
library(tidyverse)
library(forecast)

knitr::opts_chunk$set(
  fig.align = "center"
)

ggplot2::theme_set(ggplot2::theme_bw())
```

# $MA(\infty)$

## $MA(q)$

From last time - a $MA(q)$ process with $\w_t \overset{iid}{\sim} N(0,\sigma^2_w)$,
$$y_t = \delta + w_t + \theta_1 \, w_{t-1} + \theta_2 \, w_{t-2} + \cdots + \theta_q \, w_{t-q} $$

has the following properties,
$$E(y_t) = \delta$$

$$
Var(y_t) = \gamma(0) = (1 + \theta_1^2 + \theta_2 + \cdots + \theta_q^2) \, \sigma_w^2
$$

$$
Cov(y_t, y_{t+h}) = \gamma(h) = \begin{cases}
\sigma^2_w \sum_{j=0}^{q-|h|} \theta_j \theta_{j+|h|} & \text{if $|h| \leq q$} \\
0 & \text{if $|h| > q$}
\end{cases}
$$

and is stationary for any values of $(\theta_1, \ldots,\theta_q)$


## $MA(\infty)$

If we let $q \to \infty$ then process will be stationary if and only if the moving average coefficients ($\theta$
's) are square summable, i.e.

$$ \sum_{i=1}^\infty \theta_i^2 < \infty$$

which is necessary so that the $Var(y_t) < \infty$ condition is met for weak stationarity.

Sometimes, a slightly stronger condition known as absolute summability, 
$\sum_{i=1}^\infty |\theta_i| < \infty$ 
is  necessary (e.g. for some CLT related asymptotic results). 


## Invertibility

If an $MA(q)$ process, $y_t = \delta + \theta_q(L) w_t$, can be rewritten as a stationary $AR$ process then the process is said to be invertible.

. . .

<br/>

$MA(1)$ w/ $\delta=0$ example:

<!--
$$
\begin{aligned}
y_t &= w_t + \theta \, w_{t-1} \\
w_t &= y_t - \theta \, w_{t-1} \\
\\
w_t &= y_t - \theta \, w_{t-1} \\
    &= y_t - \theta \, (y_{t-1} - \theta \, w_{t-2}) = y_t - \theta \, y_{t-1} + \theta^2 w_{t-2} \\
    &= y_t - \theta \, y_{t-1} + \theta^2 (y_{t-2} - \theta w_{t-3}) = y_t - \theta \, y_{t-1} + \theta^2 y_{t-2} - \theta^3 w_{t-3} \\
    &~~\vdots \\
    &= y_t + \sum_{i=1}^p(-\theta)^i \, y_{t-i} + (-\theta)^{p+1} w_{t-p+1} \\
\text{Therefore invertible if $|\theta| < 1$}
\end{aligned}
$$
-->

## Invertibility vs Stationarity

A $MA(q)$ process is *invertible* if $y_t = \delta + \theta_q(L) \, w_t$ can be rewritten as an exclusively $AR$ process (of possibly infinite order), i.e. $\phi(L) \, y_t = \alpha + w_t$.  

$~$  

. . . 
 
Conversely, an $AR(p)$ process is *stationary* if $\phi_p(L) \, y_t = \delta + w_t$ can be rewritten as an exclusively $MA$ process (of possibly infinite order), i.e. $y_t = \delta + \theta(L) \, w_t$.

$~$

. . . 

So using our results w.r.t. $\phi(L)$ it follows that if all of the roots of $\theta_q(L)$ are outside the complex unit circle then the moving average process is invertible.


# Differencing

## Difference operator

We will need to define one more notational tool for indicating differencing
$$ \Delta y_t = y_t - y_{t-1} $$

. . .

Just like the lag operator we will indicate repeated applications of this operator using exponents
$$ 
\begin{aligned}
\Delta^2 y_t 
  &= \Delta (\Delta y_t) \\
  &= (\Delta y_t) - (\Delta y_{t-1}) \\
  &= (y_t - y_{t-1}) - (y_{t-1} - y_{t-2}) \\
  &= y_t - 2y_{t-1}+y_{t-2}
\end{aligned}
$$

. . .

Note that $\Delta$ can even be expressed in terms of the lag operator $L$,
$$ \Delta^d = (1-L)^d $$


## Differencing and Stocastic Trend

Using the two component time series model
$$ y_t = \mu_t + x_t $$
where $\mu_t$ is a non-stationary trend component and $x_t$ is a mean zero stationary component. 

$~$

We have already shown that differencing can address deterministic trend (e.g. $\mu_t = \beta_0+\beta_1 \, t$). In fact, if $\mu_t$ is any $k$-th order polynomial of $t$ then $\Delta^k y_t$ is stationary.

$~$

Differencing can also address stochastic trend such as in the case where $\mu_t$ follows a random walk.


## Stochastic trend - Example 1

Let $y_t = \mu_t + w_t$ where $w_t$ is white noise and $\mu_t = \mu_{t-1} + v_t$ with $v_t$ being a stationary process with mean 0. 

```{r echo=FALSE}
d = tibble(
  w=rnorm(300,0,1),
  v=rnorm(300,0,1),
  mu = 0,
  y = 0
)

for(t in 2:300) {
  d$mu[t] = d$mu[t-1] + d$v[t]
  d$y[t] = d$mu[t] + d$w[t]
}

forecast::ggtsdisplay(d$y)
```

## Differenced stochastic trend

```{r}
forecast::ggtsdisplay(diff(d$y))
```

## Stationary?

Is $y_t$ stationary?

## Difference Stationary?

Is $\Delta y_t$ stationary?

<!--
$$
\begin{aligned}
\Delta y_t 
  &= (\mu_t + w_t) - (\mu_{t-1} + w_{t-1}) \\
  &= \mu_{t-1} + v_t - \mu_{t-1} + w_{t} + w_{t-1} \\
  &= v_t + \Delta w_{t}
\end{aligned}
$$
-->


## Stochastic trend - Example 2

Let $y_t = \mu_t + w_t$ where $w_t$ is white noise and $\mu_t = \mu_{t-1} + v_t$ but now $v_t = v_{t-1} + e_t$ with $e_t$ being stationary. 

```{r echo=FALSE}
d = tibble(
  w=rnorm(300,0,1),
  e=rnorm(300,0,1),
  v=0,
  mu = 0,
  y = 0
)

for(t in 2:300) {
  d$v[t] = d$v[t-1] + d$e[t]
  d$mu[t] = d$mu[t-1] + d$v[t]
  d$y[t] = d$mu[t] + d$w[t]
}

forecast::ggtsdisplay(d$y)
```

## Differenced stochastic trend

```{r}
forecast::ggtsdisplay(diff(d$y))
```

## Twice differenced stochastic trend

```{r}
forecast::ggtsdisplay(diff(d$y,differences = 2))
```

## Difference stationary?

Is $\Delta y_t$ stationary? 

<!--
$$
\begin{aligned}
\Delta y_t 
  &= (\mu_t + w_t) - (\mu_{t-1} + w_{t-1}) \\
  &= \mu_{t-1} + v_t - \mu_{t-1} + w_{t} + w_{t-1} \\
  &= v_t + \Delta w_{t} \\
\end{aligned}
$$
-->

## 2nd order difference stationary?

What about $\Delta^2 y_t$, is it stationary?

<!--
$$
\begin{aligned}
\Delta^2 y_t 
  &= (v_t + \Delta w_{t}) - (v_{t-1} + \Delta w_{t-1}) \\
  &= v_{t-1} + e_t + \Delta w_{t} - v_{t-1} - \Delta w_{t-1} \\
  &= e_t + \Delta^2 w_t
\end{aligned}
$$
-->

# $ARIMA$

## $ARIMA$ Models

Autoregressive integrated moving average are just an extension of an $ARMA$ model to include differencing of degree $d$ to $y_t$ before including the autoregressive and moving average components.

$$
\begin{aligned}
ARIMA(p,d,q): \qquad \phi_p(L) \; \Delta^d \, y_t &= \delta + \theta_q(L) w_t  
\end{aligned}
$$

. . .

$~$

Box-Jenkins approach:

1. Transform data if necessary to stabilize variance

2. Choose order ($p$, $d$, $q$) of ARIMA model

3. Estimate model parameters ($\delta$, $\phi$s, and $\theta$s)

4. Diagnostics


## Using `forecast` - random walk with drift

Some of R's base timeseries handling is a bit wonky, the `forecast` package offers some useful alternatives and additional functionality.

```{r}
rwd = arima.sim(n=500, model=list(order=c(0,1,0)), mean=0.1) 

forecast::Arima(rwd, order = c(0,1,0), include.constant = TRUE)
```

## EDA

```{r}
forecast::ggtsdisplay(rwd)
```

## Differencing - Order 1

```{r}
forecast::ggtsdisplay(diff(rwd))
```

## Differencing - Order 2

```{r}
forecast::ggtsdisplay(diff(rwd, 2))
```

## Differencing - Order 3

```{r}
forecast::ggtsdisplay(diff(rwd, 3))
```

## AR or MA?

<br/>

```{r echo=FALSE, fig.height=4}
ts1 = arima.sim(n=250, model=list(order=c(0,1,2), ma=c(0.4,0.5))) 
ts2 = arima.sim(n=250, model=list(order=c(2,1,0), ar=c(0.4,0.5))) 


par(mfrow=c(1,2), mar=c(2,4,2,2))
plot(ts1, main="ts1")
plot(ts2, main="ts2")
```

## EDA

```{r echo=FALSE, fig.height=4}
par(mfrow=c(2,3), mar=c(2,4,2,2))
plot(ts1)
forecast::Acf(ts1,main="")
forecast::Pacf(ts1,main="")

plot(ts2)
forecast::Acf(ts2,main="")
forecast::Pacf(ts2,main="")
```

## `ts1` - Finding $d$

```{r echo=FALSE, fig.height=5}
par(mfrow=c(3,3), mar=c(2,4,2,2))

plot(diff(ts1), main="d=1")
plot(diff(ts1,2), main="d=2")
plot(diff(ts1,3), main="d=3")
forecast::Acf(diff(ts1), main="")
forecast::Acf(diff(ts1,2), main="")
forecast::Acf(diff(ts1,3), main="")
forecast::Pacf(diff(ts1), main="")
forecast::Pacf(diff(ts1,2), main="")
forecast::Pacf(diff(ts1,3), main="")
```

## `ts2` - Finding $d$

```{r echo=FALSE, fig.height=5}
par(mfrow=c(3,3), mar=c(2,4,2,2))
plot(diff(ts2), main="d=1")
plot(diff(ts2,2), main="d=2")
plot(diff(ts2,3), main="d=3")
forecast::Acf(diff(ts2), main="")
forecast::Acf(diff(ts2,2), main="")
forecast::Acf(diff(ts2,3), main="")
forecast::Pacf(diff(ts2), main="")
forecast::Pacf(diff(ts2,2), main="")
forecast::Pacf(diff(ts2,3), main="")
```

## `ts1` - Models

```{r echo=FALSE}
expand.grid(p=0:2, d=1, q=0:2) %>%
  mutate(
    model = purrr::pmap(.,~ forecast::Arima(ts1, order = c(..1,..2,..3))[c("aic","aicc","bic")]),
    aic  = purrr::map_dbl(model, "aic"),
    aicc = purrr::map_dbl(model, "aicc"),
    bic  = purrr::map_dbl(model, "bic")
  ) %>%
  select(-model) %>%
  knitr::kable(digits = 2)
```

## `ts2` - Models

```{r echo=FALSE}
expand.grid(p=0:2, d=1, q=0:2) %>%
  mutate(
    model = purrr::pmap(.,~ forecast::Arima(ts2, order = c(..1,..2,..3))[c("aic","aicc","bic")]),
    aic  = purrr::map_dbl(model, "aic"),
    aicc = purrr::map_dbl(model, "aicc"),
    bic  = purrr::map_dbl(model, "bic")
  ) %>%
  select(-model) %>%
  knitr::kable(digits = 2)
```

## `ts1` - final model

Fitted:
```{r}
forecast::Arima(ts1, order = c(0,1,2))
```

Truth:
```{r eval=FALSE}
ts1 = arima.sim(n=250, model=list(order=c(0,1,2), ma=c(0.4,0.5))) 
```

## `ts2` - final model

Fitted:
```{r}
forecast::Arima(ts2, order = c(2,1,0))
```

Truth:
```{r eval=FALSE}
ts2 = arima.sim(n=250, model=list(order=c(2,1,0), ar=c(0.4,0.5))) 
```


##  Residuals

```{r echo=FALSE, fig.height=4}
ts1_resid = forecast::Arima(ts1, order = c(0,1,2))$residuals
ts2_resid = forecast::Arima(ts2, order = c(2,1,0))$residuals

par(mfrow=c(2,3), mar=c(2,4,6,2))
plot(ts1_resid, main="ts1 Residuals")
forecast::Acf(ts1_resid, main="")
forecast::Pacf(ts1_resid, main="")

plot(ts2_resid, main="ts2 Residuals")
forecast::Acf(ts2_resid, main="")
forecast::Pacf(ts2_resid, main="")
```

## Automatic model selection

:::: {.columns .small}
::: {.column width='50%'}
`ts1`:
```{r}
forecast::auto.arima(ts1)
```
:::
::: {.column width='50%'}
`ts2`:
```{r}
forecast::auto.arima(ts2)
```
:::
::::


## General Guidance

::: {.medium}
1. Positive autocorrelations out to a large number of lags usually indicates a need for differencing

2. Slightly too much or slightly too little differencing can be corrected by adding AR or MA terms respectively.

3. A model with no differencing usually includes a constant term, a model with two or more orders (rare) differencing usually does not include a constant term. 

4. After differencing, if the PACF has a sharp cutoff then consider adding AR terms to the model.

5. After differencing, if the ACF has a sharp cutoff then consider adding an MA term to the model.

6. It is possible for an AR term and an MA term to cancel each other's effects, so try models with fewer AR terms and fewer MA terms.
:::

::: {.aside}
Based on guidance in Robert Nau's notes on [regression and time series analysis](https://people.duke.edu/~rnau/411home.htm) - Chapter 5
:::
