Ichimoku order entry

Hi, I am trying to code an Ichimoku Cloud. What I am looking for is to go long on the security if the current price is above the cloud AND if the close price of the 3 previous days were above the cloud. I coded the following but its not working properly. Im sure there is a more efficient way to code this.

equity = symbol('SPY'); n_f = 9; n_m = 26; n_s = 52;
import talib

def initialize(context):
schedule_function(Ichimoku, date_rules.every_day(), time_rules.market_open())

def Ichimoku(context, data):
bars = n_s*2
cur_price = data.current(equity,'price')
H = data.history(equity, 'high', bars, '1d')
L = data.history(equity,'low', bars, '1d')
3_back = data.history(equity,'close',3,'1d')
2_back = data.history(equity,'close',2,'1d')
1_back = data.history(equity,'close',1,'1d')

tenkan_sen = (H.rolling(n_f).max() + L.rolling(n_f).min())/2
kijun_sen = (H.rolling(n_m).max() + L.rolling(n_m).min())/2
senkou_span_a = ((tenkan_sen + kijun_sen) / 2).shift(n_m)
senkou_span_b = ((H.rolling(n_s).max() + L.rolling(n_s).min())/2).shift(n_m)


if (cur_price > senkou_span_a[-1]) and (3_back > senkou_span_a[-1]) and (2_back > senkou_span_a[-1]) and (1_back > senkou_span_a[-1]) :
order_target_percent(equity, 1.0)

elif (cur_price < senkou_span_b[-1]) and (3_back < senkou_span_b[-1]) and (2_back < senkou_span_b[-1]) and (1_back < senkou_span_b[-1]) :
order_target_percent(equity, -1.0)

else:
pass

2 responses

@Pedro,

try something like this:

    prices = data.history(STOCK, 'price', 4,'1d')

if (prices[-1] > senkou_span_a[-1]):
if (prices[-2] > senkou_span_a[-2]):
if (prices[-3] > senkou_span_a[-3]):
order_target_percent(STOCK, 1.0)

elif (prices[-1] < senkou_span_a[-1]):
if (prices[-2] < senkou_span_a[-2]):
if (prices[-3] < senkou_span_a[-3]):
order_target_percent(STOCK, 0)


BTW, to get help faster, please attach your backtest or at least format the code snippet properly.

Thank you very much Vladimir. I would take notice or your advice.