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

Looking up tickers for different time periods in a loop with quantmod

当每个代码的时间段相同时,我能够循环并计算代码列表的 overnight/over-weekend returns,但是当时间段我想查找每个自动收报机的不同之处。

例如:

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

我想要 AAPL 在 2015-01-04 和 2015-01-05 之间过夜 return,在 2015-01-05 和 2015-01-06 之间为 GOOG 等。如果它是星期五,我想下个星期一。

我可以通过像这样查找每个单独的自动收报机来获得我正在寻找的东西:

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)
  }

如何将日期循环添加到上述代码循环中?

也许这就是您要找的。请注意,我使用的是索引,而不是实际列表,因此我可以引用数据框的每个元素(它没有优化,但它正在执行您在函数中描述的工作):

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)
}