4

I download historical prices with quantmod's getSymbols function for multiple tickers and convert them into either a list or a multivariate XTS with the following code:

library(quantmod)

myenv <- new.env()
tickers <- c("^GSPC", "AAPL", "MSFT", "GOOG", "^RUT")
getSymbols(tickers, env=myenv)
ll <- eapply(myenv, function(x) x)        # Convert to list
ts <- do.call(merge, (eapply(myenv, Ad))) # Convert to multivariate XTS and extract only the adjusted price

The problem I have with this approach is that the order of the tickers in the list and the XTS are not the same as what I specified in tickers:

> names(ll)
[1] "AAPL" "GSPC" "GOOG" "RUT"  "MSFT"
> names(ts)
[1] "AAPL.Adjusted" "GSPC.Adjusted" "GOOG.Adjusted" "RUT.Adjusted" 
[5] "MSFT.Adjusted"

I think this is because eapply performs the operations in a random order, as explained in the help pages of eapply:

Note that the order of the components is arbitrary for hashed environments.

How can I perform the same operations above but have an output that is in the same order as specified in my tickers vector? I.e. first item of the list / first column of XTS should correspond to first element of the tickers vector and so on.

mchangun
  • 9,814
  • 18
  • 71
  • 101
  • Try `tickers <- c("GSPC", "AAPL", "MSFT", "GOOG", "RUT"); namesll <- c("AAPL", "GSPC", "GOOG", "RUT", "MSFT"); namesll[order(tickers)]`. – Roman Luštrik Mar 21 '13 at 07:54

2 Answers2

4

You could just subset the results of eapply into the order you want.

library(quantmod)
tickers <- c("^GSPC", "AAPL", "MSFT", "GOOG", "^RUT")
myenv <- new.env()
symnames <- getSymbols(tickers, env=myenv)  # getSymbols returns adjusted names
ts <- do.call(merge, eapply(myenv, Ad)[symnames])
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
2

Try mget instead of eapply. Note: Need to use gsub to remove ^ from ticker names to get object names in myenv.

library(quantmod)

myenv <- new.env()
tickers <- c("^GSPC", "AAPL", "MSFT", "GOOG", "^RUT")
getSymbols(tickers, env = myenv)
## [1] "GSPC" "AAPL" "MSFT" "GOOG" "RUT" 

test <- mget(gsub("\\^", "", tickers), envir = myenv)
ts <- do.call(merge, lapply(test, Ad))
names(ts)
## [1] "GSPC.Adjusted" "AAPL.Adjusted" "MSFT.Adjusted" "GOOG.Adjusted" "RUT.Adjusted" 

tickers
## [1] "^GSPC" "AAPL"  "MSFT"  "GOOG"  "^RUT" 
CHP
  • 16,981
  • 4
  • 38
  • 57