# Collect all stock returns in one single matrix using quantmod in R

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:

library(quantmod)

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   }
else{
getSymbols(symbol, from = "1990-01-01", to = "2010-01-01")
dailyReturn(type = "log")
colnames(retx) <- as.character(symbol)
dataset <- merge(dataset, retx)
rm(symbol)
} }


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

rm(symbol)


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

rm(get(symbol))


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

Thank you for the help!

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

stock<- lapply(as.list(tickers), function(x) {

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.