我正在尝试通过下载此页面上的所有 CSV 文件 (http://cfe.cboe.com/Products/historicalVIX.aspx) 来获取 VIX future 的历史价格。这是我用来执行此操作的代码:
library(XML)
#Extract all links for url
url <- "http://cfe.cboe.com/Products/historicalVIX.aspx"
doc <- htmlParse(url)
links <- xpathSApply(doc, "//a/@href")
free(doc)
#Filter out URLs ending with csv and complete the link.
links <- links[substr(links, nchar(links) - 2, nchar(links)) == "csv"]
links <- paste("http://cfe.cboe.com", links, sep="")
#Peform read.csv on each url in links, skipping the first two URLs as they are not relevant.
c <- lapply(links[-(1:2)], read.csv, header = TRUE)
我收到错误:
Error in read.table(file = file, header = header, sep = sep, quote = quote, :
more columns than column names
经过进一步调查,我意识到这是因为某些 CSV 文件的格式不同。如果我手动加载 URL links[9]
,我会看到第一行有此免责声明:
CFE data is compiled for the .......use of CFE data is subject to the Terms and Conditions of CBOE's Websites.
大多数其他文件(例如links[8]
和links[10]
)都很好,所以看起来这是随机插入的。有没有一些 R 魔法可以解决这个问题?
谢谢。
最佳答案
我的 qmao 有一个 getSymbols.cfe
方法包(对于 getSymbols
包中的 quantmod 函数),这将使这变得更加容易。
#install.packages('qmao', repos='http://r-forge.r-project.org')
library(qmao)
这来自 ?getSymbols.cfe
的示例部分(请阅读帮助页面,因为该函数有一些您可能希望与默认值不同的参数)
getSymbols(c("VX_U11", "VX_V11"),src='cfe')
#all contracts expiring in 2010 and 2011.
getSymbols("VX",Months=1:12,Years=2010:2011,src='cfe')
#getSymbols("VX",Months=1:12,Years=10:11,src='cfe') #same
这不仅仅是 VIX 的问题
getSymbols(c("VM","GV"),src='cfe') #The mini-VIX and Gold vol contracts expiring this month
如果您不熟悉 getSymbols
,默认情况下它会将数据存储在 .GlobalEnv
中,并返回已保存对象的名称。
> getSymbols("VX_Z12", src='cfe')
[1] "VX_Z12"
> tail(VX_Z12)
VX_Z12.Open VX_Z12.High VX_Z12.Low VX_Z12.Close VX_Z12.Settle VX_Z12.Change VX_Z12.Volume VX_Z12.EFP VX_Z12.OpInt
2012-10-26 19.20 19.35 18.62 18.87 18.9 0.0 22043 15 71114
2012-10-31 18.55 19.50 18.51 19.46 19.5 0.6 46405 319 89674
2012-11-01 19.35 19.35 17.75 17.87 17.9 -1.6 40609 2046 95720
2012-11-02 17.90 18.65 17.55 18.57 18.6 0.7 42592 1155 100691
2012-11-05 18.60 20.15 18.43 18.86 18.9 0.3 28136 110 102746
2012-11-06 18.70 18.85 17.75 18.06 18.1 -0.8 35599 851 110638
编辑
我现在发现我没有回答你的问题,而是向你指出了另一种方法来得到同样的错误!让代码正常工作的一个简单方法是为 read.csv
制作一个包装器,使用 readLines
来查看第一行是否包含免责声明;如果是,则跳过第一行,否则正常使用 read.csv
。
myRead.csv <- function(x, ...) {
if (grepl("Terms and Conditions", readLines(x, 1))) { #is the first row the disclaimer?
read.csv(x, skip=1, ...)
} else read.csv(x, ...)
}
L <- lapply(links[-(1:2)], myRead.csv, header = TRUE)
我还将该补丁应用于 getSymbols.cfe
。您可以使用 svn checkout 获取最新版本的 qmao (1.3.11)(如果您需要帮助,请参阅 this post),或者,您可以等待 R-Forge 为您构建它,这通常会很快发生,但也可以最多需要几天时间。
关于r - 从 CBOE 下载 VIX future 价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13282094/