Question

I want basically to calculate a cumulative return (and an Index value) for a xts time series for which I have a return for each period. But since I'm looking at defined periods to compare these time series I want the cumulative return and Index value from the beginning of this period to the end and the current cumulative return in each row.

Lets say my data is something like this (and the base index value is 100):

      Return  Index  Cumulative Return
Date0   0     100         0  
Date1  0.05   105        0.05
Date2  0.10   115.5      0.155           
Date3  -0.1   103.95     0.0395

How can I achieve that in R?

Was it helpful?

Solution

# First create an xts object similar to the one you describe
x <- .xts(c(100,105,115.5,103.95), 1:4, dimnames=list(NULL, "Index"), tzone="UTC")
x$Return <- c(0, ROC(x$Index, type="discrete", na.pad=FALSE))

The cumulative arithmetic return at any time is just the product of 1 plus the returns (minus 1). cumprod will calculate the cumulative product for you.

x$CumulativeReturn <- cumprod(1 + x$Return) - 1
#                     Index Return CumulativeReturn
#1970-01-01 00:00:01 100.00   0.00           0.0000
#1970-01-01 00:00:02 105.00   0.05           0.0500
#1970-01-01 00:00:03 115.50   0.10           0.1550
#1970-01-01 00:00:04 103.95  -0.10           0.0395

If you were working with log returns, you could simply do cumsum(x$Return)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top