在sql中运行累积返回

时间:2014-09-06 13:27:51

标签: sql return finance

想要获得一系列每日回报的累积回报?我知道这可以使用exp和sum来解决,但我的返回系列不是使用LN计算的。

希望在不使用循环的情况下解决这个问题,因为它们在sql中非常低效。 重要的是要让它快速运行。

数据集:

enter image description here

期望的结果

enter image description here

2 个答案:

答案 0 :(得分:4)

这是你想要的吗?

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

exp()log()的功能在您使用的数据库中可能有所不同。在许多数据库中,您还可以使用:

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

我认为任何数据库都没有内置product()聚合功能。唉。

答案 1 :(得分:0)

(1+r)(1+r)(1+r)转换为

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

不起作用,因为1 + r可能是负数。 负日志未定义。即回报率低于-100%