R/alignReturnsWeights.R

Defines functions alignReturnsWeights

Documented in alignReturnsWeights

#' Align Index of Two Xts Objects
#'
#' @param R xts object with asset returns
#' @param weights xts object with asset weights
#'
#' @return list containing index aligned xts objects [1] returns and [2] weights
#' @export
#' @importFrom magrittr %>%
#'
#' @examples alignReturnsWeights(returns, weights)
#'
alignReturnsWeights <- function(R, weights) {
  corrected_xts <- list()
  r <- ncol(R)
  w <- ncol(weights)
  col_names_R <- colnames(R)
  col_names_W <- colnames(weights)

  combined_xts <- merge.xts(R, weights, join = "right")

  corrected_xts[["returns"]] <- combined_xts %>%
    na.fill(., fill = 0) %>%
    .[, c(1:r)] %>%
    `colnames<-`(col_names_R)

  corrected_xts[["weights"]] <- combined_xts %>%
    na.fill(., fill = 0) %>%
    .[, c((r + 1):(r + w))] %>%
    `colnames<-`(col_names_W)

  if (all(round(rowSums(corrected_xts$weights)) == 1) != TRUE) {
    warning("Weights do not sum up to 1")
  }
  if (all(index(corrected_xts$weights) == index(corrected_xts$returns)) != TRUE) {
    stop("Not able to align xts objects by index")
  }

  return(corrected_xts)
}
rengelke/quantTraiding_trato documentation built on Oct. 13, 2020, 12:01 p.m.