scripts/empirical_properties.R

library(Data)
library(xts)
library(qrmdata)
library(qrmtools)
library(dplyr)
library(scrAndFun)
library(IPAMomentum)

outputFig <- c("C:/Users/Soren Schwartz/Dropbox/Egne dokumenter/Skole/master/opgave/Figures/")
#### Crypto ####
coinList.xts <- list(
  BitCoinYahoo.xts = xts::xts(BitCoinYahoo[,2:7], order.by = BitCoinYahoo[,1]),
  BitCashYahoo.xts = xts::xts(BitCashYahoo[,2:7], order.by = BitCashYahoo[,1]),
  EthereumYahoo.xts = xts::xts(EthereumYahoo[,2:7], order.by = EthereumYahoo[,1]),
  RippleYahoo.xts = xts::xts(RippleYahoo[,2:7], order.by = RippleYahoo[,1])
)
MSCI.xts <- list(
  days = xts::xts(MSCI_DP[,2], order.by = MSCI_DP[,1]),
  weeks = xts::xts(MSCI_WP[,2], order.by = MSCI_WP[,1]),
  months = xts::xts(MSCI_MP[,2], order.by = MSCI_MP[,1])
)
dailyExcess <- Log_Period_Vol(listCoins = coinList.xts, listIndex = MSCI.xts,
                              period = "days",
                              delta = 60/61, annu = 365.25,
                              dateRange = list(
                                BitCoin = "2013/",
                                BitCash = "2017-08-01/",
                                Ethereum = "2016-02-01/",
                                Ripple = "2014-01-01/",
                                Cum = "2013/"
                              ))
coinAd <- list(
  BitCoinYahoo.xts = xts::xts(BitCoinYahoo[,2:7], order.by = BitCoinYahoo[,1]),
  BitCashYahoo.xts = xts::xts(BitCashYahoo[,2:7], order.by = BitCashYahoo[,1]),
  EthereumYahoo.xts = xts::xts(EthereumYahoo[,2:7], order.by = EthereumYahoo[,1]),
  RippleYahoo.xts = xts::xts(RippleYahoo[,2:7], order.by = RippleYahoo[,1])
) %>%
  lapply(quantmod::Ad)
FX <- merge(coinAd$BitCoinYahoo.xts, coinAd$BitCashYahoo.xts,
            coinAd$RippleYahoo.xts, coinAd$EthereumYahoo.xts
            )
FX <- FX[!duplicated(zoo::index(FX)),]
colnames(FX) <- c("BTC", "BCH", "XRP", "ETH")

X <- merge(dailyExcess$BitCoin[-1,1], dailyExcess$BitCash[-1,1],
            dailyExcess$Ripple[-1,1], dailyExcess$Ethereum[-1,1]
           )
colnames(X) <- c("BTC", "BCH", "XRP", "ETH")

plot.zoo(FX, xlab = "Time", main = "Exchange rates to USD",
         col = c("black", "royalblue3", "maroon3", "darkorange2"))
plot.zoo(X, xlab = "Time", main = "Log-returns of exchange rates to USD",
         col = c("black", "royalblue3", "maroon3", "darkorange2"))
## Weekly
X.w <- apply.weekly(X, FUN = colSums)
dim(X.w)
## Monthly
X.m <- apply.monthly(X, FUN = colSums)
dim(X.m)
plot.zoo(X.m, type = "h", xlab = "Time", main = "Monthly log-returns",
         col = c("black", "royalblue3", "maroon3", "darkorange2"))
pairs(as.zoo(X), gap = 0, cex = 0.4)

## Auto- and crosscorrelations of returns and absolute returns
# Daily
pdf(file = paste0(outputFig, "acfDaily.pdf"),
    width = 8, height = 6)
par(mfrow = c(2,2))
acf(X$BTC, na.action = na.omit, main = "Bitcoin \n Daily"); acf(X$BCH, na.action = na.omit, main = "Bitcash \n Daily")
acf(X$XRP, na.action = na.omit, main = "Ripple \n Daily"); acf(X$ETH, na.action = na.omit, main = "Ethereum \n Daily")# raw
dev.off()
pdf(file = paste0(outputFig, "acfDailyAbs.pdf"),
    width = 8, height = 6)
