计算 SQL 中的每日股票回撤

Calculating Daily Stock Drawdowns in SQL

我有 table 个股票价格,我想从中计算回撤。

Ticker       Date        price
ABC         01/01/13    100.00
ABC         01/02/13    101.50
ABC         01/03/13     99.80
ABC         01/04/13     95.50
ABC         01/05/13     78.00
XYZ         01/01/13     11.50
XYZ         01/02/13     12.10
XYZ         01/03/13     13.15
XYZ         01/04/13     14.10
XYZ         01/05/13     15.55

我将回撤定义为最高价(截至并包括该日期)减去当前价格除以最高价之间的差值。

每日最高价和每日回撤应如下所示:

Ticker   Date       price      max   drawdown
ABC     01/01/13   100.00    100.00    0.0%
ABC     01/02/13   101.50    101.50    0.0%
ABC     01/03/13    99.80    101.50    1.7%
ABC     01/04/13    95.50    101.50    5.9%
ABC     01/05/13    78.00    101.50   23.2% 
XYZ     01/01/13    11.50     11.50    0.0%
XYZ     01/02/13    12.10     12.10    0.0%
XYZ     01/03/13    13.15     17.15    0.0%
XYZ     01/04/13    14.10     14.10   17.8%
XYZ     01/05/13    15.55     15.55    9.3%

我知道如何计算整个数据集的最大回撤,但我正在努力改进适用于个股的每日回撤。

;WITH x AS
(  SELECT [drop] = ((s.price-e.price)/s.price) *100 
    FROM [temp] AS s
    INNER JOIN [temp] AS e
    ON s.[Date] < e.[Date]
    AND s.price > e.price
)
   SELECT [Largest Drawdown] = MAX([drop]) FROM x;

Largest Drawdown
87.900000000000000

此回撤正在计算整个数据集的最高价格(ABC 为 101.50)和数据集的最低价(XYZ = 11.50),以获得 87.9% 的最大回撤

如何计算每只股票的每日回撤?

这听起来像一个 window 函数:

select t.*,
       max(t.price) over (partition by ticker order by date) as max_price,
       (t.price / max(t.price) over (partition by ticker order by date)) - 1 as ratio
from temp t;