Alan Vazquez
Alan Vazquez

Reputation: 11

Function for create a cumulative index of returns

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.

Upvotes: 1

Views: 483

Answers (1)

akrun
akrun

Reputation: 887158

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)

Upvotes: 1

Related Questions