问题描述
我有一个股票行情列表,我想遍历它并获取历史调整后收盘价.之后我会将输出绑定在一起.但是,如果发现错误是因为其中一个代码不正确,我想 (i) 跳过并获取下一个代码或 (ii) 将该代码捕获为错误.这是一些玩具代码:
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))
显然,FANTASTICALLYCOOL 和 LUCKYDEVIL 不是真正的股票代码,但奇怪的是,没有出现错误.事实上,这就是我得到的人头(价格)
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 和 LUCKYDEVIL 将采用前面代码的值.我要么希望 R 跳过自动收报机,要么输入一列充满 NA 的内容.
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.
我试过同时使用 try() 和 tryCatch() 都无济于事.
I've tried using both try() and tryCatch() to no avail.
推荐答案
getSymbols
应该抛出错误.试试
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
这篇关于Quantmod 错误处理不正确的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!