I am having some difficulty coding a trailing stop within Pipeline. Basically, I am attempting to make a strategy that will look for stocks that have moved 20% off of any low (buy signal). Then sell the stock when it falls 20% from any high. Take a look at this link for a better idea of what I am talking about. Trailing stop . On this website near the bottom of the page you should see a picture of a chart with a trailing stop. I realize in the picture the trailing stop is an ATR trailing stop. I simply want to make a trailing stop that follows 20% below the stock. Notice in the picutre how the blue trailing stop flips above and below the price. When the the blue trailing stop is above the price and the price exceeds the trailing stop, the trailing stop switches to be below the price. The action of the trailing stop flipping from above to below the price is my buy signal. I need help creating a pipeline that will spit out stocks (in the top 1000 by market cap) that display this buy signal.
I have attempted to work around this by calcuating this trading signal outside of the pipeline but this has proven extremely tedious and takes several hours to run a test.
Here is how I have been calculating the trading signal outside of the pipeline
buy_signal_list = []
for stock in context.output.index:
close = data.history(stock,"close",252,"1d")
high_location = np.nanargmax(close,axis = 0)
low_location = np.nanargmin(close,axis = 0)
if high_location > low_location:
close_data = close[high_location:]
trailstop = close_data[0]*.8
a = 0
elif high_location < low_location:
close_data = close[low_location:]
trailstop = close_data[0]*1.2
a = 1
trailstop_value = []
for i in range(len(close_data)):
value = float(close_data[i])
if trailstop <= value:
if a == 1:
trailstop = trailstop*.8
a = 0
elif a == 0:
trailstop = max(trailstop, value*.8)
elif trailstop > value:
if a == 0:
trailstop = trailstop*1.2
a = 1
elif a == 1:
trailstop = min(trailstop,value*1.2)
trailstop_value.append(trailstop)
last_two_trailstop_values = trailstop_value[-2:]
if len(last_two_trailstop_values) == 2:
if close[-1]>last_two_trailstop_values[-1] and close[-2]<last_two_trailstop_values[-2]:
buy_signal_list.append(stock)
context.output is a dataframe from the pipeline. All this pipeline returns is the top 1000 stocks by market cap
Any help is greatly appreciated!
Thank you
Jake