R/fun_RollingCorrelation.R

#' fun_RollingCorrelation
#'
#' @param list List of daily data with mean and sd in second and third row
#' @param dep The currency the other cryptocurrencies compares against
#' @param period Period one want to convert data to. One can choose "days", "weeks", "months", "quarters" or "years"
#' @param savePlot If one want to save plot
#' @param margin Number used for rolling window
#' @param outputFig Output path if one have said TRUE to saveplot
#' @param width Width of plot saved
#' @param height heigh of plot saved
#'
#' @return A list
#'  \item{name cor_plot}{description Plot with time series of rolling correlation}
#'  \item{name corData}{description Data with rolling correlation values}
#' @export
#'
fun_RollingCorrelation <- function(list = list(BTC= BTC.daily, ETH = ETH.daily,
                                               XRP = XRP.daily, BCH = BCH.daily),
                                   dep = "BTC", period = c("minutes", "hours", "days", "weeks", "months", "quarters", "years"),
                                   savePlot = FALSE,
                                   margin = 10,
                                   outputFig = c("C:/Users/Soren Schwartz/Dropbox/Egne dokumenter/Skole/master/opgave/Figures/"),
                                   width = 8, height = 6) {

  PeriodAndLags <- lapply(list, function(x) {
    out <- fun_toPeriodCl(x, period = period) %>%
      fun_GetVolAdReturn(lag = lag)
    names(out) <- names(list)
    return(out)
  })

  CorIndex <- dplyr::intersect(rownames(PeriodAndLags[[1]]),
                               rownames(PeriodAndLags[[2]])) %>%
    dplyr::intersect(rownames(PeriodAndLags[[3]])) %>%
    dplyr::intersect(rownames(PeriodAndLags[[4]]))

  other <- names(list)[-which(names(list) == dep)]
  reVolList <- list()
  reVolList[[length(other)+1]] <- PeriodAndLags[[dep]][LMIndex,"reVol"]
  for(i in 1:length(other)) {
    reVolList[[i]] <- PeriodAndLags[[other[i]]][LMIndex,"reVol"]
  }
  reVolData <- do.call(cbind, reVolList)

  reVolData <- reVolData[-unique(which((is.infinite(reVolData) | is.na(reVolData)), arr.ind = TRUE)[,1]),]
  colnames(reVolData) <- c(other, dep)

  corList <- list()
  for(i in 1:length(other)) {
    corList[[i]] <- TTR::runCor(reVolData[,other[i]],reVolData[,dep],margin)
  }
  corData <- do.call(cbind,corList)
  corData <- corData[-unique(which((is.infinite(corData) | is.na(corData)), arr.ind = TRUE)[,1]),]
  corData <- data.frame(cbind(Date = rownames(corData), corData), row.names = NULL)
  colnames(corData) <- c("Date", other)

  corData_tidy <- tidyr::gather(corData, other, key = "Crypto", value = "Cor")
  corData_tidy[,"Date"] <- lubridate::as_date(corData_tidy[,"Date"])
  corData_tidy[,"Cor"] <- as.numeric(corData_tidy[,"Cor"])
  corData_tidy[,"Crypto"] <- as.factor(corData_tidy[,"Crypto"])

  cor_plot <- ggplot2::ggplot(corData_tidy, ggplot2::aes(x=Date, y=Cor, col=Crypto)) +
    ggplot2::geom_line() +
    ggplot2::labs(title="Time Series of Rolling correlation",
                  subtitle="BTC and others cryptocurrencies",
                  caption=paste0(margin, "-", period, " rolling window"),
                  y="Correlation",
                  color=NULL) +
    ggplot2::theme(axis.text.x = ggplot2::element_text(angle = 90, vjust=0.5, size = 8),
                   panel.grid.minor = ggplot2::element_blank())

  if(savePlot == TRUE) {
    pdf(file = paste0(outputFig, "Cor_plot_", dep, ".pdf"),
        width = width, height = height)
    print(cor_plot)
    dev.off()
  }

  out <- list(cor_plot = cor_plot,
              corData = corData)
  return(out)
}
3schwartz/SpecialeScrAndFun documentation built on May 4, 2019, 6:29 a.m.