My problem is similar to the one in this question: how do I loop through all the stocks with quantmod and ttr?

To estimate the covariance matrix of stock returns, I need a $NxT$ matrix $X$ of returns ($N$ stocks $T$ observations). So using the link above, I have the following code:


symbols <- stockSymbols(c("AMEX", "NYSE")) 
symbols <- symbols[,1]

dataset <- xts()

for(i in 1:length(symbols)){   
  symbol <- symbols[i]   
  tryit <- try(getSymbols(symbol,from = "1990-01-01", to = "2010-01-01"))   
  if(inherits(tryit, "try-error")){
    i <- i+1   }
  getSymbols(symbol, from = "1990-01-01", to = "2010-01-01")   
  retx <- Ad(get(symbol)) %>%
    dailyReturn(type = "log")   
  colnames(retx) <- as.character(symbol)   
  dataset <- merge(dataset, retx)
  } }

However, for some reason and it appears in the link above as well, the for loop above breaks after 50 or 100 iterations. A solution is described and it consists of running again the loop starting where it breaks, but I'm wondering why it breaks at all since it runs fine in the beginning.

I have a second question, the last line


doesn't actually remove the xts data for the symbol from the database. Instead, it deletes the temporary character variable. Instead, I wish to delete the xts element from my environment. I tried using


but this doesn't work either and throws an error at the first iteration.

Thank you for the help!

  • $\begingroup$ When the loop breaks, it just stop without throwing an error $\endgroup$
    – Olivier
    Commented May 12, 2018 at 10:24
  • $\begingroup$ Did the answer of @Rime help you? Then it would be great if you could accept it. $\endgroup$
    – vonjd
    Commented Jun 12, 2018 at 6:24

1 Answer 1


try using

stock<- lapply(as.list(tickers), function(x) {
tmp <- try(getSymbols(x, from="1990-01-01",   auto.assign= FALSE))
if(!inherits(tmp, 'try-error'))

stock will return all OHLCV for available stocks as a list. You can possibly use do.call to merge all Adjusted closes and then calculate returns.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.