---
title: The Copula GARCH Model
author: Marius Hofert
date: '`r Sys.Date()`'
vignette: >
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteIndexEntry{The Copula GARCH Model}
---
```{r, message=FALSE}
require(copula)
require(rugarch)
set.seed(271)
```

## 1) Simulate data

First, we simulate the innovation distribution.
```{r}
n <- 200 # sample size
d <- 2 # dimension
nu <- 3 # degrees of freedom for t
tau <- 0.5 # Kendall's tau
th <- iTau(ellipCopula("t", df=nu), tau) # corresponding parameter
cop <- ellipCopula("t", param=th, dim=d, df=nu) # define copula object
U <- rCopula(n, cop) # sample the copula
Z <- qnorm(U) # adjust margins
```

Now we simulate two ARMA(1,1)-GARCH(1,1) processes with these copula-dependent
innovations. To this end, recall that an ARMA($p_1$,$q_1$)-GARCH($p_2$,$q_2$) model is given by
\begin{align}
	X_t &= \mu_t + \sigma_t Z_t\\
  \mu_t &= \mu + \sum_{k=1}^{p_1} \phi_k  (X_{t-k}-\mu) +
            \sum_{k=1}^{q_1} \theta_k (X_{t-k}-\mu_{t-k})\sigma_t^2\\
		&= \alpha_0 + \sum_{k=1}^{p_2} \alpha_k (X_{t-k}-\mu_{t-k})^2 +
            \sum_{k=1}^{q_2} \beta_k \sigma_{t-k}^2.
\end{align}

```{r}
## Set parameters
fixed.p <- list(mu  = 1,
                ar1 = 0.5,
                ma1 = 0.3,
                omega = 2, # alpha_0 (conditional variance intercept)
                alpha1= 0.4,
                beta1 = 0.2)
varModel <- list(model = "sGARCH", garchOrder=c(1,1)) # standard GARCH
uspec <- ugarchspec(varModel, mean.model = list(armaOrder=c(1,1)),
                    fixed.pars = fixed.p,
                    distribution.model = "norm") # conditional innovation density
## Note: ugarchpath(): simulate from a spec; ugarchsim(): simulate from a fitted object
X <- ugarchpath(uspec,
                n.sim= n, # simulated path length
                m.sim= d, # number of paths to simulate
                custom.dist=list(name="sample", distfit=Z)) # passing sample (n x d)-matrix
str(X, max.level=2) # => @path$sigmaSim, $seriesSim, $residSim
matplot(X@path$sigmaSim,  type="l") # plot of sigma's (conditional standard deviations)
matplot(X@path$seriesSim, type="l") # plot of X's
matplot(X@path$residSim,  type="l") # plot of Z's
par(pty="s")
plot(pobs(X@path$residSim)) # plot of Z's pseudo-observations => seem fine
```

## 2) Fitting procedure based on the simulated data

We now show how to fit an ARMA(1,1)-GARCH(1,1) process to `X`
(remove 'fixed.pars' from specification to be able to fit).
```{r}
uspec <- ugarchspec(varModel, mean.model = list(armaOrder=c(1,1)),
                    distribution.model = "norm")
fit <- apply(X@path$seriesSim, 2, function(x) ugarchfit(uspec, x))
str(fit, max.level=3)
str(fit[[1]], max.level=2) # for first time series
stopifnot(identical(fit[[1]]@fit$residuals, residuals(fit[[1]]@fit))) # => the same
```

Check the residuals.
```{r}
Z. <- sapply(fit, function(fit.) residuals(fit.@fit))
U. <- pobs(Z.)
par(pty="s")
plot(U., # plot of Z's pseudo-observations => seem fine
     xlab=expression(italic(hat(U)[1])),
     ylab=expression(italic(hat(U)[2])))
```

Fit a t copula to the residuals Z.
```{r}
fitcop <- fitCopula(ellipCopula("t", dim=2), data=U., method="mpl")
rbind(est = fitcop@estimate, true = c(th, nu)) # hat{rho}, hat{nu}; close to th, nu
```

## 3) Simulate from the fitted time series model

Simulate from the fitted copula model.
```{r}
U.. <- rCopula(n, fitcop@copula)
Z.. <- qnorm(U..)
X..sim <- lapply(1:d, function(j)
                 ugarchsim(fit[[j]], n.sim=n, m.sim=1,
                           custom.dist=list(name="sample",
                           distfit=Z..[,j, drop=FALSE]))@simulation)
str(X..sim, max.level=3)
X..Z <- sapply(X..sim, `[[`, "residSim")
X.. <- sapply(X..sim, `[[`, "seriesSim")
plot(X..Z, main="residSim"); abline(h=0,v=0, lty=2, col=adjustcolor(1, .5))
plot(X.., main="seriesSim"); abline(h=0,v=0, lty=2, col=adjustcolor(1, .5))
matplot(pobs(X..), type="l")
par(pty="s")
plot(pobs(X..), main="pobs(series..)"); rect(0,0,1,1, border=adjustcolor(1, 1/2))
```
