【问题标题】:Loading intraday data into R for handling it with quantmod将日内数据加载到 R 中以使用 quantmod 处理它
【发布时间】:2015-01-17 14:09:18
【问题描述】:

我需要修改this example code 以将其与我应该从herehere 获得的盘中数据一起使用。据我了解,该示例中的代码适用于任何历史数据(或不适用?),所以我的问题归结为以必要的格式(我的意思是每天或当日)加载初始数据的问题。

我也从this question 的回答中了解到,使用getSymbols() 加载日内数据是不可能的。我尝试将这些数据下载到我的硬盘驱动器中,然后使用read.csv() 函数获取它,但这种方法效果不佳。最后,我在各种文章(例如here)中发现了这个问题的一些解决方案,但它们似乎都非常复杂和“人为”。

那么,我的问题是如何从程序员的角度优雅而正确地将给定的盘中数据加载到给定的代码中,而无需重新发明轮子?

附:我对 R 和 quantstrat 中的时间序列分析非常陌生,因此如果我的问题似乎晦涩难懂,请告诉我你需要知道什么才能回答它。

【问题讨论】:

    标签: r csv quantmod yahoo-finance quantstrat


    【解决方案1】:

    如果不“重新发明轮子”,我不知道如何做到这一点,因为我不知道任何现有的解决方案。不过,使用自定义函数很容易做到。

    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
    }
    

    我会考虑在 quantmod 中添加类似的内容,但需要对其进行测试。我用了不到 15 分钟的时间写了这篇文章,所以我敢肯定会有一些问题。

    【讨论】:

    • 感谢 Joshua 提供附加代码。正如我所提到的,我对这一切都很陌生,R 编程与我之前所做的一切略有不同。因此,我不确定是否存在任何开箱即用的解决方案并决定询问,因为我认为它必须存在。不管怎样,你的代码将帮助我进一步探索 R 和 quantmod 的能力,即使我有一些问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    相关资源
    最近更新 更多