【问题标题】:Looping with quantmod使用 quantmod 循环
【发布时间】:2016-03-28 05:31:21
【问题描述】:

我是 R、循环和 quantmod 的新手。我试图说服 quantmod 跳过它无法处理的任何代码并继续下一个代码,而不是停止。我以为我在这里找到了答案how do I loop through all the stocks with quantmod and ttr?,但我无法让 Rime 的解决方案发挥作用:

如果循环中断,比如第 50 次迭代,那么只需通过更改以下内容重新运行最后一段代码

# Actual loop: 
# IF IT BREAKS ON THE 50th ITERATION, it must be skipped, therefore change it to 51
for(i in 51:length(symbols)) { 
  symbols[i]-> symbol
...

下面是我的原始代码,它只返回许多值中的 8 个(所以我假设 9 是问题点)。

library(gdata)
d = read.xls("~/Documents/TEST.xlsx", sheet = 1, stringsAsFactors=F)

library(quantmod)
sym <- as.character(d[,1])

results <- NULL

for (ii in sym){
  data1 <- getSymbols(Symbols = ii, 
                      src = "yahoo", 
                      from = Sys.Date() - 100, 
                      auto.assign = FALSE)
  de = head(data1,150)
  colnames(de) <- c("open","high","low","close","volume","adj.")
  overnightRtn <- (as.numeric(de[2:nrow(de),"open"])/as.numeric(de[1:(nrow(de)-1),"close"])) - 1

  results <- rbind(results,cbind(
    paste(round(min(overnightRtn,na.rm=T),5),"%",sep="")))

} 

colnames(results) <- c("overnightRtn2")
rownames(results) <- sym
View(results)

当我将for(ii in sym) 更改为for(ii in 9:length(sym)) 时出现错误:

找不到函数“getSymbols.9”

这里是d[,1]的开始:

[1] "ABX"    "ACC"    "ACCO"   "ACE"    "ACG"    "ACH"    "ACI"    "ACM"    "ACMP"   "ACN"

【问题讨论】:

    标签: r quantmod


    【解决方案1】:

    在 R 中循环时有一些错误的解决方法,其中一种方法是使用 tryCatch 函数,juba 显示了 here 如何做到这一点。我还确保只有当data1variable 被分配了某个值时,for 循环才会继续。

    将您的for loop 更改为以下代码,它应该可以满足您的要求。

    for (ii in sym){
      data1 <- NULL                               # NULL data1
      data1 <- tryCatch(getSymbols(Symbols = ii,  
                          src = "yahoo", 
                          from = Sys.Date() - 100, 
                          auto.assign = FALSE),
                        error=function(e){})      # empty function for error handling
      if(is.null(data1)) next()                   # if data1 is still NULL go to next ticker
      de = head(data1,150)
      colnames(de) <- c("open","high","low","close","volume","adj.")
      overnightRtn <- (as.numeric(de[2:nrow(de),"open"])/as.numeric(de[1:(nrow(de)-1),"close"])) - 1
    
      results <- rbind(results,cbind(
        paste(round(min(overnightRtn,na.rm=T),5),"%",sep="")))
    } 
    

    【讨论】:

    • 使用trytryCatch简单很多。
    • @JoshuaUlrich 当我只使用try 时它正在停止,可能我做错了什么。
    • data1 &lt;- try(getSymbols(...)); if(inherits(data1, "try-error")) next
    • 两种解决方案都有效,非常感谢! stop 按钮在运行时没有一直出现是否有原因?它断断续续地闪烁。还有@JoshuaUlrich(或者任何人,如果你知道的话),你能告诉我在哪里插入n &lt;- length(symbols); pb &lt;- txtProgressBar(min = 0, max = n, style=3); setTxtProgressBar(pb, i) 来获取状态栏吗?我现在插入它的地方,它在控制台窗口中给了我一个 0%,之后什么也没有。我在 Mac 上 - 也许这很重要?
    【解决方案2】:

    您可以试试tidyquant 包,它负责内部错误处理。它也不需要 for 循环,因此可以为您节省大量代码。 tq_get() 函数负责获取股票价格。您可以使用complete_cases 参数来调整错误的处理方式。

    complete_cases = TRUE 示例:自动删除“坏苹果”

    library(tidyquant)
    
    # get data with complete_cases = TRUE automatically removes bad apples
    c("AAPL", "GOOG", "BAD APPLE", "NFLX") %>%
        tq_get(get = "stock.prices", complete_cases = TRUE)
    
    #> Warning in value[[3L]](cond): Error at BAD APPLE during call to get =
    #> 'stock.prices'. Removing BAD APPLE.
    #> # A tibble: 7,680 × 8
    #>    symbol       date  open  high   low close    volume adjusted
    #>     <chr>     <date> <dbl> <dbl> <dbl> <dbl>     <dbl>    <dbl>
    #> 1    AAPL 2007-01-03 86.29 86.58 81.90 83.80 309579900 10.85709
    #> 2    AAPL 2007-01-04 84.05 85.95 83.82 85.66 211815100 11.09807
    #> 3    AAPL 2007-01-05 85.77 86.20 84.40 85.05 208685400 11.01904
    #> 4    AAPL 2007-01-08 85.96 86.53 85.28 85.47 199276700 11.07345
    #> 5    AAPL 2007-01-09 86.45 92.98 85.15 92.57 837324600 11.99333
    #> 6    AAPL 2007-01-10 94.75 97.80 93.45 97.00 738220000 12.56728
    #> 7    AAPL 2007-01-11 95.94 96.78 95.10 95.80 360063200 12.41180
    #> 8    AAPL 2007-01-12 94.59 95.06 93.23 94.62 328172600 12.25892
    #> 9    AAPL 2007-01-16 95.68 97.25 95.45 97.10 311019100 12.58023
    #> 10   AAPL 2007-01-17 97.56 97.60 94.82 94.95 411565000 12.30168
    #> # ... with 7,670 more rows
    

    complete_cases = FALSE 示例:返回嵌套数据框。


    library(tidyquant)
    
    # get data with complete_cases = FALSE returns a nested data frame
    c("AAPL", "GOOG", "BAD APPLE", "NFLX") %>%
        tq_get(get = "stock.prices", complete_cases = FALSE)
    
    #> Warning in value[[3L]](cond): Error at BAD APPLE during call to get =
    #> 'stock.prices'.
    #> Warning in value[[3L]](cond): Returning as nested data frame.
    #> # A tibble: 4 × 2
    #>      symbol         stock.prices
    #>       <chr>               <list>
    #> 1      AAPL <tibble [2,560 × 7]>
    #> 2      GOOG <tibble [2,560 × 7]>
    #> 3 BAD APPLE            <lgl [1]>
    #> 4      NFLX <tibble [2,560 × 7]>
    

    在这两种情况下,用户都会收到警告消息。谨慎的用户会阅读它们并尝试确定问题所在。最重要的是,长时间运行的脚本不会失败。

    【讨论】:

    • 我尝试多次安装 tidyquant,但总是出错。是否存在经过 tidyquant 验证始终有效的 R 发行版(适用于 Mac)?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-16
    • 1970-01-01
    • 1970-01-01
    • 2019-02-15
    • 1970-01-01
    相关资源
    最近更新 更多