2016-12-04 176 views
0

我有一個我想要遍歷的股票代碼的列表,並獲取歷史調整後的收盤價格。之後我會將輸出綁定在一起。但是,如果因爲其中一個代碼錯誤而發現錯誤,我想要(i)跳過並抓取下一個代碼或(ii)將代碼錯誤捕獲。下面是一些玩具代碼:Quantmod錯誤處理錯誤代碼

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不是真正的行情,但奇怪的是,沒有錯誤踢了。事實上,這是我得到的頭(價格)

   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列。

我試過使用try()和tryCatch()都無濟於事。

回答

2

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 
+0

非常好!這工作完美。謝謝@黃偉煌 – huesecon