R/fun_tstats_allModels.R

#' fun_tstats_allModels
#'
#' @description For each of the element in list a linear regression is made with the element in the list as independent variables.
#' A table of t-statistics is return and the maximum VIF value within each model
#'
#' @param list List of daily data with mean and sd in second and third row
#' @param period character vector Period of rebalance
#' @param lag int Number of lags
#'
#' @return A list
#'  \item{name name}{description Name n which one can se periodicity and lag of object}
#'  \item{name Sharpe}{description Table of t-statistics is return and the maximum VIF value within each model}
#' @export
#'
fun_tstats_allModels <- function(list = list(BTC= BTC.daily, ETH = ETH.daily, XRP = XRP.daily, BCH = BCH.daily),
                           period = c("days", "weeks", "months", "quarters", "years"),
                           lag = 12){

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

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

  tlist <- list()

  for(i in 1:length(list)) {
    dependent <- names(list)[i]
    independent <- names(list)[-i]

    LMdata <- cbind(PeriodAndLags[[dependent]][LMIndex,"reVol"], do.call(cbind, lapply(PeriodAndLags[independent], function(x) {
      x[LMIndex,5]
    })))

    LMdata <- LMdata[-unique(which((is.infinite(LMdata) | is.na(LMdata)), arr.ind = TRUE)[,1]),]
    colnames(LMdata) <- names(list)
    formel <- paste(dependent, "~", paste(independent, collapse = " + "))

    model <- lm(formel, data = as.data.frame(LMdata))

    tstats <- summary(model)$coef[,c("t value"),drop = F] %>%
      t()
    colnames(tstats)[1] <- "alpha"
    row.names(tstats) <- dependent
    tstats <- cbind(tstats, VIFmax = max(car::vif(model))) %>%
      round(digits = 2)
    tlist[[i]] <- tstats
  }

  lm_tstats <- do.call(dplyr::bind_rows, lapply(tlist, function(x) {
    data.frame(cbind(Dep = rownames(x), x))
  }))

  lm_tstats[is.na(lm_tstats)] <- ""

  lm_tstats <- cbind(lm_tstats[,-which(names(lm_tstats) == "VIFmax")],
                     VIFmax = lm_tstats[,c("VIFmax")])
  nameOut <- paste0("tstats-",period,"-",lag)

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