使用quantmod在循环中查找不同时间段的代码

时间:2016-01-19 00:55:39

标签: r quantmod

当每个自动收报机的时间段相同时,我能够循环并计算过夜/周末返回的代码清单,但是当我想要查找时间段时遇到麻烦每个股票代码都不同。

例如,使用:

symbols <- c("AAPL", "GOOG"," MSFT")
dates <- as.Date(c("2015-01-04", "2015-01-05", "2015-01-06"))
example.df <- data.frame(tickers, dates)
example.df
  tickers dates
1    AAPL 2015-01-04
2    GOOG 2015-01-05
3    MSFT 2015-01-06

我希望2015-01-04和2015-01-05之间的AAPL过夜回报,在2015-01-05和2015-01-06等之间,如果是星期五,我想要下周一。

我可以通过查找每个单独的代码来获得我想要的东西:

library(quantmod)
library(dplyr)
# date range accounts for weekends
getSymbols("AAPL", from = "2016-01-04", to = "2016-01-08")
data <- as.data.frame(AAPL)
colnames(data) <- c("open","high","low","close","volume","adj.")
# overnight return calculation
data$overnight.return <- data$open / lag(data$close, default = 0) - 1
data$overnight.return <- paste(round(data$overnight.return * 100, 3), "%",sep= "") 
# the overnight/over-weekend returns for the specified date
data.df.final <- slice(data, 2)

当然,这非常慢。 至于我能够尝试从中做出循环:

# needs to be a loop itself and inside the other 'for' loop somehow I think
symbol.list <- example.df[,1]
start <-  data[,2]
end <- data[,2] + days(3) 

results <- NULL
for (i in symbol.list) {
  data <- getSymbols(Symbols = i, 
                     src = "yahoo", 
                     from = start, to = end, 
                     auto.assign = FALSE)
  if (inherits(data, 'try-error')) next
  colnames(data) <- c("open","high","low","close","volume","adj.")
  data <- as.data.frame(data)
  data <- cbind(date = rownames(data), data)
  data$overnightRtn <- as.vector(data$open / lag(data$close, default = 0) - 1)
  data$overnightRtn <- paste(round(data$overnightRtn * 100, 3), "%") 
  data <- slice(data, 2)
  results <- bind_rows(results, data)
  }

如何将日期循环方面添加到上面的股票代码循环中?

1 个答案:

答案 0 :(得分:2)

也许这就是你要找的东西。看到我使用的是索引,而不是实际的列表,所以我可以参考数据框的每个元素(它没有被优化,但是它正在完成你在函数中描述的工作):

symbols <- c("AAPL", "GOOG"," MSFT")              ## " MSFT" has an extra space
dates <- as.Date(c("2015-01-04", "2015-01-05", "2015-01-06"))
example.df <- data.frame(tickers=symbols, dates)  ## there was an error here in your example.

symbol.list <- trimws(example.df[,1])
start <-  as.Date(example.df[,2])
end <- as.Date(example.df[,2]) + days(3) 

results <- NULL
for (i in 1:NROW(symbol.list)) {
  try(dataX <- getSymbols(Symbols = symbol.list[i], 
                     src = "yahoo", 
                     from = start[i], to = end[i], 
                     auto.assign = FALSE),silent=T)
  if (!exists("dataX")) {cat("Error in ",i,"\n");next}
  colnames(dataX) <- c("open","high","low","close","volume","adj.")
  dataX <- as.data.frame(dataX)
  dataX <- cbind(date = rownames(dataX), dataX)
  dataX$overnightRtn <- as.vector(dataX$open / lag(dataX$close, default = 0) - 1)
  dataX$overnightRtn <- paste(round(dataX$overnightRtn * 100, 3), "%") 
  data2 <- slice(dataX, 2);rm(dataX)
  results <- if (is.null(results)) data2 else rbind(results, data2)
}