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)
ALPACA_SECRET_KEY = r'ysaezMtOX8sUghmR534ZGzEXzCTVpkDt26BEIY8e' APCA_RETRY_MAX=0 api = tradeapi.REST( key_id=ALPACA_KEY_ID, secret_key=ALPACA_SECRET_KEY, base_url='https://paper-api.alpaca.markets' ) # 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]))
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)