Search code examples
rloopsdownloadsymbols

getSymbols.yahoo "method" in a loop with several symbols and corresponding dates in R


"Method" getSymbols.yahoo allows putting a vector in lieu of the Symbols argument allowing the download of several tickers without using a loop:

library(quantmod)

someSymbols <- c("RMO", "NKLA", "JD", "AAPL", "IBM", "SPCE", "MRNA", "MPNGF")

getSymbols.yahoo(someSymbols, auto.assign = TRUE, env = globalenv())

However, this does not seem to work whe one adds a date vector of equal length in the from = argument, such as:

library(quantmod)

someSymbols <- c("RMO", "NKLA", "JD", "AAPL", "IBM", "SPCE", "MRNA", "MPNGF")
someDates <- as.Date(c(18659, 18659, 18659, 18901, 18901, 18659, 18901, 
                       18659), origin = "1970-01-01")

getSymbols.yahoo(someSymbols, auto.assign = TRUE, env = globalenv(), from = someDates)

My question:

  • Whilst respective orders of someSymbols and someDates must be kept and with (preferably) only the System Libraries and library(quantmod) (without which getSymbols.yahoo does not work), what piece of code could download each symbol with its corresponding date?

Thanks in advance.


Systems used:

  • R version: 4.1.1 (2021-08-10)
  • RStudio version: 1.4.1717
  • OS: macOS Catalina version 10.15.7 and macOS Big Sur version 11.6

Solution

  • Use Map to pass one element at a time from each vector to the function.

    library(quantmod)
    
    someSymbols <- c("RMO", "NKLA", "JD", "AAPL", "IBM", "SPCE", "MRNA", "MPNGF")
    someDates <- as.Date(c(18659, 18659, 18659, 18901, 18901, 18659, 18901, 
                           18659), origin = "1970-01-01")
    
    Map(\(x, y) getSymbols(
      Symbols = x, 
      env = globalenv(), 
      auto.assign = TRUE, 
      from = y,
      src = "yahoo"), someSymbols, someDates)