I am doing some backtesting for some trading strategies on the stock market on a pandas dataframe and I would like to set a trailing stop loss of 1% away from the entered price. If the stock price went up by let's say 5%, the trailing stop loss will move up 5% as well. If the stock price went down, the trailing stop loss will not change. (https://www.investopedia.com/terms/t/trailingstop.asp)
I have this table which shows my signal to enter and the exit column will show a value of 1 if the price goes below the trailing stop loss price, which means the trade is exited.
This is the table I have so far:
date price entry_signal
30/06/2018 95 0
01/07/2018 100 1
02/07/2018 103 0
03/07/2018 105 0
04/07/2018 104.50 0
05/07/2018 101 0
I would like to have a column showing what is the trailing stop loss at every date. The trailing stop loss is first set as 99% of the price on 01/07/2018 when the enter_signal = 1, where trade is executed on this date.
When the price moves up by y%, the trailing stop loss will move up by y% as well. However if the price goes down, the trailing stop loss will not change from its last value.
When the price <= trailing stop loss, the trade is exited and there will be an exit_signal of 1...
I am currently stuck at not having the trailing stop loss to move down by y% if the price move down by y% as well....
Desired table outcome:
date price trailing stop loss entry_signal exit_signal
30/06/2018 95 NULL 0 0
01/07/2018 100 99 1 0
02/07/2018 103 101.97 0 0
03/07/2018 105 103.95 0 0
04/07/2018 104.50 103.95 0 0
05/07/2018 101 103.95 0 1
Table I have obtained:
date price trailing stop loss entry_signal
30/06/2018 95 NULL 0
01/07/2018 100 99 1
02/07/2018 103 101.97 0
03/07/2018 105 103.95 0
04/07/2018 104.50 103.455 0
05/07/2018 101 99.99 0