David Hancock
David Hancock

Reputation: 1071

Calculating cumulative returns

I have calculated the daily returns from some market data and am trying to add each of those returns in an accumulation column (cum_rets). Here's a sample of the data:

    timestamp   dash_cap    litecoin_cap    dogecoin_cap    nxt_cap Total_MC    Dal_rets
0   2014-02-14  702537  410011811   80883283    61942277    553539908   NaN
1   2014-02-15  1054625 413848776   73684156    59127182    547714739   -1.052349
2   2014-02-17  1882753 407014106   70512004    59753481    539162344   -1.561469
3   2014-02-18  3766068 398556278   69890414    60219880    532432640   -1.248178
4   2014-02-19  3038521 404855950   71588924    59870181    539353576   1.299871

I don't understand why, when I use this code:

merged['cum_rets'] = 0
merged['cum_rets'] = merged['cum_rets'].shift(1) + merged.Dal_rets
merged

it returns

    timestamp   dash_cap    litecoin_cap    dogecoin_cap    nxt_cap Total_MC    Dal_rets    cum_rets
0   2014-02-14  702537  410011811   80883283    61942277    553539908   NaN NaN
1   2014-02-15  1054625 413848776   73684156    59127182    547714739   -1.052349   -1.052349
2   2014-02-17  1882753 407014106   70512004    59753481    539162344   -1.561469   -1.561469
3   2014-02-18  3766068 398556278   69890414    60219880    532432640   -1.248178   -1.248178

merged['cum_rets'].shift(1) should retrieve the previous value for cum_rets and then add it to the current value of Dal_ret thus incrementally sumating all values in Dal_rets. I know I could use the .cumprod() but i'd like to learn why my method doesn't work

Upvotes: 1

Views: 611

Answers (1)

Ami Tavory
Ami Tavory

Reputation: 76406

merged['cum_rets'].shift(1) should retrieve the previous value for cum_rets and then add it to the current value of Dal_ret

is correct. However, the conclusion

thus incrementally sumating all values in Dal_rets

is not.

The expression

 a = b + c

treats a, b, and c as distinct arrays in the sense that it first adds b and c, then assigns the results to a. It doesn't matter if a and b refer to the same thing.


Incidentally, you probably want here cumsum, not cumprod.

Upvotes: 1

Related Questions