1

I am stuck with the following code.

For reference the code it is taken from the following website (http://gekkoquant.com/2013/01/21/statistical-arbitrage-trading-a-cointegrated-pair/), I am also compiling the code through 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

I am getting the following error.

Error in stockPair$a - stockPair$hedgeRatio * stockPair$b : 
      non-conformable arrays

The reason these particular series don't match is because "WPL.AX" has an extra value (date:19-05-2014 - the matrix lengths are different) compared to "BHP". How can I solve this issue when loading data?

I have also tested other stock pairs such as "ANZ","WBC" with the source = "google" which produces two of the same length arrays.

> length(stockPair$a)
[1] 360
> length(stockPair$b)
[1] 359
Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
NodeExplosion
  • 83
  • 1
  • 6

2 Answers2

2

Add code such as this prior to the stockPair computation, to trim each xts set to the intersection of dates:

common_dates <- as.Date(Reduce(intersect, eapply(symbolData, index)))
symbolData <- eapply(symbolData, `[`, i=common_dates)
Matthew Lundberg
  • 42,009
  • 6
  • 90
  • 112
1

Your code works fine if you don't convert your xts object to matrix via coredata. Then Ops.xts will ensure that only the rows with the same index will be subtracted. And fortune(106) applies.

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

Here's an alternative approach:

# 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
Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418