Generating A Trailing Stop Strategy in Pandas But Cannot Prevent Re-issue Signal
I am relatively new to Python & Pandas. I am trying to generate a trailing stop strategy where once the total p&l of the position reaches either ultimate stop loss level, or the trailing stop level, position will be reset to zero, and will REMAIN zero. I am able to reset the position to zero, however, once the p&l moves above trailing stop, position resets back to original level.
Please see the code snippets below. I am sure there is an easy solution, but I am not able to think of it. Appreciate any help, any clue to move forward.
df['price_prev'] = df['close'].shift(1)
df['delta_price'] = df['close'] - df['price_prev']
df['delta_tick'] = df['delta_price']/tick
df['position open'] = position_open #this is set to a specific amo开发者_开发技巧unt e.g. 100 at start
df['position held'] = df['position open'] * buy_sell_signal() #the signal function gives a +1/-1 signal
df['p_l'] = df['delta_tick'] * df['position held']*tickvalue
df['total p&l'] = df['p_l'].cumsum()
df['trailing stop'] = df['total p&l'].cummax() + stop_loss
def change_position(x):
if x['total p&l'] <= x['trailing stop']:
x['position held'] = 0
return x
df = df.apply(change_position,axis='columns')
In row 235 df['position held']
resets to zero, because the df['total p&l']
went below df['trailing stop']
. This is the EXPECTED behaviour. However, as df['p_l']
continues to evaluate, the df['position held']
reverts to previous level.
How can I prevent this? I would like it to remain zero.
slice of dataframe
精彩评论