R/extractWeights.optimize.portfolio.rebalancing.R

Defines functions extractWeights.optimize.portfolio.rebalancing

Documented in extractWeights.optimize.portfolio.rebalancing

#
# File extractWeights.optimize.portfolio.rebalancing.R
#
# This file overwrites this function from PortfolioAnalytics
#'
#'
#' NEW function to deal with extractWeights with rebalancing
#'
#' This function overrides extractWeights from PortfolioAnalytics.
#' It was rewritten to deal with the accelerated version of
#' optimize.portfolio.rebalancing, where all assets with zero
#' weights have been removed at each WFO dates.  Therefore,
#' the resulting weights at each WFO date is a subset of the
#' universe and only includes non-zero weights.
#'
#' This version of extractWeights fills in the zero weighted assets
#' when such assets are not in the weights at the WFO date.
#'
#' @method extractWeights optimize.portfolio.rebalancing
#' @export
extractWeights.optimize.portfolio.rebalancing <- function(object, ...){
  if(!inherits(object, "optimize.portfolio.rebalancing")){
    stop("Object passed in must be of class 'optimize.portfolio.rebalancing'")
  }

  sprint("USING NEW VERSION OF extractweight for rebalancing")

  tickers <- colnames(object$R)
  #sprint("tickers are:")
  #print(tickers)

  rebal_object <- object$opt_rebal
  numColumns <- length(tickers)
  numRows    <- length(rebal_object)

  result           <- matrix(nrow = numRows, ncol = numColumns)
  colnames(result) <- tickers

  for(i in 1:numRows) {
    wvec                   <- unlist(rebal_object[[i]]$weights)
    result[i, names(wvec)] <- wvec
  }

  #-------------------------------------------
  # Replace NAs with zero weights
  #-------------------------------------------
  result[is.na(result)] <- 0
  rownames(result) = names(rebal_object)
  result = as.xts(result)

  return(result)

}
jeanmarcgp/ResilientPortfolio documentation built on April 8, 2018, 5:43 p.m.