1

Im trying to code a function to calculate the cumulative index returns where calculations would be current observation / first observation in an xts object. Here's a sample of my code:

    cumret <- function(x){
      cum <- rep(0,nrow(x))
      for (i in 1:nrow(x)) {
        cum[i,] <-x[i,]/x[1,]
      }
      cumret <- cum
      return(cumret)
    }

Then when a tried it, shows this error: "incorrect number of subscripts on matrix"

As input data, I used e.g.

Prices <- c(23,23.5,24,24.3,24.6,25) 

I want to create a vector of cumulative returns, Cum.Ret <- Price[i,] / as.numeric(Prices[1,])

Hope you can help me, thanks in advance.

B--rian
  • 5,578
  • 10
  • 38
  • 89
  • Can you show a small reproducible example and expecteed output – akrun Aug 23 '19 at 14:55
  • Of course: For example the normalize returns of the sp500 during a time window would begin with 1 and end with the total cumulative return. Expected output would be a time series of these cumulative returns. – Alan Vazquez Aug 23 '19 at 15:04
  • According to `R` tag, the minimal reproducible example expected is [here](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – akrun Aug 23 '19 at 15:09
  • Do you need `cumsum(Prices/Prices[1])` – akrun Aug 23 '19 at 15:19
  • Here is: Prices <- c(23,23.5,24,24.3,24.6,25) I want to create a vector of cmulative Returns: Cum.Ret <- Price[i,] / as.numeric(Prices[1,]) – Alan Vazquez Aug 23 '19 at 15:20
  • 1
    Comments are not ideal for pasting examples. Please edit your original question. – Roman Luštrik Aug 24 '19 at 07:01

1 Answers1

1

An option is to divide by the first element and then take the cumsum

cumsum(Prices/Prices[1])

data

Prices <- c(23,23.5,24,24.3,24.6,25)
akrun
  • 874,273
  • 37
  • 540
  • 662
  • The problem is that this will no returns a time series of cumulative returns, only total return. Let me be more suscint, I try to reproduce a time series for the value of 1 $dollar for a given set of prices. – Alan Vazquez Aug 23 '19 at 15:28
  • @AlanVazquez Not clear from the comments. You provided an example and I try to use that example to create the expected – akrun Aug 23 '19 at 15:49