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.


                  pull.price.data <- function(tickers, from.date, to.date) {
                  #
                  # 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).
                  #      from.date: Start date for price pull.
                  #      to.date: End date for price pull.
  
                      require(quantmod, quietly = TRUE)
                      try(getSymbols(tickers, from = from.date, to = to.date), silent = TRUE)
  
                      price.data.frame <- Ad(get(tickers[1]))
                      for(i in 2:length(tickers)) {
                         try(price.data.frame <- merge(price.data.frame, Ad(get(tickers[i]))), silent = TRUE)
                      }
                      return(price.data.frame)
                  }
                

You can probably shorten the function by using a do.call() 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.


000webhost logo