将日内数据加载到R中以使用quantmod处理它

Mst*_*nen 5 csv r quantmod yahoo-finance quantstrat

我需要修改这个示例代码,以便将它与日常数据一起使用,我应该从这里此处获取.据我所知,该示例中的代码适用于任何历史数据(或不是?),因此我的问题归结为以必要的格式(我的意思是每日或日内)加载初始数据的问题.

正如我也从这个问题的答案中理解的那样,不可能加载日内数据getSymbols().我试图将这些数据下载到我的硬盘驱动器中,然后使用一个read.csv()函数来获取它,但这种方法不能正常工作.最后,我在各种文章(例如这里)中找到了这个问题的解决方案,但是所有这些解决方案看起来都非常复杂和"人为".

所以,我的问题是如何从程序员的角度优雅而正确地将给定的日内数据加载到给定的代码中,而不重新发明轮子?

PS我对R和quantstrat中的时间序列分析很新,因此如果我的问题看起来很模糊,请告诉我你需要知道什么才能回答它.

Jos*_*ich 9

我不知道如何在没有"重新发明轮子"的情况下做到这一点,因为我不知道任何现有的解决方案.虽然使用自定义功能很容易.

intradataYahoo <- function(symbol, ...) {
  # ensure xts is available
  stopifnot(require(xts))
  # construct URL
  URL <- paste0("http://chartapi.finance.yahoo.com/instrument/1.0/",
    symbol, "/chartdata;type=quote;range=1d/csv")

  # read the metadata from the top of the file and put it into a usable list
  metadata <- readLines(paste(URL, collapse=""), 17)[-1L]
  # split into name/value pairs, set the names as the first element of the
  # result and the values as the remaining elements
  metadata <- strsplit(metadata, ":")
  names(metadata) <- sub("-","_",sapply(metadata, `[`, 1))
  metadata <- lapply(metadata, function(x) strsplit(x[-1L], ",")[[1]])
  # convert GMT offset to numeric
  metadata$gmtoffset <- as.numeric(metadata$gmtoffset)

  # read data into an xts object; timestamps are in GMT, so we don't set it
  # explicitly. I would set it explicitly, but timezones are provided in
  # an ambiguous format (e.g. "CST", "EST", etc).
  Data <- as.xts(read.zoo(paste(URL, collapse=""), sep=",", header=FALSE,
    skip=17, FUN=function(i) .POSIXct(as.numeric(i))))
  # set column names and metadata (as xts attributes)
  colnames(Data) <- metadata$values[-1L]
  xtsAttributes(Data) <- metadata[c("ticker","Company_Name",
    "Exchange_Name","unit","timezone","gmtoffset")]
  Data
}
Run Code Online (Sandbox Code Playgroud)

我会考虑在quantmod中添加这样的东西,但需要进行测试.我写了不到15分钟,所以我肯定会有一些问题.