当价格低于阈值时使用 Pandas DataFrame 实现矢量化止损 [英] Implement a vectorized stop loss when price goes below a threshold using pandas DataFrame

查看:95
本文介绍了当价格低于阈值时使用 Pandas DataFrame 实现矢量化止损的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于此示例数据帧:

date;close;signal;positions
2017-01-02;27.90;0.0;0.0
2017-01-03;27.76;0.0;0.0
2017-01-04;28.65;1.0;1.0
2017-01-05;28.72;1.0;0.0
2017-01-06;28.00;1.0;0.0
2017-01-09;27.03;1.0;0.0 # <<<--- Note the price is -5% when compared to 28.65 (in 2017-01-04)
2017-01-10;28.26;1.0;0.0
2017-01-11;28.35;0.0;-1.0 # <<-- Sell
2017-01-12;29.12;0.0;0.0
2017-01-13;28.99;0.0;0.0
2017-01-16;28.50;1.0;1.0
2017-01-17;28.45;1.0;0.0
2017-01-18;29.06;1.0;0.0
2017-01-19;28.74;0.0;-1.0
2017-01-20;28.76;0.0;0.0
2017-01-23;29.50;0.0;0.0
2017-01-24;29.12;1.0;1.0
2017-01-25;29.87;1.0;0.0
2017-01-26;27.22;1.0;0.0 # <<<--- Note the price is -5% when compared to 29.12 (in 2017-01-24)
2017-01-27;29.76;1.0;0.0 # <<-- still holding the position...

我想在价格低于 5% 时实施止损".在这种情况下,DataFrame 应如下所示:

I want to implement a "stop loss" when the prices go bellow, let's say, 5%. In this case, the DataFrame should look like as:

date;close;signal;positions
2017-01-02;27.90;0.0;0.0
2017-01-03;27.76;0.0;0.0
2017-01-04;28.65;1.0;1.0 # <<-- Buy
2017-01-05;28.72;1.0;0.0
2017-01-06;28.00;1.0;0.0
2017-01-09;27.03;0.0;-1.0 # <<-- Sell with stop-loss
2017-01-10;28.26;0.0;0.0
2017-01-11;28.35;0.0;0.0
2017-01-12;29.12;0.0;0.0
2017-01-13;28.99;0.0;0.0
2017-01-16;28.50;1.0;1.0 # <<-- Buy
2017-01-17;28.45;1.0;0.0
2017-01-18;29.06;1.0;0.0
2017-01-19;28.74;0.0;-1.0 # <<-- Sell with profit
2017-01-20;28.76;0.0;0.0
2017-01-23;29.50;0.0;0.0
2017-01-24;29.12;1.0;1.0 # <<-- Buy
2017-01-25;29.87;1.0;0.0
2017-01-26;27.22;0.0;-1.0 # <<-- Sell with stop-loss
2017-01-27;29.76;0.0;0.0

(请注意 2017-01-09 和 2017-01-26 的变化).

(Please note the changes in 2017-01-09 and 2017-01-26).

简单说一下,信号"栏代表的是1.0时的持仓."positions" 列是使用 df['signal'].diff() 计算的,它在等于 1.0 时表示买入,在等于 -1.0 时表示卖出.

Just to make it clear, the "signal" column represents holding positions when it is 1.0. The "positions" column was computed using df['signal'].diff() and it represents a buy when equal to 1.0 and a sell when it is equal to -1.0.

先谢谢你!

推荐答案

IIUC now...

IIUC now...

data['cor_price'] = data['close'].where((data['signal'] == 1) & (data['positions'] == 1), pd.np.nan)
data['cor_price'] = data['cor_price'].ffill().astype(data['close'].dtype)
data['diff_perc'] = (data['close'] - data['cor_price']) / data['cor_price']
data['positions2'] = np.where(data['diff_perc'] <= -0.05, 1, 0)
data

这可能有待改进,但我是一步一步来的.首先创建一个带有相应买入价和远期填充的列.然后创建一个包含价格差异的列,最后创建显示您需要的结果的仓位2.

This might be open for improvement, but I took it step by step. First create a column with the corresponding buying price and forward fill. Then create a column with the price differences and lastly create positions2 which shows the result you need.

这篇关于当价格低于阈值时使用 Pandas DataFrame 实现矢量化止损的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