我已经创建了一个指数价格水平表(例如,S& P 500),我想计算每日回报率。表结构如下所示:
Date Value
2009-07-02 880.167341
2009-07-03 882.235134
2009-07-06 881.338052
2009-07-07 863.731494
2009-07-08 862.458985
我想计算索引的每日算术回报(即百分比回报),定义为:
Daily Return = P(2)/P(1) - 1
其中P代表这种情况下的指数值。给定上面的输入表,所需的输出将如下所示:
Date Return
2009-07-03 0.002349318
2009-07-06 -0.001016829
2009-07-07 -0.019977077
2009-07-08 -0.001473269
我觉得自我加入会起作用,但我不确定将第二张桌子上的日期增加到周末的最佳方法。
关于最佳方式的任何想法?
答案 0 :(得分:3)
WITH cteRank AS (
SELECT [Date], Value,
ROW_NUMBER() OVER(ORDER BY [Date]) AS RowNum
FROM YourTable
)
SELECT c1.[Date], c1.Value/c2.Value - 1 as [Return]
from cteRank c1
inner join cteRank c2
on c1.RowNum - 1 = c2.RowNum
where c1.RowNum > 1
答案 1 :(得分:2)
一个简单的交叉申请
SELECT
Tlater.Date, (Tlater.Value / TPrev2.Value) - 1
FROM
MyTable Tlater
CROSS APPLY
(
SELECT TOP 1 TPrev.Value
FROM MyTable TPrev
WHERE TPrev.Date < Tlater.Date
ORDER BY TPrev.Date
) TPrev2
注意:这在使用LAG的Denali(SQL Server 2012)中变得微不足道(未经测试,可能需要CTE)
SELECT
OrderDate,
(Value / (LAG(Value) OVER (ORDER BY Date))) -1
FROM
MyTable
或者
;WITH cPairs AS
(
SELECT
Date,
Value AS Curr,
LAG(Value) OVER (ORDER BY Date) AS Prev
FROM
MyTable
)
SELECT
Date,
(Curr / Prev) -1
FROM
cPairs
答案 2 :(得分:2)
如果您使用的是2005+,则可以将ROW_NUMBER功能与CTE结合使用:
;with RowNums as ( select *, row_number() over (order by date) as RN from table )
select *, r1.Value / r.Value - 1 as Return
from RowNums r
inner join RowNums r1
on r.RN = r1.RN - 1