2012-11-08 23 views
1

我想通过下载此页面上的所有CSV文件(http://cfe.cboe.com/Products/historicalVIX.aspx)获取VIX期货的历史价格。下面是我使用这样做代码:从CBOE下载VIX期货价格

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魔法可以解决这个问题?

谢谢。

回答

3

我在我的qmao程序包(程序包中的getSymbols函数)中有一个getSymbols.cfe方法,这将使这更容易。

#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为你建立它,这通常很快发生,但可能会占用几天。

+0

谢谢。我不需要重新发明轮子。 – mchangun

+0

感谢您指出VX_N13在第一行有免责声明。我会尽力修补,以尽快处理。 – GSee

+0

@GSee有没有像getQuote.cfe可用的东西。我环顾四周,无法找到它。我在问,因为使用getSmbols.cfe提供的数据有点晚了“请注意:CFE数据直到上午10:00左右C.T.在下一个工作日才可用。”问题在于何处获得(接近)实时数据。一个明显的地方是盈透证券......任何其他想法(谷歌,雅虎,...)?日Thnx。 – Samo