Search code examples
rxtsquantmod

Calculate Returns of xts object with multiple columns


What is the most straight forward way to calculate the returns of an (n x m) xts object?

When I feed an (n x m) xts object mxts into the quantmod function dailyReturn, the return value is an (n x 1) vector, representing the returns of the first column. What I am looking for is a way to generate an (n x m) xts object containing the respective return vector for each column of mxts.

I have tried to work with some of the apply functions, such as

lapply(mxts,dailyReturn)

but the returns always had the wrong type and lost their labeling (dailyReturn changes the value of the colnames vector to "daily.returns").

Is there an easy, non-hacky way to achieve this? Am I maybe using a wrong function for this problem?


Solution

  • The ROC function in the TTR package will do this, but you can easily do the calculation yourself using lag (which is what ROC does internally).

    R> require(quantmod)  # loads TTR
    R> getSymbols("SPY")
    R> head(ROC(OHLC(SPY)))
                    SPY.Open      SPY.High       SPY.Low     SPY.Close
    2007-01-03            NA            NA            NA            NA
    2007-01-04 -0.0071963059 -5.686021e-03  0.0002845153  0.0021198425
    2007-01-05  0.0007078143 -4.586355e-03 -0.0016370693 -0.0080082636
    2007-01-08 -0.0036151023  7.071886e-05 -0.0009264869  0.0046143553
    2007-01-09  0.0034735795  1.342709e-03  0.0010689472 -0.0008502799
    2007-01-10 -0.0051793368 -2.118869e-04 -0.0007125045  0.0033261416