问题描述
我有15分钟的蜡烛数据,并且有一个简短的信号-我想创建一个新的柱止损,如果signal = 0,则止损=下一个蜡烛的第二个高点,即(df ['high'] .shift(-2))
open high low close signal
date
2020-01-01 09:15:00 1452.50 1457.00 1449.20 1452.50 NaN
2020-01-01 09:30:00 1452.30 1454.40 1450.00 1451.45 NaN
2020-01-01 09:45:00 1450.50 1454.80 1450.00 1453.75 NaN
2020-01-01 10:00:00 1453.70 1453.70 1450.10 1450.70 0.0
2020-01-01 10:15:00 1450.70 1453.00 1450.50 1452.20 NaN
2020-01-01 10:30:00 1452.00 1452.00 1446.75 1446.85 NaN
2020-01-01 10:45:00 1447.60 1449.00 1445.50 1447.10 NaN
2020-01-01 11:00:00 1446.75 1449.00 1446.55 1447.65 NaN
在此示例中:
2020-01-01 10:00:00的短期信号止损将为1452.00
这是2020-01-01 10:30:00的最高点
解决方法
让我们尝试np.where(condition,answer if condition is true,answer if condition is false)
df['stop-loss']=np.where(df.signal==0,df.high.shift(-2),'')
在这种情况下,您没有指定为false时的条件,所以我将其放在''
open high low close signal stop-loss
date
2020-01-01 09:15:00 1452.50 1457.0 1449.20 1452.50 NaN
2020-01-01 09:30:00 1452.30 1454.4 1450.00 1451.45 NaN
2020-01-01 09:45:00 1450.50 1454.8 1450.00 1453.75 NaN
2020-01-01 10:00:00 1453.70 1453.7 1450.10 1450.70 0.0 1452.0
2020-01-01 10:15:00 1450.70 1453.0 1450.50 1452.20 NaN
2020-01-01 10:30:00 1452.00 1452.0 1446.75 1446.85 NaN
2020-01-01 10:45:00 1447.60 1449.0 1445.50 1447.10 NaN
2020-01-01 11:00:00 1446.75 1449.0 1446.55 1447.65 NaN
在评论中回答您的其他问题。假设数据框是
open high low close signal
date
2020-01-01 09:15:00 1452.50 1457.0 1449.20 1452.50 NaN
2020-01-01 09:30:00 1452.30 1454.4 1450.00 1451.45 NaN
2020-01-01 09:45:00 1450.50 1454.8 1450.00 1453.75 NaN
2020-01-01 10:00:00 1453.70 1453.7 1450.10 1450.70 0.0
2020-01-01 10:15:00 1450.70 1453.0 1450.50 1452.20 NaN
2020-01-01 10:30:00 1452.00 1452.0 1446.75 1446.85 1.0
2020-01-01 10:45:00 1447.60 1449.0 1445.50 1447.10 NaN
2020-01-01 11:00:00 1446.75 1449.0 1446.55 1447.65 NaN
使用np.select([conditons],[choices],alternative)
conditions=[df.signal==0,df.signal==1]
choices=[df.high.shift(-2),df.low.shift(-2)]
df['stop-loss']=np.select(conditions,choices,'')
open high low close signal stop-loss
date
2020-01-01 09:15:00 1452.50 1457.0 1449.20 1452.50 NaN
2020-01-01 09:30:00 1452.30 1454.4 1450.00 1451.45 NaN
2020-01-01 09:45:00 1450.50 1454.8 1450.00 1453.75 NaN
2020-01-01 10:00:00 1453.70 1453.7 1450.10 1450.70 0.0 1452.0
2020-01-01 10:15:00 1450.70 1453.0 1450.50 1452.20 NaN
2020-01-01 10:30:00 1452.00 1452.0 1446.75 1446.85 1.0 1446.55
2020-01-01 10:45:00 1447.60 1449.0 1445.50 1447.10 NaN
2020-01-01 11:00:00 1446.75 1449.0 1446.55 1447.65 NaN