Skip to content
Prev 13426 / 15274 Next

aggregate an xts by factors

On Mon, Aug 3, 2015 at 6:51 PM, Aaron Goldenberg
<aaron at quantrisktrading.com> wrote:
The problem is that you're trying to mix types in the xts data.  xts
extends zoo, which is simply a matrix with an index attribute, and you
can't mix types in a matrix.

There are many different ways to do this.  Here's one way that should
be easily extensible to more sectors.

library(quantmod)
Computer <- new.env()
Financial <- new.env()
getSymbols("AAPL;GOOG", from="2015-07-01", env=Computer)
getSymbols("GS", from="2015-07-01", env=Financial)

sectorReturnSum <- function(env) {
  adj <- do.call(cbind, eapply(env, Ad))
  ret <- ROC(adj, type="discrete")
  xts(rowSums(ret, na.rm=TRUE), index(ret))
}
combined <- merge(Computer = sectorReturnSum(Computer),
  Financial = sectorReturnSum(Financial))