Search code examples
rmergextsquantmodportfolio

Combine multiple xts objects created by getSymbols


I'm attempting to carry out some stock portfolio simulations. Using the Package 'quantmod' I have downloaded price data on multiple securities. I would like to accomplish two things.

1) I'd like to create a list/array of the xts objects, where each security ticker symbol would correspond to a time series object in the list.

2) More importantly I'd like to create a time series data frame with the adjusted share price for each security, by day.

I have the following code, which downloads all the price data.

library(quantmod)

tickers <- c("SNC.TO", "PHII", "HBC.TO", "GTE", "MOO",
             "MND.TO", "STKL", "SXC","XIU.TO")

for(i in tickers) {
  getSymbols(i, from = "2010-06-30", to = "2015-06-30") 
}

This is what I have so far to try and create the list of dataframes

pframe <- list()
for(i in tickers) {
  pframe[[i]] <- assign(i)
}

Solution

  • The simplest way to do this is to load all the data into a new environment. Then you can use eapply to extract all the adjusted close columns into a list. Finally, you can use do.call to merge all the adjusted close prices in the list into one xts object.

    library(quantmod)
    tickers <- c("SNC.TO", "PHII", "HBC.TO", "GTE", "MOO",
                 "MND.TO", "STKL", "SXC","XIU.TO")
    dataEnv <- new.env()
    getSymbols(tickers, from="2010-06-30", to="2015-06-30", env=dataEnv)
    plist <- eapply(dataEnv, Ad)
    pframe <- do.call(merge, plist)