par(mfrow = c(2,2))
acf(abs(X$BTC), na.action = na.omit, main = "Bitcoin - abs \n Daily"); acf(abs(X$BCH), na.action = na.omit, main = "Bitcash - abs \n Daily")
acf(abs(X$XRP), na.action = na.omit, main = "Ripple - abs \n Daily"); acf(abs(X$ETH), na.action = na.omit, main = "Ethereum - abs \n Daily")# absolute values
dev.off()

### 2 Apply Ljung--Box tests ##
## Compute Ljung--Box tests
LB.raw   <- apply(X,        2, Box.test, lag = 10, type = "Ljung-Box")
LB.abs   <- apply(abs(X),   2, Box.test, lag = 10, type = "Ljung-Box")
LB.raw.m <- apply(X.m,      2, Box.test, lag = 10, type = "Ljung-Box")
LB.abs.m <- apply(abs(X.m), 2, Box.test, lag = 10, type = "Ljung-Box")

## Extract p-values
p.LB.raw   <- sapply(LB.raw,   `[[`, "p.value")
p.LB.abs   <- sapply(LB.abs,   `[[`, "p.value")
p.LB.raw.m <- sapply(LB.raw.m, `[[`, "p.value")
p.LB.abs.m <- sapply(LB.abs.m, `[[`, "p.value")
xtable::xtable(round(cbind(p.LB.raw, p.LB.abs, p.LB.raw.m, p.LB.abs.m), 2))

par(mfrow = c(1,1))
## Plot of returns
pdf(file = paste0(outputFig, "timeSeriesLogRe.pdf"),
    width = 8, height = 6)
plot.zoo(X, xlab = "Time", main = "Log-returns of exchange rates to USD",
         col = c("black", "royalblue3", "maroon3", "darkorange2"))
dev.off()
par(mfrow = c(1,1))

## Plot of volatilities
X.vols <- zoo::rollapply(X, width = 30, FUN = function(x) apply(x, 2, sd))
pdf(file = paste0(outputFig, "timeSeriesVolLogRe.pdf"),
    width = 8, height = 6)
plot.zoo(X.vols, xlab = "Time", main = "Volatility estimates",
         col = c("black", "royalblue3", "maroon3", "darkorange2"))
dev.off()

L <- -returns(coinAd$BitCoinYahoo.xts)
xtr.L <- L[rank(as.numeric(-L)) <= 100]

pdf(file = paste0(outputFig, "100largelosses.pdf"),
    width = 8, height = 6)
plot(as.numeric(xtr.L), type = "h", xlab = "Time", ylab = "100 largest losses")
dev.off()

spcs <- as.numeric(diff(time(xtr.L)))

pdf(file = paste0(outputFig, "qq100largelosses.pdf"),
    width = 8, height = 6)
qqplot(qexp(ppoints(length(spcs))), y = spcs, xlab = "Theoretical quantiles",
       ylab = "Sample quantiles")
qqline(spcs, distribution = qexp)
dev.off()

L. <- xts(rt(length(L), df = 4), time(L))
xtr.L. <- L.[rank(as.numeric(-L.)) <= 100]
pdf(file = paste0(outputFig, "100largePois.pdf"),
    width = 8, height = 6)
plot(as.numeric(xtr.L.), type = "h", xlab = "Time", ylab = "100 largest losses")
dev.off()
spcs. <- as.numeric(diff(time(xtr.L.)))
pdf(file = paste0(outputFig, "qq100largePois.pdf"),
    width = 8, height = 6)
qq_plot(spcs., FUN = qexp, method = "empirical")
dev.off()

pdf(file = paste0(outputFig, "qqplotWeekly.pdf"),
    width = 8, height = 6)
par(mfrow = c(2,2))
for (i in 1:4) {
  qq_plot(X.w[,i], FUN = qnorm, method = "empirical", main = names(X.w)[i])
}
dev.off()
pdf(file = paste0(outputFig, "qqplotDaily.pdf"),
    width = 8, height = 6)
par(mfrow = c(2,2))
for (i in 1:4) {
  qq_plot(X[,i], FUN = qnorm, method = "empirical", main = names(X)[i])
}
dev.off()
par(mfrow = c(1,1))

