Simplifying Stock Price Pulls with Quantmod in R

Ivan Vanchev

Tuesday, February 2, 2016

While I must say that the quantmod package for R is quite handy, one of the things I find a little inconvenient is that providing a vector of \(n\) tickers doesn't return a data frame of prices but instead creates \(n\) objects with OHLC data for each ticker.

I wrote myself a little function that remedies this little pet peeve of mine. The code below returns a data frame with adjusted close prices for all tickers provided. The function uses a try() wrapper to avoid problems with any invalid tickers or missing yahoo data.

         <- function(tickers,, {
                  # Pull price data for a list of securities using 'quantmod' and return a data frame containing adjusted close price series. 
                  # Args:
                  #      tickers: Vector of security tickers (no "US Equity" appended).
                  # Start date for price pull.
                  # End date for price pull.
                      require(quantmod, quietly = TRUE)
                      try(getSymbols(tickers, from =, to =, silent = TRUE)
             <- Ad(get(tickers[1]))
                      for(i in 2:length(tickers)) {
                         try( <- merge(, Ad(get(tickers[i]))), silent = TRUE)

You can probably shorten the function by using a or Reduce() instead of that for() loop, but this gets the job done. For ticker vectors longer than 5, getSymbols() delays pulling data by 1 second. You can try looping through 5 tickers at a time to circumvent that behavior but risk having yahoo block your requests. This still doesn't beat Rblpapi package, but for a free alternative it's alright.