我坚持使用以下代码。
作为参考,它是从以下网站(http://gekkoquant.com/2013/01/21/statistical-arbitrage-trading-a-cointegrated-pair/)获取的代码,我也是通过R Studio编译代码。
library("quantmod")
startDate = as.Date("2013-01-01")
symbolLst<-c("WPL.AX","BHP.AX")
symbolData <- new.env()
getSymbols(symbolLst, env = symbolData, src = "yahoo", from = startDate)
stockPair <- list(
a =coredata(Cl(eval(parse(text=paste("symbolData$\"",symbolLst[1],"\"",sep="")))))
,b = coredata(Cl(eval(parse(text=paste("symbolData$\"",symbolLst[2],"\"",sep="")))))
,hedgeRatio = 0.70 ,name=title)
spread <- stockPair$a - stockPair$hedgeRatio*stockPair$b
我收到以下错误。
Error in stockPair$a - stockPair$hedgeRatio * stockPair$b :
non-conformable arrays
这些特定系列不匹配的原因是因为“WPL.AX”与“BHP”相比具有额外值(日期:19-05-2014-矩阵长度不同)。如何在加载数据时解决此问题?
我还测试了其他股票对,例如“ANZ”,“WBC”和source =“google”,它产生两个相同长度的数组。
> length(stockPair$a)
[1] 360
> length(stockPair$b)
[1] 359
答案 0 :(得分:2)
在stockPair
计算之前添加此类代码,将每个xts
集修剪为日期的交集:
common_dates <- as.Date(Reduce(intersect, eapply(symbolData, index)))
symbolData <- eapply(symbolData, `[`, i=common_dates)
答案 1 :(得分:1)
如果您不通过coredata
将xts对象转换为矩阵,则代码可以正常工作。然后Ops.xts
将确保仅减去具有相同索引的行。 fortune(106)
适用。
fortunes::fortune(106)
# If the answer is parse() you should usually rethink the question.
# -- Thomas Lumley
# R-help (February 2005)
stockPair <- list(
a = Cl(symbolData[[symbolLst[1]]])
,b = Cl(symbolData[[symbolLst[2]]])
,hedgeRatio = 0.70
,name = "title")
spread <- stockPair$a - stockPair$hedgeRatio*stockPair$b
这是另一种方法:
# merge stocks into a single xts object
stockPair <- do.call(merge, eapply(symbolData, Cl))
# ensure stockPair columns are in the same order as symbolLst, since
# eapply may loop over the environment in an order you don't expect
stockPair <- stockPair[,pmatch(symbolLst, colnames(stockPair))]
colnames(stockPair) <- c("a","b")
# add hedgeRatio and name as xts attributes
xtsAttributes(stockPair) <- list(hedgeRatio=0.7, name="title")
spread <- stockPair$a - attr(stockPair,'hedgeRatio')*stockPair$b