循环使用quantmod

时间:2015-12-22 02:27:22

标签: r quantmod

我是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"

2 个答案:

答案 0 :(得分:1)

在R中循环时有一些错误的解决方法,一种方法是使用tryCatch函数,juba显示here如何执行此操作。我还确保for循环只会在data1变量赋值时继续。

为以下代码更改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="")))
} 

答案 1 :(得分:0)

您可以尝试在内部处理错误处理的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]>

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