X. <- list(daily = X,
           weekly = apply.weekly(X, FUN = colSums),
           monthly = apply.monthly(X, FUN = colSums),
           quarterly = apply.quarterly(X, FUN = colSums))

## Formal tests
pvals <- sapply(X., function(x) apply(x, 2, function(data) {
  jarque.test(data[which(!is.na(data))])$p.value
}))
pvals < 0.05
xtable::xtable(pvals < 0.05)

### Multi variate ###
X <- merge(dailyExcess$BitCoin[-1,1], dailyExcess$BitCash[-1,1],
           dailyExcess$Ripple[-1,1], dailyExcess$Ethereum[-1,1]
           , all = FALSE
)
colnames(X) <- c("BTC", "BCH", "XRP", "ETH")
pairs(as.zoo(X), gap = 0, cex = 0.4)
## Aggregating log returns by summation for each column
## Weekly
X.w <- apply.weekly(X, FUN = colSums)
## Monthly
X.m <- apply.monthly(X, FUN = colSums)

pdf(file = paste0(outputFig, "crossserialCor.pdf"),
    width = 8, height = 6)
pairs(as.zoo(X), gap = 0, cex = 0.4)
dev.off()

pdf(file = paste0(outputFig, "acfCross.pdf"),
    width = 8, height = 6)
acf(X[,-which(names(X) == "BCH")])
dev.off()
pdf(file = paste0(outputFig, "acfCrossAbs.pdf"),
    width = 8, height = 6)
acf(abs(X[,-which(names(X) == "BCH")]))
dev.off()

X. <- apply(X, 2, rank)
pdf(file = paste0(outputFig, "pseudoObsCrypto.pdf"),
    width = 8, height = 6)
par(mfrow = c(3,2))
plot(X., main = "Componentwise ranks")
plot(X.[,c(1,3)], main = "Componentwise ranks")
plot(X.[,c(1,4)], main = "Componentwise ranks")
plot(X.[,c(2,3)], main = "Componentwise ranks")
plot(X.[,c(2,4)], main = "Componentwise ranks")
plot(X.[,c(3,4)], main = "Componentwise ranks")
dev.off()
par(mfrow = c(1,1))

X.cor <- corrRollMatrixCpp(X[,-which(names(X) == "BCH")], period = 30)[,2:3]
  colnames(X.cor) <- colnames(X[,-which(names(X) == "BCH")])[-1]
  rownames(X.cor) <- as.character(zoo::index(X))
X.vols <- IPAMomentum::sdRollMatrixCpp(X[,-which(names(X) == "BCH")], period = 30)
  colnames(X.vols) <- colnames(X[,-which(names(X) == "BCH")])
  rownames(X.vols) <- as.character(zoo::index(X))

pdf(file = paste0(outputFig, "crossCorTSplot_XRP_BTC.pdf"),
                  width = 8, height = 6)
X.cor.vols <- cbind(X.cor[,1], X.vols[,c("BTC", "XRP")])
plot.zoo(na.omit(xts::as.xts(X.cor.vols)),
         xlab = "Time", main = "Cross-correlation and volatility estimates - BTC and XRP",
         ylab = c(expression(hat(rho)["BTC,XRP"]), "BTC", "XRP"))
dev.off()
pdf(file = paste0(outputFig, "crossCorTSplot_ETH_BTC.pdf"),
    width = 8, height = 6)
X.cor.vols <- cbind(X.cor[,2], X.vols[,c("BTC", "ETH")])
plot.zoo(na.omit(xts::as.xts(X.cor.vols)),
         xlab = "Time", main = "Cross-correlation and volatility estimates - BTC and ETH",
         ylab = c(expression(hat(rho)["BTC,ETH"]), "BTC", "ETH"))
dev.off()
pdf(file = paste0(outputFig, "crossCorTSplot.pdf"),
    width = 8, height = 6)
plot.zoo(na.omit(xts::as.xts(X.cor)),
         xlab = "Time", main = "Cross-correlation and volatility estimates",
         ylab = c(expression(hat(rho)["BTC,XRP"]),
                  expression(hat(rho)["BTC,ETH"])))
dev.off()

## Volatilities
BTC.sig <- as.numeric(X.vols[,"BTC"])
XRP.sig  <- as.numeric(X.vols[,"XRP"])
ETH.sig  <- as.numeric(X.vols[,"ETH"])

