I am trying to find the cumulative return of the following 4 vectors using the function cummulative_return (given below) but the result is not as expected.
library(TTR) # ROC function
a = c(-1000,-2000,-3000,-4000,-5000,-6000,-7000,-8000)
b = c(1,2,3,4,5,6,7,8)
c = c(-7, -1, -20, -50, -93, 112, 212)
d = c(7, 1, 20, 50, 93, -112, -212)
cummulative_return <- function(x){
y <- ROC(x, type = c("discrete"), na.pad = T) * sign(lag(x))
cumprod(na.omit(y) + 1) - 1
}
cummulative_return(a)
[1] -1 -1 -1 -1 -1 -1 -1
cummulative_return(b)
[1] 1 2 3 4 5 6 7
cummulative_return(c)
[1] 0.8571429 -34.4285714 15.7142857 1.3400000 6.4980645 13.1927650
cummulative_return(d)
[1] -0.8571429 1.8571429 6.1428571 12.2857143 -17.0000000 -2.7142857
Only the answer for vector 'a' is incorrect, and the expected result should be
cummulative_return(a)
[1] -1 -2 -3 -4 -5 -6 -7
Can you point out the error in the function cummulative_return?
Also, Is there a similar function in any library that can find the cumulative return of negative and positive numbers without such errors?
if I got the definition of cumulative return correct, it is the difference between the value at position x and the initial value, divided by the initial value for normalisation. This can be achieved with the following function:
cummulative_return <- function(x) {
(x[2:length(x)]-x[1])/abs(x[1])
}
> cummulative_return(a)
[1] -1 -2 -3 -4 -5 -6 -7
> cummulative_return(b)
[1] 1 2 3 4 5 6 7
> cummulative_return(c)
[1] 0.8571429 -1.8571429 -6.1428571 -12.2857143 17.0000000 31.2857143
> cummulative_return(d)
[1] -0.8571429 1.8571429 6.1428571 12.2857143 -17.0000000 -31.2857143