inst/doc/LFU_Risk_Management_Utilities.R

## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

## ----download, fig.show='hold'------------------------------------------------
library(LFUrmutils)
library(zoo)

data(CRSPday_zoo)
y <- CRSPday_zoo

head(y)
plot(y)
plot(y^2)

## ----ewma, fig.width=7, fig.height=7------------------------------------------
# Compute the EWMA model
EWMA <- MultiEWMA(y, center = TRUE)

# Compare the return series used in EWMA to the original return series
head(EWMA$Returns)
head(y)

# Plot the residuals
plot(EWMA, which = 7)

# Plot the return series with 1.96 * conditional volatility superimposed
plot(EWMA, which = 3)

## ----volacor, fig.width=7, fig.height=7---------------------------------------
EWMAvola <- vola(EWMA)
plot(EWMA, which = 2)
plot(EWMA, which = 13)

## ----rollcor, fig.width=7, fig.height=7---------------------------------------
EWMAccor <- ccor(EWMA, diagonal = FALSE, duplicates = FALSE)
cor_GE_IBM <- rollapplyr(y[, c(1:2)], width = 30, by.column = FALSE, 
                           FUN = function(x) cor(x[, 1], x[, 2]), fill = NA)
cor_GE_IBM <- zoo(cor_GE_IBM, index(y))
plot(EWMAccor[, 1])
lines(cor_GE_IBM, col = "green", lty = 2)

## ----varcov-------------------------------------------------------------------
EWMAvola <- vola(EWMA)
EWMAccor <- ccor(EWMA)

TT <- dim(EWMAccor)[1]
c <- sqrt(dim(EWMAccor)[2])
VarCov <- matrix(NA, dim(EWMAccor)[1], dim(EWMAccor)[2])

for(i in 1:TT){
  VarCov[i, ] <- c(diag(as.numeric(EWMAvola[i, ])) 
                   %*% matrix(as.numeric(EWMAccor[i, ]), c, c,  byrow = TRUE) 
                   %*% diag(as.numeric(EWMAvola[i, ])))
}

VarCov <- zoo(VarCov, order.by = index(EWMAvola))

tail(VarCov[, c(1:4)])
tail(EWMA$Variances[, c(1:4)])

## ----portfoliorisk------------------------------------------------------------
weights <- rep(1/3, times = 3)
varcov <- fitted(EWMA)
TT <- dim(varcov)[1]
Cols <- sqrt(dim(varcov)[2])
portfolio_volatility <- matrix(NA, nrow = TT)

for(i in 1:TT){
  portfolio_volatility[i, ] <- t(weights) %*% matrix(varcov[i ,], nrow = Cols, ncol = Cols, byrow = TRUE) %*% weights
}

portfolio_volatility <- zoo(portfolio_volatility, index(varcov))
plot(portfolio_volatility)

## ----sqrtoftime---------------------------------------------------------------
annualized_volatility <- sqrt(252) * portfolio_volatility
plot(annualized_volatility)

Try the LFUrmutils package in your browser

Any scripts or data that you put into this service are public.

LFUrmutils documentation built on Jan. 3, 2020, 3 a.m.