I am downloading some information from yahoo finance using quantmod wrapped in an lapply statement:
require(quantmod)
tickers <- c("AAPL", "MSFT", "MKQ", "TSLA")
quotes <- lapply(tickers,function(x) getSymbols(x, src="yahoo", from="2015-02-01", auto.assign=FALSE))
The ticker MKQ is made up intentionally. I would like the loop to print the error but still create a list of xts objects with the requested data for the other 3 tickers.
I have tried to use tryCatch as follows but was unsuccessful:
quotes <- tryCatch(lapply(tickers,function(x) getSymbols(x,
src="yahoo", from="2015-02-01", auto.assign=FALSE)) , error=function(e) NULL)
Any suggestions on how to do this? I read the documentation on tryCatch but was not able to make sense of it.
Thank you.
You need to put the try
block inside your function:
quotes <- lapply(tickers, function(x) try(getSymbols(x, ...)))
Note we use the simpler try
here. If there is an error, your quotes
object will contain an object of try-error
class at location of element that caused the error.