![](/img/trans.png)
[英]Problems plotting intraday OHLC data in R with quantmod chartSeries
[英]Loading intraday data into R for handling it with quantmod
我需要修改这个示例代码,以便将它与我应该从这里和从这里获取的日内数据一起使用。 据我了解,该示例中的代码适用于任何历史数据(或不适用于任何历史数据?),因此我的问题归结为以必要格式(我的意思是每天或日内)加载初始数据的问题。
正如我从这个问题的答案中也了解到,使用getSymbols()
加载日内数据是不可能的。 我尝试将该数据下载到我的硬盘驱动器中,然后使用read.csv()
函数获取它,但是这种方法并没有奏效。 最后,我在各种文章(例如这里)中找到了几个解决这个问题的方法,但它们似乎都非常复杂和“人为”。
所以,我的问题是如何从程序员的角度优雅而正确地将给定的日内数据加载到给定的代码中,而无需重新发明轮子?
PS 我对 R 和 quantstrat 中的时间序列分析非常陌生,因此如果我的问题似乎很模糊,请告诉我您需要知道什么才能回答它。
我不知道如何在不“重新发明轮子”的情况下做到这一点,因为我不知道任何现有的解决方案。 不过,使用自定义函数很容易做到。
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 分钟内写了这篇文章,所以我肯定会有一些问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.