Search code examples
rquantmod

Quantmod Error Handling Incorrect Tickers


I have a list of stock tickers I want to iterate through and grab the historical Adjusted Close prices. Afterward I'll bind the output together. However, if an error is found because one of the tickers is incorrect, I want to either (i) skip and grab the next ticker or (ii) capture that ticker as an error. Here is some toy code:

require(quantmod)

symbols <- c("KO","FANATASTICALLYCOOL","MSFT","LUCKYDEVIL","LMT")
getSymbols(symbols, from="1990-01-01")
prices <- list()
for(i in 1:length(symbols)) {
    prices[[i]] <- try(Ad(get(symbols[i])))
}

prices <- do.call(cbind, prices)
colnames(prices) <- gsub("\\.[A-z]*", "", colnames(prices))

Clearly, FANTASTICALLYCOOL and LUCKYDEVIL are not real tickers, but strangely enough, no error kicks up. In fact, this is what I get for head(prices)

              KO   FANATASTICALLYCOOL     MSFT       LUCKYDEVIL   LMT
1990-01-02 2.737389    2.737389          0.418482   0.418482    5.970848  
1990-01-03 2.697907    2.697907          0.420840   0.420840    5.934217
1990-01-04 2.684747    2.684747          0.433218   0.433218    5.915902
1990-01-05 2.662812    2.662812          0.422608   0.422608    6.080741
1990-01-08 2.719841    2.719841          0.429092   0.429092    6.025795
1990-01-09 2.697907    2.697907          0.427913   0.427913    5.989164

FANTASTICALLYCOOL and LUCKYDEVIL are taking on the values of the preceding ticker. I'd either like R to skip the ticker or input a column full of NA's.

I've tried using both try() and tryCatch() to no avail.


Solution

  • getSymbols should throw the error. Try

    symbols <- c("KO","FANATASTICALLYCOOL","MSFT","LUCKYDEVIL","LMT")
    out <- sapply(symbols, function(s) tryCatch({
      getSymbols(s , env = NULL)
      }, error = function(e) NA)
    )
    
    dd <- lapply(out, function(x) if (any(is.na(x))) NA else Ad(x))
    dd <- do.call(cbind, dd)
    #            KO.Adjusted FANATASTICALLYCOOL MSFT.Adjusted LUCKYDEVIL LMT.Adjusted
    # 2007-01-03    18.03268                 NA      23.47842         NA     66.64122
    # 2007-01-04    18.04010                 NA      23.43910         NA     66.46724
    # 2007-01-05    17.91389                 NA      23.30543         NA     66.70646
    # 2007-01-08    18.02896                 NA      23.53346         NA     67.91707
    # 2007-01-09    18.04381                 NA      23.55704         NA     67.85182
    # 2007-01-10    18.06979                 NA      23.32116         NA     68.56224