Search code examples
sqlreturnfinance

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


Solution

  • 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.