Search code examples
rquantmod

Looping with quantmod


I'm new to R, loops and quantmod. I'm trying to convince quantmod to skip any ticker it's unable to process and continue on to the next ticker symbol, instead of stopping. I thought I'd found my answer here how do I loop through all the stocks with quantmod and ttr? but I'm not able to get Rime's solution to work:

If the loop breaks, say on the 50th iteration, then just re run the last block of code by changing the following

# Actual loop: 
# IF IT BREAKS ON THE 50th ITERATION, it must be skipped, therefore change it to 51
for(i in 51:length(symbols)) { 
  symbols[i]-> symbol
...

Below is my original code, which only returns 8 of the many values(so I assume that 9 is the trouble spot).

library(gdata)
d = read.xls("~/Documents/TEST.xlsx", sheet = 1, stringsAsFactors=F)

library(quantmod)
sym <- as.character(d[,1])

results <- NULL

for (ii in sym){
  data1 <- getSymbols(Symbols = ii, 
                      src = "yahoo", 
                      from = Sys.Date() - 100, 
                      auto.assign = FALSE)
  de = head(data1,150)
  colnames(de) <- c("open","high","low","close","volume","adj.")
  overnightRtn <- (as.numeric(de[2:nrow(de),"open"])/as.numeric(de[1:(nrow(de)-1),"close"])) - 1

  results <- rbind(results,cbind(
    paste(round(min(overnightRtn,na.rm=T),5),"%",sep="")))

} 

colnames(results) <- c("overnightRtn2")
rownames(results) <- sym
View(results)

When I change for(ii in sym) to for(ii in 9:length(sym)) I get an error:

could not find function "getSymbols.9"

Here is the start of d[,1] :

[1] "ABX"    "ACC"    "ACCO"   "ACE"    "ACG"    "ACH"    "ACI"    "ACM"    "ACMP"   "ACN"

Solution

  • There are some workarounds for errors when looping in R, one way to do this will be using the tryCatchfunction, juba showed here how to do it. I also made sure that the for loop will only continue when the data1variable is assigned some value.

    Change your for loop for the following code and it should work for what you are asking.

    for (ii in sym){
      data1 <- NULL                               # NULL data1
      data1 <- tryCatch(getSymbols(Symbols = ii,  
                          src = "yahoo", 
                          from = Sys.Date() - 100, 
                          auto.assign = FALSE),
                        error=function(e){})      # empty function for error handling
      if(is.null(data1)) next()                   # if data1 is still NULL go to next ticker
      de = head(data1,150)
      colnames(de) <- c("open","high","low","close","volume","adj.")
      overnightRtn <- (as.numeric(de[2:nrow(de),"open"])/as.numeric(de[1:(nrow(de)-1),"close"])) - 1
    
      results <- rbind(results,cbind(
        paste(round(min(overnightRtn,na.rm=T),5),"%",sep="")))
    }