SQL计算贸易利润的查询

SQL Query for Calculating Trade Profits

正在尝试构建一个 SQL 脚本来计算每笔交易的 profit/loss 百分比

下面是原文table

SELECT id, exchange, ticker, signal, time, price 
from trade_data 
ORDER BY exchange, ticker, time;
id 交换 代码 信号 时间 价格
3 BSE_DLY UDAICEMENT 2021-08-05 22:00:43.800603 46.4
27 BSE_DLY UDAICEMENT 关闭 2021-08-06 10:00:26.718044 47.1
24 NAS TATAMOTORS 2021-08-06 05:45:16.384777 300.85
22 NAS UDAICEMENT 2021-08-06 05:00:25.23066 47.75
4 NSE 国民 2021-08-05 22:00:43.996958 94.8
26 NSE 国民 关闭 2021-08-06 09:45:17.511157 93.65
2 NSE NMDC 关闭 2021-08-05 22:00:43.600858 178.05
14 NSE NMDC 2021-08-06 03:45:11.243861 179.45
5 NSE 航行 2021-08-05 22:00:44.197164 140.4
25 NSE 航行 关闭 2021-08-06 09:45:17.441593 140.5
1 NSE TATACONSUM 关闭 2021-08-05 21:57:56.840043 761
13 NSE TATACONSUM 2021-08-06 03:37:38.371882 773
15 NSE TATAMOTORS 2021-08-06 03:45:12.891371 300.65

计算profit/loss百分比的公式

profit % =   (close_price-entry_price)   *  100
            ---------------------------
                 entry_price

Print profit as 0 if Trade Entry is not available

生成的数据集应如下所示

id 交换 代码 信号 时间 价格 利润百分比
3 BSE_DLY UDAICEMENT 2021-08-05 22:00:43.800603 46.4
27 BSE_DLY UDAICEMENT 关闭 2021-08-06 10:00:26.718044 47.1 1.5
24 NAS TATAMOTORS 2021-08-06 05:45:16.384777 300.85
22 NAS UDAICEMENT 2021-08-06 05:00:25.23066 47.75
4 NSE 国民 2021-08-05 22:00:43.996958 94.8
26 NSE 国民 关闭 2021-08-06 09:45:17.511157 93.65 -1.21
2 NSE NMDC 关闭 2021-08-05 22:00:43.600858 178.05 0
14 NSE NMDC 2021-08-06 03:45:11.243861 179.45
5 NSE 航行 2021-08-05 22:00:44.197164 140.4
25 NSE 航行 关闭 2021-08-06 09:45:17.441593 140.5 0.07
1 NSE TATACONSUM 关闭 2021-08-05 21:57:56.840043 761 0
13 NSE TATACONSUM 2021-08-06 03:37:38.371882 773
15 NSE TATAMOTORS 2021-08-06 03:45:12.891371 300.65

我猜你可以使用 LAG 函数来实现这一点。 想法是检查特定 exchange/ticker 组合的先前信号。 如果当前信号等于 'close' 并且没有之前的记录(我猜应该是信号 = 'long')那么我们输入 0 如果有之前的记录那么我们进行数学运算。对于 signal = 'long' 我们什么都不做。

请检查这是否可以接受。

select id, exchange, ticker, signal, time, price,
    case 
        when signal = 'close' and prev_signal is null then 0 
        when signal = 'close' then round(((price-prev_price)*100)/price, 2)
    end as profit
from (
    select id, exchange, ticker, signal, time, price, 
        lag(signal) OVER (PARTITION BY exchange, ticker ORDER BY time) as prev_signal,
        lag(price) OVER (PARTITION BY exchange, ticker ORDER BY time) as prev_price
    from trade_Data
) as t0