2

I am trying to cycle through a list of symbols and download the data and save it to a csv file. individual stocks work perfectly fine if it is there, but it stops if there is an error and I do not know how to handle errors (new to R) I used part of an answer here, but I am unable to find answer on error handling while looping it to save it to file.

quantmod omitting tickers in getSymbols

startDate = Sys.Date()- 365
pth = "C:\\"
tickers <- c("LMT","AAPL","AMT", "GOOG") 
#the sapply method works by not stopping when it has issues with LMT and still it goes not to dwld AAPL, 

library(quantmod)
WoW <- new.env()
sapply(tickers, function(x){
  try(
    getSymbols(
      x,
      src ="google",
      from =startDate,
        env=WoW),
    silent=TRUE)
})


#Now for the looping to save to file, somehow it does not go althe way till GOOG. it stops at AAPL
#Error in data.frame(sym) : row names contain missing values. 


for (i in 1:length(tickers) ) { 

    col <- c( "Open","High","Low","Close","Volume")
    sym <- eval(parse(text=paste("WoW$",tickers[i],sep="")))

if (!is.null(nrow(sym))){
    colnames(sym) <- col
    sym <- data.frame(sym)
    sym <- cbind(BizDay = 0, sym)
    sym$BizDay <- rownames(sym)


    op <- paste0(pth,tickers[i],".csv")
    print(op)
    write.table(sym, file=op, na="", sep=",", row.names = FALSE)

    }          
}

Any pointers on how to handle basic errors? I have to run through full security list, and have to make sure that i handle those. but right now stuck on this.

Thanks

Hack-R
  • 22,422
  • 14
  • 75
  • 131

1 Answers1

1

Got it to work with nrow(sym) > 1 check.

xlm
  • 6,854
  • 14
  • 53
  • 55