On Mon, Aug 3, 2015 at 6:51 PM, Aaron Goldenberg <aa...@quantrisktrading.com> wrote: > Alternatively, I could have two separate time series, one for each factor. > > On Mon, Aug 3, 2015 at 7:48 PM, Aaron Goldenberg <aa...@quantrisktrading.com >> wrote: > >> This seems like a simple issue but I cannot get it to work for some >> reason. I have a time series object that has daily returns of several >> stocks that I would like to aggregate by qualitative factor. In my toy >> example, for each day, I would like to have two entries, one for the sum of >> the returns of my two computer stocks and another for my financial stock. >> Then I would like to calculate the cumulative sum of the returns for each >> factor. What am I not doing correctly? >> >> library(quantmod) >> getSymbols("AAPL", src="yahoo", from="2015-07-01") >> AAPL <- dailyReturn(AAPL$AAPL.Adjusted) >> AAPL <- cbind(data.frame(AAPL), sector="Computer") >> AAPL <- as.xts(AAPL) >> getSymbols("GOOG", src="yahoo", from="2015-07-01") >> GOOG <- dailyReturn(GOOG$GOOG.Adjusted) >> GOOG <- cbind(data.frame(GOOG), sector="Computer") >> GOOG <- as.xts(GOOG) >> getSymbols("GS", src="yahoo", from="2015-07-01") >> GS <- dailyReturn(GS$GS.Adjusted) >> GS <- cbind(data.frame(GS), sector="Financial") >> GS <- as.xts(GS) >> combined <- rbind(AAPL, GOOG, GS) >> #combined <- period.sum(combined$daily.returns, endpoints(combined, >> on="days")) >> combined <- aggregate(combined, by=combined$sector, sum) >> 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)) > > [[alternative HTML version deleted]] > > _______________________________________________ > R-SIG-Finance@r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-sig-finance > -- Subscriber-posting only. If you want to post, subscribe first. > -- Also note that this is not the r-help list where general R questions > should go. -- Joshua Ulrich | about.me/joshuaulrich FOSS Trading | www.fosstrading.com _______________________________________________ R-SIG-Finance@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-sig-finance -- Subscriber-posting only. If you want to post, subscribe first. -- Also note that this is not the r-help list where general R questions should go.