php*_*kie 0 numpy vectorization algorithmic-trading dataframe pandas
鉴于此示例数据帧:
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...
Run Code Online (Sandbox Code Playgroud)
我想在价格低于 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
Run Code Online (Sandbox Code Playgroud)
(请注意 2017-01-09 和 2017-01-26 的变化)。
只是为了清楚起见,“信号”栏代表的是 1.0 时的持仓。“持仓”列是使用df['signal'].diff()它计算的,当它等于 1.0 时代表买入,当它等于 -1.0 时代表卖出。
先感谢您!
IUC现在...
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
Run Code Online (Sandbox Code Playgroud)
这可能有待改进,但我是一步一步来的。首先创建一个带有相应买入价和远期填充的列。然后创建一个包含价格差异的列,最后创建 position2 来显示您需要的结果。
| 归档时间: |
|
| 查看次数: |
1115 次 |
| 最近记录: |