fisher <- function(r) log((1 + r)/(1 - r))/2
rho <- fisher(X.cor)

pdf(file = paste0(outputFig, "fisherTransRhoReg.pdf"),
    width = 8, height = 6)
par(mfrow = c(2,2))
## BTC and XRP
plot(BTC.sig, rho[,"XRP"],
     xlab = expression("Estimated "~hat(sigma)["BTC"]),
     ylab = expression("Estimated "~hat(rho)["BTC,XRP"]))
reg <- lm(rho ~ BTC.sig)
abline(reg, col = "royalblue3")
## XRP
plot(XRP.sig, rho[,"XRP"],
     xlab = expression("Estimated "~hat(sigma)["XRP"]),
     ylab = expression("Estimated "~hat(rho)["BTC,XRP"]))
reg <- lm(rho ~ XRP.sig)
abline(reg, col = "royalblue3")
## BTC and ETH
plot(BTC.sig, rho[,"ETH"],
     xlab = expression("Estimated "~hat(sigma)["BTC"]),
     ylab = expression("Estimated "~hat(rho)["BTC,ETH"]))
reg <- lm(rho ~ BTC.sig)
abline(reg, col = "royalblue3")
## ETH
plot(ETH.sig, rho[,"ETH"],
     xlab = expression("Estimated "~hat(sigma)["ETH"]),
     ylab = expression("Estimated "~hat(rho)["BTC,ETH"]))
reg <- lm(rho ~ ETH.sig)
abline(reg, col = "royalblue3")
par(mfrow = c(1,1))
dev.off()

#### Other asset types ####
SX <- returns(stocks.xts[,-4])
IX <- returns(indx.xts)
FX <- returns(cur.xts)
COMX <- returns(com.xts)
ZCB <- ZCB.xts[,c("THREEFY1","THREEFY3", "THREEFY10")]
colnames(ZCB) <- c("Y1", "Y3", "Y10")
ZCBX <- returns(ZCB)

## Stock prices ##
pdf(file = paste0(outputFig, "OtherAssets/stockReturn.pdf"),
    width = 8, height = 6)
plot.zoo(SX, xlab = "Time", main = "Log-returns \n Stocks",
         col = c(RColorBrewer::brewer.pal(4, name = "Dark2")),#, "red"),
         nc = 2)
dev.off()
pdf(file = paste0(outputFig, "OtherAssets/stockPairs.pdf"),
    width = 8, height = 6)
pairs(as.zoo(SX), gap = 0, cex = 0.4)
dev.off()

## Index ##
pdf(file = paste0(outputFig, "OtherAssets/indxReturn.pdf"),
    width = 8, height = 6)
plot.zoo(IX, xlab = "Time", main = "Log-returns \n Indexes",
         col = c(RColorBrewer::brewer.pal(3, name = "Dark2")))
dev.off()
pdf(file = paste0(outputFig, "OtherAssets/indxPairs.pdf"),
    width = 8, height = 6)
pairs(as.zoo(IX), gap = 0, cex = 0.4)
dev.off()

## Exchange rates ##
pdf(file = paste0(outputFig, "OtherAssets/curReturn.pdf"),
    width = 8, height = 6)
plot.zoo(FX, xlab = "Time", main = "Log-returns \n Exchange rates to USD",
         col = c(RColorBrewer::brewer.pal(3, name = "Dark2")))
dev.off()
pdf(file = paste0(outputFig, "OtherAssets/curPairs.pdf"),
    width = 8, height = 6)
pairs(as.zoo(FX), gap = 0, cex = 0.4)
dev.off()

## Commodities rates #
pdf(file = paste0(outputFig, "OtherAssets/comReturn.pdf"),
    width = 8, height = 6)
plot.zoo(COMX, xlab = "Time", main = "Log-returns \n Commodity rates to USD",
         col = c(RColorBrewer::brewer.pal(3, name = "Dark2"))[1:2])
dev.off()
pdf(file = paste0(outputFig, "OtherAssets/comPairs.pdf"),
    width = 8, height = 6)
pairs(as.zoo(COMX), gap = 0, cex = 0.4)
dev.off()

