def getEnterDate(self,nextED=None, TOD="", calendar=None, stk=""): ''' Establish Enter Date ''' enterDate = None if ( TOD in ['Before Market', 'During Market'] ): ''' Back shift enter date if necessary ''' idx = utils.find_date_in_list(calendar=calendar, target_date=nextED, move=0 ) if(idx ==np.nan): last_idx = utils.find_date_in_list(calendar=calendar, target_date=nextED, move=1 ) else: last_idx = idx -1 try: enterDate = calendar[last_idx] return enterDate except: print stk, ": Couldn't locate earnings date" else: return nextED
def getScrubDate(self,nextED=None, TOD="", calendar=None): idx = utils.find_date_in_list(calendar=calendar, target_date=nextED, move=0 ) if( (TOD=='After Market') ): try: return calendar[idx+1] except: print nextED, " not in trading Calendar " elif( TOD!='nan' ): return nextED elif ( TOD=='nan' ): print "We should not even be attempting to update"
def momentumGuard(self): ''' # ========================================================= # ''' pos = self.execBroker.getPositions() for key, position_ in pos.iterrows(): if (position_['Symbol'] == self.hedgeInstrument): continue sgn = np.sign(position_['Number_of_Units']) ticker = (position_['Symbol']) if (sgn != 0): ''' Check if returns have moved against us ''' contract = self.execBroker.createContract( ticker=ticker, instrument_type=position_['Financial_Instrument']) todayOpen = datetime.datetime.now().replace(hour=9, minute=30) idx = utils.find_date_in_list( calendar=nysecal, target_date=datetime.date.today(), move=0) prevClose = datetime.datetime.combine(nysecal[idx - 1], datetime.time(16, 00)) prevClosePrice = self.execBroker.getDataAtTime( type_data='MIDPOINT', contract=contract, data_time=prevClose, bar_size='1 secs')['close'].iloc[-1] todayOpenPrice = self.execBroker.getDataAtTime( type_data='MIDPOINT', contract=contract, data_time=todayOpen, bar_size='1 secs')['close'].iloc[-1] interDayRtns = sgn * (todayOpenPrice - prevClosePrice) / prevClosePrice print ticker, interDayRtns if (interDayRtns <= 0): self.execBroker.closePosition(symbol=ticker, order_type='MARKET')
if (position['Symbol'] == hedgeInstrument): continue sgn = np.sign(position['Number_of_Units']) ticker = (position['Symbol']) if (sgn != 0): ''' Check if returns have moved against us ''' contract = ib.createContract( ticker=ticker, instrument_type=position['Financial_Instrument']) todayOpen = datetime.datetime.now().replace(hour=9, minute=30) idx = utils.find_date_in_list(calendar=nysecal, target_date=datetime.date.today(), move=0) prevClose = datetime.datetime.combine(nysecal[idx - 1], datetime.time(15, 59)) prevClosePrice = ib.getDataAtTime(type_data='MIDPOINT', contract=contract, data_time=prevClose, bar_size='1 secs')['close'].iloc[-1] todayOpenPrice = ib.getDataAtTime(type_data='MIDPOINT', contract=contract, data_time=todayOpen, bar_size='1 secs')['close'].iloc[-1]
def enterNewPositions(self): ''' This should be entered at the close ''' todayBulls = pd.Series() todayBears = pd.Series() # Get top 30 positions ''' ------------------- ''' ''' BULLS ''' ''' ------------------- ''' for stk in self.decision_algorithm.bulls.keys(): ''' live Data ''' contract = self.broker.createContract(ticker=stk, instrument_type='STK') liveData = self.broker.getLiveMarketData(contract=contract) print(stk, liveData) try: askPrice = liveData['price'][liveData['Type'] == 'ASK PRICE'] bidPrice = liveData['price'][liveData['Type'] == 'BID PRICE'] except: # Josh's fix askPrice = pd.Series() bidPrice = pd.Series() if ((not askPrice.empty) & (not bidPrice.empty)): todayClosePrice = (askPrice.values[0] + bidPrice.values[0]) * 0.5 #mid point else: try: todayClosePrice = liveData['price'][ liveData['Type'] == 'CLOSE PRICE'].values[0] except: print("Close price DNE for: ", stk) continue ''' prevClose ''' idx = utils.find_date_in_list(calendar=nysecal, target_date=dt.date.today(), move=0) print(idx) prevClose = dt.datetime.combine(nysecal[int(idx - 1)], dt.time(16, 0, 0)) prevClosePrice = self.broker.getDataAtTime( type_data='MIDPOINT', contract=contract, data_time=prevClose, bar_size='1 min', )['close'] ''' Inter Close-Close returns ''' # prevClosePrice=0.1 todayBulls[stk] = (todayClosePrice - prevClosePrice) / prevClosePrice print(stk, todayBulls[stk]) # print(stk, prevClosePrice) ''' ------------------- ''' ''' BEARS ''' ''' ------------------- ''' for stk in self.decision_algorithm.bears.keys(): ''' live Data ''' contract = self.broker.createContract(ticker=stk, instrument_type='STK') liveData = self.broker.getLiveMarketData(contract=contract) print(stk, liveData) try: askPrice = liveData['price'][liveData['Type'] == 'ASK PRICE'] bidPrice = liveData['price'][liveData['Type'] == 'BID PRICE'] except: # Josh's fix askPrice = pd.Series() bidPrice = pd.Series() if ((not askPrice.empty) & (not bidPrice.empty)): todayClosePrice = (askPrice.values[0] + bidPrice.values[0]) * 0.5 #mid point else: try: todayClosePrice = liveData['price'][ liveData['Type'] == 'CLOSE PRICE'].values[0] except: print("Close price DNE for: ", stk) continue ''' prevClose ''' idx = utils.find_date_in_list(calendar=nysecal, target_date=dt.date.today(), move=0) prevClose = dt.datetime.combine(nysecal[idx - 1], dt.time(16, 0, 0)) prevClosePrice = self.broker.getDataAtTime( type_data='MIDPOINT', contract=contract, data_time=prevClose, bar_size='1 min', )['close'] ''' Inter Close-Close returns ''' # prevClosePrice=0.1 todayBears[stk] = (todayClosePrice - prevClosePrice) / prevClosePrice print(stk, todayBears[stk]) # ''' live Data ''' # contract = self.broker.createContract(ticker=stk, instrument_type='STK') # liveData = self.broker.getLiveMarketData(contract=contract) # # askPrice = liveData['price'][ liveData['Type']=='ASK PRICE' ].values[0] # bidPrice = liveData['price'][ liveData['Type']=='BID PRICE' ].values[0] # # todayClosePrice = ( askPrice +bidPrice )*0.5 #mid price # # ''' prevClose ''' # idx = utils.find_date_in_list(calendar=nysecal, # target_date=dt.date.today(), # move=0) # prevClose = dt.datetime.combine( nysecal[idx-1], dt.time(16,0,0) ) # prevClosePrice = self.broker.getDataAtTime( type_data='MIDPOINT', # contract = contract, # data_time = prevClose, # bar_size='1 secs' # )['close'].iloc[-1] # # ''' Inter Close-Close returns ''' # todayBears[stk] = (todayClosePrice - prevClosePrice) /prevClosePrice todayBulls.sort_values(inplace=True, ascending=True) todayBears.sort_values( inplace=True, ascending=False ) # note the sign for bears is incorrectly calculated so we flip the sign. ''' keep only the top 30 ''' todayBears = todayBears.iloc[:min(self.decision_algorithm. params[2], todayBears.size)] todayBulls = todayBulls.iloc[:min(self.decision_algorithm. params[2], todayBulls.size)] ''' List of tickers to remove ''' # Bears popBear = [] for stk in self.decision_algorithm.bears.keys(): if stk not in todayBears.keys(): popBear.append(stk) # Bulls popBull = [] for stk in self.decision_algorithm.bulls.keys(): if stk not in todayBulls.keys(): popBull.append(stk) ''' Remove those not in top 30 ''' for stk in popBull: self.decision_algorithm.bulls.pop(stk, "None") for stk in popBear: self.decision_algorithm.bears.pop(stk, "None") print("Bears: ", self.decision_algorithm.bears) print("Bulls: ", self.decision_algorithm.bulls) ''' ---------------- ''' print("Enter Shorts") ''' ---------------- ''' for stk in self.decision_algorithm.bears.keys(): print(stk) try: stk_ = stk.replace(".", " ") c = self.broker.createContract(ticker=stk_, instrument_type="STK", primary_exchange='NYSE') sell_order = self.broker.createDollarOrder( trade_type='SELL', amount_dollars=self.dW, contract=c, order_type='MOC', ) #order_type='MARKET',) # time_in_force='MOC' # ) # default is market order time.sleep(1) order_id = self.broker.nextOrderId() # self.broker.placeRecordedOrder(order_id=order_id, # contract= c, # order=sell_order, # path = self.broker.exec_path # ) self.broker.placeOrder(order_id, c, sell_order) print('Short: ', stk_, order_id) # time.sleep(1) except: print("error:", traceback.format_exc()) continue ''' ---------------- ''' print("Enter Longs") ''' ---------------- ''' for stk in self.decision_algorithm.bulls.keys(): print(stk) try: stk_ = stk.replace(".", " ") c = self.broker.createContract(ticker=stk_, instrument_type="STK", primary_exchange='NYSE') buy_order = self.broker.createDollarOrder( trade_type='BUY', contract=c, amount_dollars=self.dW, order_type='MOC', ) # order_type='#MARKET',) # time_in_force='MOC' # ) # default is market order order_id = self.broker.nextOrderId() self.broker.placeOrder(order_id, c, buy_order) # self.broker.placeRecordedOrder(order_id=order_id, # contract= c, # order=buy_order, # path = self.broker.exec_path # ) print('Long: ', stk, order_id) time.sleep(1) self.broker.callback.order_Status # time.sleep(1) except: print("error:", traceback.format_exc()) continue
def momentumGuard(self): pos = self.broker.getPositions() for key, position_ in pos.iterrows(): if (position_['Symbol'] == self.hedgeInstrument): continue if (position_['Financial_Instrument'] != 'STK'): continue sgn = np.sign(position_['Number_of_Units']) ticker = (position_['Symbol']) if (sgn != 0): ''' Check if returns have moved against us ''' contract = self.broker.createContract( ticker=ticker, instrument_type=position_['Financial_Instrument']) #todayOpen = dt.datetime.now().replace( hour=9, minute=30,second=0 ) idx = utils.find_date_in_list(calendar=nysecal, target_date=dt.date.today(), move=0) prevClose = dt.datetime.combine(nysecal[idx - 1], dt.time(16, 0, 0)) try: prevClosePrice = self.broker.getDataAtTime( type_data='MIDPOINT', contract=contract, data_time=prevClose, bar_size='1 min' # used to be 1 secs )['close'] # NO ILOC WHEN BAR_SIZE == DURATION '''prevClosePrice = self.broker.getDataAtTime( type_data='MIDPOINT', contract = contract, data_time = prevClose, bar_size='1 min' # used to be 1 secs )['close'].iloc[-1]''' except: try: prevClosePrice = self.broker.getDataAtTime( type_data='BID', contract=contract, data_time=prevClose, bar_size='1 min' # used to be 1 secs )['close'] #.iloc[-1] # NO ILOC WHEN BAR_SIZE == DURATION except: prevClosePrice = self.broker.getDataAtTime( type_data='ASK', contract=contract, data_time=prevClose, bar_size='1 min' # used to be 1 secs )['close'] #.iloc[-1] # NO ILOC WHEN BAR_SIZE == DURATION print(ticker, prevClosePrice) # prevClose = self.broker.getDailyData(ticker, provider='yahoo', date_start=nysecal[idx-1], date_end=nysecal[idx-1] ) # prevClosePrice = prevClose['Adj Close'].values[0] time.sleep(1) liveData = self.broker.getLiveMarketData(contract=contract) try: askPrice = liveData['price'][liveData['Type'] == 'ASK PRICE'].values[0] except Exception as e: print(e) continue try: bidPrice = liveData['price'][liveData['Type'] == 'BID PRICE'].values[0] except Exception as e: print(e) continue todayOpenPrice = (askPrice + bidPrice) * 0.5 #mid point # todayOpenPrice = self.broker.getDataAtTime( type_data='MIDPOINT', # contract = contract, # data_time = todayOpen, # bar_size='1 secs' # )['close'].iloc[-1] interDayRtns = sgn * (todayOpenPrice - prevClosePrice) / prevClosePrice print(ticker, interDayRtns) if (interDayRtns <= 0): self.broker.closePosition(symbol=ticker, order_type='MARKET', record=True)