[英]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.