I am trying to build the gap algorithm that compares the intraday price with opening price of the day. It buys stocks at open of day and closes it whenever intraday price is greater than open of the day. However, below algorithm opens position at start of day and closes it at same time. Please assist
import pandas as pd
def initialize(context):
context.stock=symbol('AAPL')
context.highprice= 0
context.lowprice=0
context.high_low_time=0
context.counter = 0
def handle_data(context, data):
price_history = history(bar_count=2, frequency='1d', field='price')
time = pd.Timestamp(get_datetime()).tz_convert('US/Eastern')
minute_close= data[context.stock].low
prev_bar= price_history[context.stock][-2]
curr_bar= price_history[context.stock][-1]
gap = curr_bar - prev_bar
if prev_bar > curr_bar and context.counter !=1:
order(context.stock, 100)
log.info('Buy 100 at {} at {} '.format(minute_close,time))
context.counter = 1
if (minute_close > (curr_bar - 0.8 *abs(gap))).any():
order(context.stock,-100)
log.info('sell 100 at {} at {} '.format(minute_close,time))
if time.hour == 15 and time.minute == 59:
order_target_percent(context.stock, 0)
log.info('closing position at eod in {}' .format(context.stock))
context.counter =0