def submitBuyOrder(stockObject, stockIndex): # Submit Order on Alpaca currentOrders = api.list_orders() for order in currentOrders: if order.symbol == stockObject.symbol: return False api.submit_order(symbol=stockObject.symbol, side='buy', type='limit', qty=stockObject.shares, time_in_force='day', limit_price=stockObject.buyPrice) time.sleep(4) currentOrders = api.list_orders() for order in currentOrders: if order.symbol == stockObject.symbol and order.qty == stockObject.shares: print('Order not filled') api.cancel_order(order.id) return False print('Bought ' + str(stockObject.symbol) + ' ' + str(stockObject.buyPrice)) positionsOpen[stockIndex].currentPosition = 1 connector.insertTrade(stockObject.symbol, floaty(stockObject.highPrice), floaty(stockObject.lowPrice), floaty(stockObject.openPrice), floaty(stockObject.closePrice), int(positionsOpen[stockIndex].shares), int(stockObject.volume), 'none', 'senkouB_buy', connection) return True
def submitSellOrder(stockObject, stockIndex): # Submit Order on Alpaca global cash print(stockObject.symbol + ' Sell at: ' + str(stockObject.closePrice)) cash += (positionsOpen[stockIndex].shares * stockObject.closePrice) positionsOpen[stockIndex].currentPosition = 0 api.submit_order( symbol=stockObject.symbol, side='sell', type='market', qty=stockObject.shares, time_in_force='gtc', ) connector.insertTrade(stockObject.symbol, floaty(stockObject.highPrice), floaty(stockObject.lowPrice), floaty(stockObject.openPrice), floaty(stockObject.closePrice), int(positionsOpen[stockIndex].shares), int(stockObject.volume), 'none', 'senkouB_sell', connection) positionsOpen[stockIndex].clearValues()
def algoStart(api, stocks, from_time, to_time, cash, strat): positions = [] cash = floaty(cash) if strat == 'bband_rsi_algo': for stock in stocks: alltrades, remaining = bband_rsi_algo(api, stock, from_time, to_time, cash) profit = round((remaining - cash), 0) positions.append((stock, alltrades, profit)) if strat == 'hammer': for stock in stocks: alltrades, remaining = hammer_algo(api, stock, from_time, to_time, cash) profit = round((remaining - cash), 0) positions.append((stock, alltrades, profit)) if strat == 'morningStar': for stock in stocks: alltrades, remaining = morningstar_algo(api, stock, from_time, to_time, cash) profit = round((remaining - cash), 0) positions.append((stock, alltrades, profit)) if strat == 'senkouB': for stock in stocks: try: alltrades, remaining = senkouB(api, stock, from_time, to_time, cash) profit = round((remaining - cash), 0) positions.append((stock, alltrades, profit)) except Exception as e: pass return positions
def dashboard(): if request.method == 'GET': global symbol connector = db.dbConnector() connection = connector.createConnection() scrapedStocks = connector.getMentions(connection) symbols = [] for x in scrapedStocks: symbols.append(x['symbol']) this = datetime.datetime.today() - timedelta(days=5) time = str(this.year) + "-" + str(this.month) + "-" + str( this.day) + " " + str(datetime.time(9, 35)) day = str(this.year) + "-" + str(this.month) + "-" + str(this.day) print(day) trades = connector.getTradeRecents(connection, time) trades = trades[0:25] stonks = connector.getBarsByTime(connection, time) stonks = stonks[0:25] results = connector.getResultsByDate(connection, day) for x in results: diff = x['endCash'] - x['startCash'] percentChange = diff / floaty(x['startCash']) + 1 x['percentChange'] = percentChange strategy = ad.Strategy() hammerChanges = strategy.calculateProfits(connector, connection, 'hammer') morningStarChanges = strategy.calculateProfits(connector, connection, 'morningStar') senkouBChanges = strategy.calculateProfits(connector, connection, 'senkouB_') if request.method == 'POST': symbol = request.form.get('symbol') df = api.polygon.historic_agg_v2(symbol, 1, 'minute', _from='2020-07-01', to='2020-07-01').df df['timestamp'] = df.index df = df.reset_index(drop=True) return render_template('graph.html', df=df.to_json(), symbol=symbol) return render_template('dashboard_copy.html', symbols=symbols, trades=trades, stonks=stonks, results=results, hammerChanges=hammerChanges, morningStarChanges=morningStarChanges, senkouBChanges=senkouBChanges)
def clearValues(self): self.symbol = self.symbol self.currentPosition = False self.buyPrice = floaty() self.shares = 0 self.takeProfit = floaty() self.lossProfit = floaty() self.closePrice = floaty() self.volume = int() self.high = floaty() self.low = floaty() self.open = floaty()
def __init__(self, stock, currentPosition): self.symbol = stock self.currentPosition = currentPosition self.buyPrice = floaty() self.shares = 0 self.takeProfit = floaty() self.lossProfit = floaty() self.closePrice = floaty() self.volume = int() self.high = floaty() self.low = floaty() self.open = floaty()
for x in symbols: stocks.append(x['symbol']) positions = bt.algoStart(api, stocks, fromTime, toTime, 25000) #print(positions) trades = [] for x in positions: if x[2] != 0.0: trades.append(x) csvRows = [] row = [] #print(trades) for x in trades: row.append(takeLoss) row.append(takeProfit) row.append(x[3][1]) row.append(floaty(x[3][0]['close']) - floaty(x[3][0]['low'])) row.append(floaty(x[3][0]['volume'])) row.append(x[1][0][11:13]) row.append(x[1][0][14:16]) if x[2] > 0: row.append(1) else: row.append(0) csvRows.append(row) row = [] with open(filename, 'a') as csvfile: # creating a csv writer object csvwriter = csv.writer(csvfile) # writing the fields #csvwriter.writerow(fields)
def algo(stock): global cash maxTrade = cash * .07 # Add to list if it is not in it if not (any(x for x in positionsOpen if x.symbol == stock)): positionsOpen.append(position(stock, 0)) stockIndex = 0 for x in positionsOpen: if x.symbol == stock: break stockIndex = stockIndex + 1 # Market variables marketOpen = datetime.time(hour=9, minute=30, second=0, microsecond=0) buyClose = datetime.time(hour=15, minute=30, second=0, microsecond=0) # Risk ratios takeProfitPercent = 1.07 lossProfitPercent = .97 try: df = api.polygon.historic_agg_v2(stock, 1, 'minute', _from=str(datetime.datetime.today()), to=str(datetime.datetime.today())).df except Exception as e: print(e) return False askPrice = round(api.polygon.last_quote(stock).askprice, 2) df.at[df.tail(1).index.item(), 'close'] = askPrice # Senkou Span B Calculation period52_high = df['high'].rolling(window=26).max() period52_low = df['low'].rolling(window=26).min() df['senkouB'] = ((period52_high + period52_low) / 2).shift(13) df['senkouB'] = df['senkouB'].fillna(df.iloc[1]['close']) df['volume'] = df['volume'].values.astype(floaty) # VWAP calculations df['vwap'] = ta.volume.VolumeWeightedAveragePrice( high=df['high'], low=df['low'], close=df['close'], volume=df['volume'], n=1000, fillna=True).volume_weighted_average_price() # Volume is at least 50% the previous 20 minutes df['volume20avg'] = df['volume'].rolling(window=20).mean() df['volume20avg'] = df['volume20avg'].fillna(df.iloc[1]['volume']) #Assign all the variables we will need for the algo lastRow = (df.tail(1)) lastRowTime = lastRow.index[0].time() closePrice = lastRow.iloc[-1]['close'] highPrice = lastRow.iloc[-1]['high'] lowPrice = lastRow.iloc[-1]['low'] openPrice = lastRow.iloc[-1]['open'] volume = (lastRow.iloc[-1]['volume']) volumeavg = (lastRow.iloc[-1]['volume20avg']) vwapPrice = (lastRow.iloc[-1]['vwap']) senkouPrice = (lastRow.iloc[-1]['senkouB']) if vwapPrice > senkouPrice: higherValue = vwapPrice #Make sure it has recenty crossed (last 5 mins) in_20 = False for index, row in df[['senkouB', 'vwap', 'close']].tail(5).iterrows(): if row.close <= row.vwap or row.close <= row.senkouB: in_20 = True firstValue = df[['close']].tail(15).head(1).close[0] highestValue = df[['close']].tail(15).head(1).close[0] three_percent_gain = False #Make sure it has a gain of at least 3% in the last 15 minutes for index, row in df[['close']].tail(15).iterrows(): if row.close > highestValue: highestValue = row.close if floaty(highestValue / firstValue) - 1.00 > .025: three_percent_gain = True try: if (lastRowTime > marketOpen): #and lastRowTime < buyClose): # Buy check ---------- # first check if open position # Next check if volume is greater than 50% of 20 min moving average, # if current price is above the VWAP, # if the price crossed senkou and vwap within last 20 minutes # and current price is above Senkou B if volume >= volumeavg / 3.0 and closePrice > vwapPrice and in_20 and closePrice > senkouPrice and three_percent_gain and not positionsOpen[ stockIndex].currentPosition: #print('Stock %s vwapPrice %s senkouPrice %s closePrice %s' % (stock, vwapPrice, senkouPrice, closePrice)) updateValues(stockIndex, closePrice, highPrice, lowPrice, openPrice, volume) try: if api.get_asset(stock).tradable: positionsOpen[stockIndex].buyPrice = closePrice positionsOpen[stockIndex].shares = int(maxTrade / askPrice) cash = cash - (positionsOpen[stockIndex].shares * askPrice) positionsOpen[ stockIndex].takeProfit = takeProfitPercent * askPrice positionsOpen[ stockIndex].lossProfit = lossProfitPercent * askPrice submitBuyOrder(positionsOpen[stockIndex], stockIndex) except Exception as e: print(e) pass #Sell check --------- #First check if open position elif (positionsOpen[stockIndex].currentPosition): #Check if we have hit our take profit mark if closePrice >= positionsOpen[stockIndex].takeProfit: updateValues(stockIndex, closePrice, highPrice, lowPrice, openPrice, volume) submitSellOrder(positionsOpen[stockIndex], stockIndex) elif closePrice <= positionsOpen[stockIndex].lossProfit: updateValues(stockIndex, closePrice, highPrice, lowPrice, openPrice, volume) submitSellOrder(positionsOpen[stockIndex], stockIndex) elif buyClose <= lastRowTime: updateValues(stockIndex, closePrice, highPrice, lowPrice, openPrice, volume) submitSellOrder(positionsOpen[stockIndex], stockIndex) except Exception as e: print(str(e.args))
updateValues(stockIndex, closePrice, highPrice, lowPrice, openPrice, volume) submitSellOrder(positionsOpen[stockIndex], stockIndex) elif buyClose <= lastRowTime: updateValues(stockIndex, closePrice, highPrice, lowPrice, openPrice, volume) submitSellOrder(positionsOpen[stockIndex], stockIndex) except Exception as e: print(str(e.args)) if __name__ == '__main__': connector = db.dbConnector() connection = connector.createConnection() allStocks = finvizScrape.scrape() while True: for stock in allStocks: account = (api.get_account()) cash = floaty(account.cash) if float(stock.changePercent) >= 3: print(stock.symbol) algo(stock.symbol) for p in positionsOpen: if p.currentPosition == 1: print(p.symbol + ' ' + str(p.buyPrice) + ' ' + str(p.shares)) print('Waiting. . .') time.sleep(10)
# Connect to the database connector = db.dbConnector() connection = connector.createConnection() #Create time window to make api call for window = datetime.datetime.now() - datetime.timedelta(minutes=1) unscreened_stocks = connector.getMentions(connection) strategy = ad.Strategy() aggregateData = [] # iterate through symbols getting bar info for each symbol of last minute for x in unscreened_stocks[0:len(unscreened_stocks)-1]: df = pd.DataFrame() tryCounter = 0 data = [] # check if df has a value to account for API response time while df.empty and tryCounter < 5: df = api.get_barset(x["symbol"], '1Min', limit=1, after=window).df tryCounter +=1 if not df.empty: data.append(x['symbol']) data.append(floaty(df.iloc[0][0])) data.append(floaty(df.iloc[0][1])) data.append(floaty(df.iloc[0][2])) data.append(floaty(df.iloc[0][3])) data.append(floaty(df.iloc[0][4])) data.append(window) aggregateData.append(data) connector.insertBars(aggregateData,connection) print("--- %s seconds ---" % (datetime.datetime.now() - start))
connection = connector.createConnection() #create time window (5min intervals updated each minute) now = datetime.datetime.now() window = datetime.datetime.now() - datetime.timedelta(minutes=5) symbols = connector.getMentions(connection) strategy = ad.Strategy() sma = 0 shares = 0 takeProfitPercent = 1.04 lossProfitPercent = .98 buyClose = datetime.time(14, 00) marketClose = datetime.time(15, 30) alltrades = [] takeProfit = floaty() lossProfit = floaty() for x in symbols[0:50]: workingSet = connector.getBarsByTimeWindow(connection, window, now, x['symbol']) cash = connector.getCash(connection, 8) cash = cash[0]['cash'] maxPosition = cash * .1 if len(workingSet) >= 5: #print(workingSet) currentBar = len(workingSet) - 1 #print(workingSet[0]['close']) sma = strategy.simpleMovingAverageAcrossTime( workingSet, 0, currentBar) currentPosition = connector.getPosition(
def morningstar_algo(api, stock, from_time, to_time, cash): alltrades = [] cash = floaty(cash) currentPosition = None barNumber = 0 buyPrice = 0 shares = 0 takeProfitPercent = 1.04 lossProfitPercent = .99 maxPosition = cash * .05 takeProfit = floaty() lossProfit = floaty() marketOpen = datetime.time(hour=9, minute=45, second=0, microsecond=0) buyClose = datetime.time(hour=12, minute=0, second=0, microsecond=0) df = api.polygon.historic_agg_v2(stock, 1, 'minute', _from=from_time, to=to_time).df while barNumber <= len(df) - 1: if (df.index[barNumber].time() > marketOpen and df.index[barNumber].time() < buyClose) or currentPosition: closePrice = df.iloc[barNumber]['close'] three_bar = [df.iloc[barNumber - 1]] set = [ df.iloc[barNumber - 2], df.iloc[barNumber - 1], df.iloc[barNumber] ] if isMorningStar(set): alltrades.append( str((df.index[barNumber])) + ' Buy at: ' + str(closePrice)) buyPrice = df.iloc[barNumber]['close'] shares = int(maxPosition / closePrice) cash = cash - shares * closePrice takeProfit = takeProfitPercent * buyPrice lossProfit = lossProfitPercent * buyPrice currentPosition = 1 if currentPosition == 1: if closePrice >= takeProfit: if (buyPrice < closePrice): alltrades.append( str((df.index[barNumber])) + ' Sell at: ' + str(closePrice)) cash += (shares * closePrice) currentPosition = 0 elif closePrice <= lossProfit: alltrades.append( str((df.index[barNumber])) + ' Sell at: ' + str(closePrice)) cash += (shares * closePrice) currentPosition = 0 elif buyClose <= df.index[barNumber].time(): alltrades.append( str((df.index[barNumber])) + ' Sell at: ' + str(closePrice)) cash += (shares * closePrice) currentPosition = 0 barNumber += 1 return alltrades, floaty(cash)
def hammer_algo(api, stock, from_time, to_time, cash): alltrades = [] cash = floaty(cash) marketOpen = datetime.time(hour=9, minute=40, second=0, microsecond=0) buyClose = datetime.time(hour=12, minute=0, second=0, microsecond=0) currentPosition = None barNumber = 1 buyPrice = 0 shares = 0 takeProfitPercent = 1.06 lossProfitPercent = .96 maxPosition = cash * .1 takeProfit = floaty() lossProfit = floaty() df = api.polygon.historic_agg_v2(stock, 1, 'minute', _from=from_time, to=to_time).df strategy = ad.Strategy() try: while barNumber <= len(df) - 1: if (df.index[barNumber].time() > marketOpen and df.index[barNumber].time() < buyClose) or currentPosition: if barNumber > 5: closePrice = df.iloc[barNumber]['close'] start = barNumber - 5 sma = strategy.backtestSMA(df, start, barNumber) if strategy.isHammerBar(df.iloc[barNumber]) and sma < 0: alltrades.append( str((df.index[barNumber])) + ' Buy at: ' + str(closePrice)) buyPrice = df.iloc[barNumber]['close'] shares = int(maxPosition / closePrice) cash = cash - shares * closePrice takeProfit = takeProfitPercent * buyPrice lossProfit = lossProfitPercent * buyPrice currentPosition = 1 if currentPosition == 1: if closePrice >= takeProfit: if (buyPrice < closePrice): alltrades.append( str((df.index[barNumber])) + ' Sell at: ' + str(closePrice)) cash += (shares * closePrice) currentPosition = 0 elif closePrice <= lossProfit: alltrades.append( str((df.index[barNumber])) + ' Sell at: ' + str(closePrice)) cash += (shares * closePrice) currentPosition = 0 elif buyClose <= df.index[barNumber].time(): alltrades.append( str((df.index[barNumber])) + ' Sell at: ' + str(closePrice)) cash += (shares * closePrice) currentPosition = 0 barNumber += 1 except Exception as e: print(str(e.args)) return alltrades, floaty(cash)
def bband_rsi_algo(api, stock, from_time, to_time, cash): alltrades = [] cash = floaty(cash) marketOpen = datetime.time(hour=9, minute=45, second=0, microsecond=0) buyClose = datetime.time(hour=14, minute=0, second=0, microsecond=0) currentPosition = None barNumber = 0 buyPrice = 0 shares = 0 takeProfitPercent = 1.03 lossProfitPercent = .99 maxPosition = cash * .05 takeProfit = floaty() lossProfit = floaty() df = api.polygon.historic_agg_v2(stock, 1, 'minute', _from=from_time, to=to_time).df # BBANDS calculations indicator_bb = ta.volatility.BollingerBands(close=df["close"], n=20, ndev=1.5) df['bb_bbm'] = indicator_bb.bollinger_mavg() df['bb_bbh'] = indicator_bb.bollinger_hband() df['bb_bbl'] = indicator_bb.bollinger_lband() # RSI calculations df['RSI'] = ta.momentum.RSIIndicator(close=df["close"], n=14).rsi() try: while barNumber <= len(df) - 1: # Check if moving average is positive for the last 10 minutes if (df.index[barNumber].time() > marketOpen and df.index[barNumber].time() < buyClose) or currentPosition: closePrice = df.iloc[barNumber]['close'] # Make sure BBAND Values and RSI values are not NaN if not (pd.isnull((df.iloc[barNumber]['bb_bbm']))): # buy check if not currentPosition: if closePrice <= df.iloc[barNumber][ 'bb_bbl'] * 1.00: # see if close price is less than or equal too lower band if round( df.iloc[barNumber]['RSI'] ) <= 34: # make sure RSI indicates oversold position alltrades.append( str((df.index[barNumber])) + ' Buy at: ' + str(closePrice)) buyPrice = df.iloc[barNumber]['close'] shares = int(maxPosition / closePrice) cash = cash - shares * closePrice takeProfit = takeProfitPercent * buyPrice lossProfit = lossProfitPercent * buyPrice currentPosition = 1 # sell check elif (currentPosition and closePrice >= df.iloc[barNumber]['bb_bbh'] * .90 ) or (currentPosition and round(df.iloc[barNumber]['RSI']) >= 60 ) or (currentPosition and closePrice <= lossProfit): if closePrice >= takeProfit: if (buyPrice < closePrice): alltrades.append( str((df.index[barNumber])) + ' Sell at: ' + str(closePrice)) cash += (shares * closePrice) currentPosition = 0 elif closePrice <= lossProfit: alltrades.append( str((df.index[barNumber])) + ' Sell at: ' + str(closePrice)) cash += (shares * closePrice) currentPosition = 0 elif buyClose <= df.index[barNumber].time(): alltrades.append( str((df.index[barNumber])) + ' Sell at: ' + str(closePrice)) cash += (shares * closePrice) currentPosition = 0 barNumber += 1 except Exception as e: print(str(e.args)) return alltrades, floaty(cash)
def senkouB(api, stock, from_time, to_time, cash): alltrades = [] cash = floaty(cash) marketOpen = datetime.time(hour=9, minute=35, second=0, microsecond=0) buyClose = datetime.time(hour=15, minute=00, second=0, microsecond=0) currentPosition = 0 barNumber = 2 shares = 0 takeProfitPercent = 1.08 lossProfitPercent = .96 maxPosition = cash * .3 takeProfit = floaty() lossProfit = floaty() try: df = api.polygon.historic_agg_v2(stock, 1, 'minute', _from=from_time, to=to_time).df except Exception as e: print('Invalid Stock') return False # Senkou Span B Calculation period52_high = df['high'].rolling(window=26).max() period52_low = df['low'].rolling(window=26).min() df['senkouB'] = ((period52_high + period52_low) / 2).shift(13) df['senkouB'] = df['senkouB'].fillna(df.iloc[0]['close']) df['volume'] = df['volume'].values.astype(floaty) # VWAP calculations df['vwap'] = ta.volume.VolumeWeightedAveragePrice( high=df['high'], low=df['low'], close=df['close'], volume=df['volume'], n=1000, fillna=True).volume_weighted_average_price() # Volume is at least 50% the previous 20 minutes df['volume20avg'] = df['volume'].rolling(window=20).mean() df['volume20avg'] = df['volume20avg'].fillna(df.iloc[0]['volume']) try: while barNumber <= len(df) - 1: # Assign all the variables we will need for the algo df2 = df.head(barNumber) lastRow = (df2.tail(1)) closePrice = lastRow.iloc[0]['close'] volume = lastRow.iloc[0]['volume'] volumeavg = (lastRow.iloc[0]['volume20avg']) vwapPrice = (lastRow.iloc[0]['vwap']) senkouPrice = (lastRow.iloc[0]['senkouB']) if vwapPrice > senkouPrice: higherValue = vwapPrice if (df2.index[-1].time() > marketOpen and df2.index[-1].time() < buyClose or currentPosition): # Make sure it has recenty crossed (last 20 mins) in_20 = False for index, row in df2[['senkouB', 'vwap', 'close' ]].head(barNumber).tail(5).iterrows(): if row.close <= row.vwap or row.close <= row.senkouB: in_20 = True print(df2.index[-1].time()) print(closePrice) print(senkouPrice) firstValue = df2[['close']].tail(15).head(1).close[0] highestValue = df2[['close']].tail(15).head(1).close[0] three_percent_gain = False # Make sure it has a gain of at least 3% in the last 15 minutes for index, row in df2[['close']].tail(15).iterrows(): if row.close > highestValue: highestValue = row.close if floaty(highestValue / firstValue) - 1.00 > .025: three_percent_gain = True if not currentPosition and volume >= volumeavg / 3.0 and closePrice > vwapPrice and in_20 and closePrice > senkouPrice and three_percent_gain: alltrades.append( str((df2.index[-1])) + ' Buy at: ' + str(closePrice)) shares = int(maxPosition / closePrice) cash = cash - shares * closePrice takeProfit = takeProfitPercent * closePrice lossProfit = lossProfitPercent * closePrice currentPosition = 1 # sell check elif (currentPosition): if closePrice >= takeProfit: alltrades.append( str((df2.index[-1])) + ' Sell at: ' + str(closePrice)) cash += (shares * closePrice) currentPosition = 0 elif closePrice <= vwapPrice - .05: alltrades.append( str((df2.index[-1])) + ' Sell at: ' + str(closePrice)) cash += (shares * closePrice) currentPosition = 0 elif closePrice <= lossProfit: alltrades.append( str((df2.index[-1])) + ' Sell at: ' + str(closePrice)) cash += (shares * closePrice) currentPosition = 0 elif buyClose <= df2.index[-1].time(): alltrades.append( str((df2.index[-1])) + ' Sell at: ' + str(closePrice)) cash += (shares * closePrice) currentPosition = 0 barNumber += 1 except Exception as e: print(str(e.args)) return alltrades, floaty(cash)
barType = 'barType' strategy = ad.Strategy() # iterate through symbols getting bar info for each symbol of last minute for x in unscreened_stocks[0:50]: df = pd.DataFrame() tryCounter = 0 # check if df has a value to account for API response time while df.empty and tryCounter < 5: df = api.get_barset(unscreened_stocks[count]["symbol"], '1Min', limit=1, after=window).df tryCounter += 1 if not df.empty: # symbol - high - low - open - close - volume - shareCount - timestamp - barType try: symbol = unscreened_stocks[count]["symbol"] count += 1 connector.insertBar(str(symbol), floaty(df[symbol]['high'][0]), floaty(df[symbol]['low'][0]), floaty(df[symbol]['open'][0]), floaty(df[symbol]['close'][0]), floaty(df[symbol]['volume'][0]), connection) except Exception as e: print(str(e)) print("--- %s seconds ---" % (datetime.datetime.now() - start))