【问题标题】:Filter xts objects by common dates按常见日期过滤 xts 对象
【发布时间】:2014-07-25 22:24:33
【问题描述】:

我被以下代码卡住了。

为了参考它取自以下网站(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

这些特定系列不匹配的原因是,与“BHP”相比,“WPL.AX”具有额外的值(日期:19-05-2014 - 矩阵长度不同)。加载数据时如何解决这个问题?

我还测试了其他股票对,例如 "ANZ","WBC" 与 source = "google" 生成两个相同长度的数组。

> length(stockPair$a)
[1] 360
> length(stockPair$b)
[1] 359

【问题讨论】:

  • 你需要找出尺寸不同的原因,而不是试图强迫它们相同。
  • @MatthewLundberg 抱歉让我重新表述一下自己,这些特定系列不匹配的原因是因为“WPL.AX”与“相比”具有额外的价值(日期:19-05-2014)必和必拓”。加载数据时如何解决这个问题?
  • 请在问题中说明这一点,而不是“我将如何强制 R 符合两个数组。”
  • @MatthewLundberg 我已经适当地更新了我的问题

标签: r time-series xts quantmod


【解决方案1】:

stockPair 计算之前添加这样的代码,将每个xts 设置为日期的交集:

common_dates <- as.Date(Reduce(intersect, eapply(symbolData, index)))
symbolData <- eapply(symbolData, `[`, i=common_dates)

【讨论】:

  • 请注意,[ 忽略参数名称,仅使用位置匹配,因此 i=common_dates 中的 i= 无关紧要。
【解决方案2】:

如果您不通过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

【讨论】:

    猜你喜欢
    • 2011-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-04
    • 2013-11-04
    • 1970-01-01
    • 2018-06-13
    • 2010-12-30
    相关资源
    最近更新 更多