#### Zero-coupon bond yields ##
pdf(file = paste0(outputFig, "OtherAssets/ZCBReturn.pdf"),
    width = 8, height = 6)
plot.zoo(ZCBX, xlab = "Time", main = "Differences (3 maturities)",
         col = c(RColorBrewer::brewer.pal(3, name = "Dark2")))
dev.off()
pdf(file = paste0(outputFig, "OtherAssets/ZCBPairs.pdf"),
    width = 8, height = 6)
pairs(as.zoo(ZCBX), gap = 0, cex = 0.4)
dev.off()

### Univariate_stylized_facts ###
SX.m <- apply.monthly(SX[,c(1,3,4)], FUN = colSums)

pdf(file = paste0(outputFig, "OtherAssets/stockAcf.pdf"),
    width = 8, height = 6)
acf(SX[,c(1,3,4)])
dev.off()
pdf(file = paste0(outputFig, "OtherAssets/stockAcfAbs.pdf"),
    width = 8, height = 6)
acf(abs(SX[,c(1,3,4)]))
dev.off()

## Extract p-values
p.LB.raw   <- apply(SX[,c(1,3,4)], 2, Box.test, lag = 10, type = "Ljung-Box") %>%
  sapply(`[[`, "p.value")
p.LB.abs   <- apply(abs(SX[,c(1,3,4)]),2, Box.test, lag = 10, type = "Ljung-Box") %>%
  sapply( `[[`, "p.value")
p.LB.raw.m <- apply(SX.m,2, Box.test, lag = 10, type = "Ljung-Box") %>%
  sapply(`[[`, "p.value")
p.LB.abs.m <- apply(abs(SX.m), 2, Box.test, lag = 10, type = "Ljung-Box") %>%
  sapply(`[[`, "p.value")
round(cbind(p.LB.raw, p.LB.abs, p.LB.raw.m, p.LB.abs.m), 2) %>%
  xtable::xtable()

## Plot of volatilities
SX.vols <- zoo::rollapply(SX[,c(1,3,4)], width = 30, FUN = function(x) apply(x, 2, sd))
IX.vols <- zoo::rollapply(IX, width = 30, FUN = function(x) apply(x, 2, sd))
FX.vols <- zoo::rollapply(FX, width = 30, FUN = function(x) apply(x, 2, sd))
COM.vols <- zoo::rollapply(COMX, width = 30, FUN = function(x) apply(x, 2, sd))
ZCB.vols <- zoo::rollapply(ZCBX, width = 30, FUN = function(x) apply(x, 2, sd))

pdf(file = paste0(outputFig, "OtherAssets/stockVolRoll.pdf"),
    width = 8, height = 6)
plot.zoo(SX.vols, xlab = "Time", main = "Volatility estimates \n Stocks",
         col = c(RColorBrewer::brewer.pal(4, name = "Dark2")))
dev.off()
pdf(file = paste0(outputFig, "OtherAssets/indxVolRoll.pdf"),
    width = 8, height = 6)
plot.zoo(IX.vols, xlab = "Time", main = "Volatility estimates \n Index",
         col = c(RColorBrewer::brewer.pal(3, name = "Dark2")))
dev.off()
pdf(file = paste0(outputFig, "OtherAssets/curVolRoll.pdf"),
    width = 8, height = 6)
plot.zoo(FX.vols, xlab = "Time", main = "Volatility estimates \n Currencies",
         col = c(RColorBrewer::brewer.pal(3, name = "Dark2")))
dev.off()
pdf(file = paste0(outputFig, "OtherAssets/comVolRoll.pdf"),
    width = 8, height = 6)
plot.zoo(COM.vols, xlab = "Time", main = "Volatility estimates \n Commodities",
         col = c(RColorBrewer::brewer.pal(3, name = "Dark2"))[1:2])
dev.off()
pdf(file = paste0(outputFig, "OtherAssets/ZCBVolRoll.pdf"),
    width = 8, height = 6)
plot.zoo(ZCB.vols, xlab = "Time", main = "Volatility estimates \n ZCB",
         col = c(RColorBrewer::brewer.pal(3, name = "Dark2")))
dev.off()
3schwartz/SpecialeScrAndFun documentation built on May 4, 2019, 6:29 a.m.