Search code examples
rxtsquantmod

R - call xts via character


Assume we have a list of characters as basis for a function, which has a xts object with the same name as result:

library(zoo)
library(xts)
library(quantmod)

l<-list("AAPL","NKE")

for(i in 1:length(l)){
  getSymbols(l[[i]], src = "yahoo")
  write.zoo(l[[i]], paste(l[[i]],".csv", sep=''), sep = ",")
}

My code does not work, cause getSymbols creates an xts object (named AAPL / NKE). My problem is, that I cannot call them properly in the write.zoo function. Can you please help me?


Solution

  • Call getSymbols with auto = FALSE to get the data directly.

    library(quantmod)
    
    syms <- c("AAPL", "NKE")
    for(s in syms) {
      dat <- getSymbols(s, auto = FALSE)
      write.zoo(dat, paste0(s, ".csv"), sep = ",")
    }