Search code examples
rapiquandl

API Call per Column in R


I have one column in a data frame that consists of ticker codes such as AAPL (for Apple), TWTR (for Twitter), and many more. I want to create new columns based on the number of ticker codes from the data frame, and filled those columns with the closing stock price which will be retrieved from API. The result should look like the following: Click here for the expected output

However as I run the code below, it shows a warning and an error as the number of rows between columns are different. Does anyone have the solution to this?

library(Quandl)

portfolio <- data.frame(Code=c("AAPL", "TWTR", "MSFT"),
                    stringsAsFactors=FALSE)


analytic <- function(pf, startDate) {
  z <- do.call(cbind.data.frame, lapply(seq(1:nrow(pf)), function(x) {
   API <- Quandl(paste0("WIKI/", pf$Code[x]),
              type = "raw", 
              start_date = startDate, 
              end_date=Sys.Date())
   ValuebyDate <- API[,c("Date", "Close")]
   return(ValuebyDate)
}))
return(z)
}

analytic(portfolio, "2016-01-01")

Solution

  • Here's another way of solving your problem using a different approach.

    rm(list=ls())
    library(tseries)
    portfolio <- data.frame(Code=c("AAPL", "TWTR", "MSFT"),
                    stringsAsFactors=FALSE)
    startDate = "2016-01-04"
    
    getHistData <- function(x){
    
      ts <- get.hist.quote(instrument = portfolio$Code[x], start = startDate, end = Sys.Date(),
                                          quote = "Close", provider = "yahoo", retclass = "zoo")
      names(ts) <- portfolio$Code[x]
      head(ts)
      return(ts)
    }
    
    ts1 = getHistData(1)
    head(ts1)
    ts2 = getHistData(2)
    head(ts2)
    ts3 = getHistData(3)
    head(ts3)
    
    cbind(ts1,ts2,ts3)
    

    Updated: this will allow you to build the table without manually running ts1, ts2, ts3

    library(zoo)
    stockPrice <- zoo()
    
    for (i in 1: length(portfolio$Code)) {
      ts <- getHistData(i)
      stockPrice <- zoo(merge(ts, stockPrice, all=TRUE))
    }
    
    head(stockPrice)