简体   繁体   English

正数和负数的累积回报

[英]Cumulative return of positive and negative numbers

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.我正在尝试使用函数 cummulative_return (下面给出)找到以下 4 个向量的累积回报,但结果并不如预期。

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只有向量 'a' 的答案不正确,预期结果应该是

cummulative_return(a)
[1] -1 -2 -3 -4 -5 -6 -7

Can you point out the error in the function cummulative_return?你能指出函数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.如果我对累积收益的定义正确,它是位置 x 处的值与初始值之间的差值,除以归一化的初始值。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM