如何在tryCatch中包装quantmod的getSymbols()

时间:2014-12-01 19:47:27

标签: r quantmod

我使用了该网站上其中一个主题的示例代码创建了一个小程序,该程序使用来自quantmod包的getSymbols从yahoo下载库存数据。但是,当我修改代码以添加tryCatch时(我以两种不同的方式执行此操作),它不会返回任何数据。我希望我没有提供太多细节,但希望确保我提供所有信息。

这是工作代码(后面跟着不返回任何数据的非工作代码):

###################### Working code################
library(quantmod)
library(plyr)
library(PerformanceAnalytics)

#Data structure that contains stock quote objects
stockData <- new.env()
#Assign dates to set range for stock quotes
sDate <- as.Date("2012-09-04")
eDate <- as.Date("2014-09-02")

#Assign a vector of ticker symbols
symbols <- c("BIL","VGSH","VGIT","VGLT","BND","VOO","VTI","VT")

# download data
l_ply(symbols, function(sym) try(getSymbols(sym,env = stockData,src = "yahoo", 
                                            from = sDate, to = eDate))) 
# Now extract the data from the environment and store in a list.
symbols <- symbols[symbols %in% ls(envir = stockData)]

# sym.list 
sym.list = llply(symbols, ge

t,stockData)
names(sym.list) <- symbols

以下两种情况不会返回任何数据:

  1. 创建一个名为getYahooTickerData的函数来调用 getSymbols内的tryCatch。这不会返回任何数据。

  2. 假设在函数之间传递环境存在问题,我将上述工作代码中的try替换为tryCatch而不是try,但它仍然没有&#39工作。

  3. 首先,案例1:

    ###################################Case 1################################
    library(quantmod)
    library(plyr)
    library(PerformanceAnalytics)
    
    #Data structure that contains stock quote objects
    stockData <- new.env()
    #Assign dates to set range for stock quotes
    sDate <- as.Date("2012-09-04")
    eDate <- as.Date("2014-09-02")
    
    #Assign a vector of ticker symbols
    symbols <- c("BIL","VGSH","VGIT","VGLT","BND","VOO","VTI","VT")
    
    getYahooTickerData <- function(ticker,startDate,endDate,envmt) {
        tryCatch(
            getSymbols(
                  Symbols=ticker, 
                  env = envmt, 
                  from = startDate, 
                  to = endDate,
                  src = "yahoo",
             ),
             error=function(error_message) {
                  message("error getting data")
                  message(ticker)
             }, 
             warning=function(warning_message) {
                  message("there was a warning for ticker ")
                  message(ticker)
             }
        )
    }# end of function getYahooTickerData
    
    l_ply(symbols, function(sym) getYahooTickerData(sym,sDate,eDate,envmt=stockData))
    
    # Now extract the data from the environment and store in a list.
    symbols <- symbols[symbols %in% ls(envir = stockData)]
    
    # sym.list 
    sym.list = llply(symbols, get,stockData)
    names(sym.list) <- symbols
    

    在这种情况下,sym.list为空。现在案例2:

    ################Case 2###################################
    library(quantmod)
    library(plyr)
    library(PerformanceAnalytics)
    
    #Data structure that contains stock quote objects
    stockData <- new.env()
    #Assign dates to set range for stock quotes
    sDate <- as.Date("2012-09-04")
    eDate <- as.Date("2014-09-02")
    
    #Assign a vector of ticker symbols
    symbols <- c("BIL","VGSH","VGIT","VGLT","BND","VOO","VTI","VT")
    
    # download data
    l_ply(symbols, function(sym) {
        tryCatch(
            getSymbols(sym,env = stockData,
                       src = "yahoo",
                       from = sDate,
                       to = eDate),
            error=function(error_message) {
                 message("error getting data for symbol")
                 message(sym)
            }, 
            warning=function(warning_message) {
                 message("warning for symbol")
                 message(sym)
            }
        )
    })
    # Now extract the data from the environment and store in a list.
    symbols <- symbols[symbols %in% ls(envir = stockData)]
    
    # sym.list 
    sym.list = llply(symbols, get,stockData)
    names(sym.list) <- symbols
    

    在这种情况下,sym.list也是空的。

2 个答案:

答案 0 :(得分:0)

对于错误,您需要在发生错误时包含所需的返回值。对于警告,您实际上没有捕获错误,但使用条件处理程序。所以一个相对完整的例子是

withCallingHandlers({
    tryCatch({
        warning("a warning")
        stop("an error")
    }, error=function(e) {
        ## catch the error
        message(conditionMessage(e))
        ## signal with appropriate return value
        NA
    })
}, warning=function(w) {
    ## handle the warning...
    message(conditionMessage(w))
    ## then continue from where the warning occurred
    invokeRestart("muffleWarning")
})

导致输出

a warning
an error
[1] NA

答案 1 :(得分:0)

我想我已经弄清楚为什么tryCatch没有使用getSymbols()。 getSymbols()始终发出警告(即使选择了warnings = FALSE选项),以及始终调用警告功能的原因。我从tryCatch中删除了警告块,代码工作正常。 由于代码在我从tryCatch中删除警告块时起作用,我假设这是正确的原因。