【问题标题】:Implement a vectorized stop loss when price goes below a threshold using pandas DataFrame当价格低于使用 pandas DataFrame 的阈值时实现矢量化止损
【发布时间】:2018-10-22 10:38:04
【问题描述】:

鉴于此示例 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 应该如下所示:

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 的变化)。

为了说明清楚,“信号”一栏代表1.0时的持仓。 “仓位”列是使用df['signal'].diff() 计算的,当等于 1.0 时表示买入,当等于 -1.0 时表示卖出。

提前谢谢你!

【问题讨论】:

  • 我当时没听懂你的问题,祝你好运...
  • 下面的答案对你有用吗?

标签: pandas numpy dataframe vectorization algorithmic-trading


【解决方案1】:

IIUC 现在...

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。

【讨论】:

  • 谢谢!它还不是完整的解决方案,但我可以开始:)
  • 请编辑您的问题,以便我能提供帮助。
猜你喜欢
  • 2023-01-17
  • 2023-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-17
  • 1970-01-01
  • 1970-01-01
  • 2020-03-20
相关资源
最近更新 更多