Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running cumulative return in sql

Looking to have a running cumulative return for a series of daily returns? I know this can be solved using exp and sum, but my return series is not calculated using LN.

Hoping to solve this without using loops, as they are very inefficient in sql. Its important to make this run fast.

Dataset:

enter image description here

desired result

enter image description here

like image 644
Børge Klungerbo Avatar asked Aug 26 '26 10:08

Børge Klungerbo


2 Answers

Is this what you want?

select t.*,
       (select exp(sum(log(1 + return))) - 1
        from table t2
        where t2.date <= t.date
       ) as cumereturn
from table t;

The functions for exp() and log() may be different in the database you are using. In many databases, you can also use:

select t.*, exp(sum(log(1 + return) over (order by date)) - 1
from table t;

I don't think any database has a built in product() aggregation function. Alas.

like image 145
Gordon Linoff Avatar answered Aug 29 '26 00:08

Gordon Linoff


converting (1+r)(1+r)(1+r) to

exp(log(1+r) + log(1+r) + log(1+r))

does not work because 1+r could be negative. Negative log is undefined. i.e. the return is less than -100%

like image 45
ckaihung Avatar answered Aug 29 '26 01:08

ckaihung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!