def pre_backtest_calculations(self, value): self.ema = TA.EMA(value) self.adx = TA.ADX(value) self.rsi = TA.RSI(value) self.bbands = TA.BBANDS(value) self.lower_bband = self.bbands["BB_UPPER"] self.upper_bband = self.bbands["BB_LOWER"]
def tech_indictors(df): df['macd'] = TA.MACD(df).SIGNAL df['boll_ub'] = TA.BBANDS(df).BB_UPPER df['boll_lb'] = TA.BBANDS(df).BB_LOWER df['rsi_30'] = TA.RSI(df, period=30) df['dx_30'] = TA.ADX(df, period=30) df['close_30_sma'] = TA.SMA(df, period=30) df['close_60_sma'] = TA.SMA(df, period=60) #fill NaN to 0 df = df.fillna(0) print( f'--------df head - tail ----------------\n{df.head(3)}\n{df.tail(3)}\n---------------------------------' ) return df
def add_technical_indicators(new_df): # Adding of technical indicators to data frame (Exponential moving average and Bollinger Band) edited_df = pd.DataFrame() edited_df['open'] = stock_df['Open'] edited_df['high'] = stock_df['High'] edited_df['low'] = stock_df['Low'] edited_df['close'] = stock_df['Close'] edited_df['volume'] = stock_df['Volume'] edited_df.head() ema = TA.EMA(edited_df) bb = TA.BBANDS(edited_df) new_df['Exponential_moving_average'] = ema.copy() new_df = pd.concat([new_df, bb], axis = 1) for i in range(19): new_df['BB_MIDDLE'][i] = new_df.loc[i, 'Exponential_moving_average'] if i != 0: higher = new_df.loc[i, 'BB_MIDDLE'] + 2 * new_df['Adj Close'].rolling(i + 1).std()[i] lower = new_df.loc[i, 'BB_MIDDLE'] - 2 * new_df['Adj Close'].rolling(i + 1).std()[i] new_df['BB_UPPER'][i] = higher new_df['BB_LOWER'][i] = lower else: new_df['BB_UPPER'][i] = new_df.loc[i, 'BB_MIDDLE'] new_df['BB_LOWER'][i] = new_df.loc[i, 'BB_MIDDLE'] return new_df
def get_bbands(data): if data is None: raise ValueError("Invalid data value") result = TA.BBANDS(data) if result is None: raise IndicatorException return result
def get_mean_open_close(number=120, kline_size='1m'): prices = [] # A utiliser que pour testnet !! # link = str(settings.BASE_URL) + "trade?symbol=XBTUSD&count="\ # + str(number * binsizes[kline_size]) + "&columns=price&reverse=true" link_ohlc = "https://www.bitmex.com/api/v1/trade/bucketed?binSize=1m&partial=true&symbol=XBTUSD&count=20&reverse=true" f = requests.get(link_ohlc) ohlc = pd.DataFrame(f.json()) ohlc = ohlc[['open', 'high', 'low', 'close']] # datta = TA.bb link = str(settings.BASE_URL) + "trade?symbol=.BXBT&count="\ + str(number * binsizes[kline_size]) + "&columns=price&reverse=true" f = requests.get(link) for x in f.json(): prices.append(float(x['price'])) prices = get_prices_binsize(prices, binsizes[kline_size]) prices.reverse() # Library Tulipy DATA = np.array(prices) bbands = ti.bbands(DATA, period=5, stddev=2) res = TA.BBANDS( get_all_bitmex('XBTUSD', kline_size, False, nb=(number * 2 * binsizes[kline_size]))) temp_df = pd.DataFrame() temp_df['BB_LOWER'] = bbands[0][-1:] temp_df['BB_MIDDLE'] = bbands[1][-1:] temp_df['BB_UPPER'] = bbands[2][-1:] # # AFFICHAGE COURBES # low = list(bbands[0]) middle = list(bbands[1]) high = list(bbands[2]) low = list(res.BB_LOWER[-number:]) middle = list(res.BB_MIDDLE[-number:]) high = list(res.BB_UPPER[-number:]) # plt.plot(high, color='orange') # plt.plot(middle, color='g') # plt.plot(low, color='yellow') # plt.plot(prices, color='red') # plt.show() # return temp_df return res[-number:], bbands
def test_bbands(): """test TA.BBANDS""" bb = TA.BBANDS(ohlc) assert isinstance(bb["BB_UPPER"], series.Series) assert isinstance(bb["BB_MIDDLE"], series.Series) assert isinstance(bb["BB_LOWER"], series.Series) assert bb["BB_UPPER"].values[-1] == 8212.7979228041968 assert bb["BB_MIDDLE"].values[-1] == 7110.5508235434954 assert bb["BB_LOWER"].values[-1] == 6008.303724282795
def get_bbands(data): """Calculate the Bollinger bands for values of given dataframe. :param data: a dataframe in OHLC format :return: a Pandas series """ if data is None: raise EmptyDataError("[!] Invalid data value") result = TA.BBANDS(data) if result is None: raise IndicatorException return result
def test_bbands(): '''test TA.BBANDS''' bb = TA.BBANDS(ohlc, 20) talib_bb = talib.BBANDS(ohlc['close'], timeperiod=20) # assert int(bb['BB_UPPER'][-1]) == int(talib_bb[0].values[-1]) # assert 8212 == 8184 # assert int(bb['BB_LOWER'][-1]) == int(talib_bb[2].values[-1]) # assert 6008 == 6036 pass # close enough
def bb(df): bands = TA.BBANDS(df).tail(chart_tail_count) close_tailed = df['close'].tail(chart_tail_count) def plottable(ax): if ax: bands['Close'] = close_tailed bands.plot(ax=ax) bands_ta = bands.tail(ta_hints_bars) close_ta_hints = df['close'].tail(ta_hints_bars) bb_diff = ((close_ta_hints - bands_ta['BB_LOWER']) * 100 / bands_ta['BB_LOWER']) bb_min_dist, bb_max_dist = min(bb_diff.values), max(bb_diff.values) info = f"BB min-max: {app.floor_new(bb_min_dist)} - {app.floor_new(bb_max_dist)}" signal = 'Buy' if bb_min_dist < 3 and bb_max_dist < 5 else 'WAIT' return {'signal': signal, 'info': info, 'plot': plottable}
def get_data(ticker): bol = TA.BBANDS(ohlc, period=20, std_multiplier=2) kc = TA.KC(ohlc, period=20, kc_mult=1.5, atr_period=14) mom = TA.ROC(ohlc, period=12) ema8 = TA.EMA(ohlc, period=9) ema21 = TA.EMA(ohlc, period=21) ema34 = TA.EMA(ohlc, period=34) ema55 = TA.EMA(ohlc, period=55) ema89 = TA.EMA(ohlc, period=89) atr14 = TA.ATR(ohlc, period=14) #print(mom) print(len(kc), len(bol), len(mom)) buymode = False f = open('result.csv', 'a') for i in range(100, len(kc) - 20): inside = (kc['KC_UPPER'][i - 1] > bol['BB_UPPER'][i - 1] and kc['KC_LOWER'][i - 1] < bol['BB_LOWER'][i - 1]) if inside: buymode = True outside = (kc['KC_UPPER'][i] < bol['BB_UPPER'][i] and kc['KC_LOWER'][i] > bol['BB_LOWER'][i]) if (buymode and outside): #if (random.randint(0,9) == 5): emaok = 0 if (ema8[i] > ema21[i]) and (ema21[i] > ema34[i]) and ( ema34[i] > ema55[i]) and (ema55[i] > ema89[i]): emaok = 1 buymode = False tttt = float(ohlc['Close'][i + 15]) ttt = float(ohlc['Close'][i + 10]) tt = float(ohlc['Close'][i + 5]) t = float(ohlc['Close'][i]) print(ohlc.index[i], (tt - t) / t * 100, (ttt - t) / t * 100, (tttt - t) / t * 100), emaok f.write(ticker + ',' + str(ohlc.index[i]) + ',' + str((tt - t) / t * 100) + ',' + str((ttt - t) / t * 100) + ',' + str((tttt - t) / t * 100) + ',' + str(emaok) + ',' + str(atr14[i]) + '\n') f.close()
def get_daily_data(ticker, compact=True): # 1 call print("\nLoading data for ticker: {}".format(ticker)) outputsize = 'compact' num_data_points = 100 if not compact: outputsize = 'full' num_data_points = 1000 + indicator_periods[-1] * 2 stock, meta_data = ts.get_daily(ticker, outputsize=outputsize) stock.columns = ['open', 'high', 'low', 'close', 'volume'] stock = stock[:num_data_points].iloc[::-1] indicators = [] for period in indicator_periods: indicators.append( TA.TEMA(ohlc=stock, period=period).to_frame(name='TEMA')) indicators.append(TA.BBANDS(ohlc=stock, period=period)) # volatility indicators.append( TA.MI(ohlc=stock, period=period).to_frame(name='MI')) # volatility indicators.append( TA.ATR(ohlc=stock, period=period).to_frame(name='ATR')) # volatility indicators.append( TA.RSI(ohlc=stock, period=period).to_frame(name='RSI')) # momentum indicators.append( TA.MFI(ohlc=stock, period=period).to_frame(name='MFI')) # momentum indicators.append( TA.WILLIAMS(ohlc=stock, period=period).to_frame(name='WILLIAMS')) # momentum indicators.append( TA.ZLEMA(ohlc=stock, period=period).to_frame(name='ZLEMA')) # trend indicators.append( TA.WMA(ohlc=stock, period=period).to_frame(name='WMA')) # trend indicators.append( TA.HMA(ohlc=stock, period=period).to_frame(name='HMA')) # trend x indicators.append( TA.VAMA(ohlcv=stock, period=period).to_frame(name='VAMA')) # volume x indicators.append( TA.EFI(ohlcv=stock, period=period).to_frame(name='EFI')) # volume indicators.append( TA.EMV(ohlcv=stock, period=period).to_frame(name='EMV')) # volume df = pd.concat(indicators, axis=1)[indicator_periods[-1] * 2:] stock = stock[indicator_periods[-1] * 2:] return stock, df
def add_technical_indicators(new_df): # Adding of technical indicators to data frame (Exponential moving average and Bollinger Band) edited_df = pd.DataFrame() #edited_df is made in order to generate the order needed for the finta library edited_df['open'] = stock_df['Open'] edited_df['high'] = stock_df['High'] edited_df['low'] = stock_df['Low'] edited_df['close'] = stock_df['Close'] edited_df['volume'] = stock_df['Volume'] edited_df.head() ema = TA.EMA(edited_df) bb = TA.BBANDS(edited_df) new_df['Exponential_moving_average'] = ema.copy() #Adding of features to the dataframe new_df = pd.concat([new_df, bb], axis=1) #Filling of missing data as Bollinger Bands is based on a 21 day EMA for i in range(19): new_df['BB_MIDDLE'][i] = new_df.loc[i, 'Exponential_moving_average'] if i != 0: higher = new_df.loc[ i, 'BB_MIDDLE'] + 2 * new_df['Adj Close'].rolling(i + 1).std()[i] lower = new_df.loc[ i, 'BB_MIDDLE'] - 2 * new_df['Adj Close'].rolling(i + 1).std()[i] new_df['BB_UPPER'][i] = higher new_df['BB_LOWER'][i] = lower else: new_df['BB_UPPER'][i] = new_df.loc[i, 'BB_MIDDLE'] new_df['BB_LOWER'][i] = new_df.loc[i, 'BB_MIDDLE'] return new_df
def get_bbo(self, contract): # Get best b/o excluding own orders vwap = {} ohlcv2 = {} fut2 = contract if contract is 'XBTUSD': fut2 = 'BTC/USD' if contract is 'ETHUSD': fut2 = 'ETH/USD' now = datetime.now() format_iso_now = now.isoformat() then = now - timedelta(minutes=100) format_later_iso = then.isoformat() thetime = then.strftime('%Y-%m-%dT%H:%M:%S') ohlcv = self.client.fetchOHLCV(fut2, '1m', self.client.parse8601(thetime)) ohlcv2 = [] for o in ohlcv: ohlcv2.append([o[1], o[2], o[3], o[4], o[5]]) df = pd.DataFrame(ohlcv2, columns=['open', 'high', 'low', 'close', 'volume']) best_bids = [] best_asks = [] if 1 in self.directional: #print(df) try: self.dsrsi = TA.STOCHRSI(df).iloc[-1] * 100 except: self.dsrsi = 50 #print(self.dsrsi) # Get orderbook if 2 in self.volatility or 3 in self.price or 4 in self.quantity_switch: self.bands[fut2] = TA.BBANDS(df).iloc[-1] self.bbw[fut2] = (TA.BBWIDTH(df).iloc[-1]) print( float(self.bands[fut2]['BB_UPPER'] - self.bands[fut2]['BB_LOWER'])) if (float(self.bands[fut2]['BB_UPPER'] - self.bands[fut2]['BB_LOWER'])) > 0: deltab = (self.get_spot() - self.bands[fut2]['BB_LOWER']) / ( self.bands[fut2]['BB_UPPER'] - self.bands[fut2]['BB_LOWER']) if deltab > 50: self.diffdeltab[fut2] = (deltab - 50) / 100 + 1 if deltab < 50: self.diffdeltab[fut2] = (50 - deltab) / 100 + 1 else: self.diffdeltab[fut2] = 25 / 100 + 1 if 3 in self.volatility: self.atr[fut2] = TA.ATR(df).iloc[-1] if 0 in self.price: # Get orderbook if contract == 'BTC/USD': ob = self.ws['XBTUSD'].market_depth() else: ob = self.ws[contract].market_depth() #ob = self.client.fetchOrderBook( contract ) #print(ob) bids = [] asks = [] for o in ob: if o['side'] == 'Sell': bids.append([o['price'], o['size']]) else: asks.append([o['price'], o['size']]) if contract == 'BTC/USD': ords = self.ws['XBTUSD'].open_orders('') else: ords = self.ws[contract].open_orders('') #print(ords) bid_ords = [o for o in ords if o['side'] == 'Buy'] ask_ords = [o for o in ords if o['side'] == 'Sell'] best_bid = None best_ask = None err = 10**-(self.get_precision(contract) + 1) best_bid = 9999999999999999999 for a in bids: if a[0] < best_bid: best_bid = a[0] best_ask = 0 for a in asks: if a[0] > best_ask: best_ask = a[0] print({'bid': best_bid, 'ask': best_ask}) best_asks.append(best_ask) best_bids.append(best_bid) if 1 in self.price: dvwap = TA.VWAP(df) #print(dvwap) tsz = self.get_ticksize(contract) try: bid = ticksize_floor(dvwap.iloc[-1], tsz) ask = ticksize_ceil(dvwap.iloc[-1], tsz) except: bid = ticksize_floor(self.get_spot(), tsz) ask = ticksize_ceil(self.get_spot(), tsz) print({'bid': bid, 'ask': ask}) best_asks.append(best_ask) best_bids.append(best_bid) if 2 in self.quantity_switch: dppo = TA.PPO(df) self.buysellsignal[fut2] = 1 try: if (dppo.iloc[-1].PPO > 0): self.buysellsignal[fut2] = self.buysellsignal[fut2] * ( 1 + PRICE_MOD) else: self.buysellsignal[fut2] = self.buysellsignal[fut2] * ( 1 - PRICE_MOD) if (dppo.iloc[-1].HISTO > 0): self.buysellsignal[fut2] = self.buysellsignal[fut2] * ( 1 + PRICE_MOD) else: self.buysellsignal[fut2] = self.buysellsignal[fut2] * ( 1 - PRICE_MOD) if (dppo.iloc[-1].SIGNAL > 0): self.buysellsignal[fut2] = self.buysellsignal[fut2] * ( 1 + PRICE_MOD) else: self.buysellsignal[fut2] = self.buysellsignal[fut2] * ( 1 - PRICE_MOD) except: self.buysellsignal[fut2] = 1 #print({ 'bid': best_bid, 'ask': best_ask }) return { 'bid': self.cal_average(best_bids), 'ask': self.cal_average(best_asks) }
# Target - predict how well the share will go over the next week prices["Target-future_week_gain"] = (prices["Adj Close"].shift(periods=-5) - prices["Adj Close"]) / prices["Adj Close"] # bollinger bands prices["Bollinger_upper"] = prices['20_Day_moving_av'] + 1.96 * prices['20_Day_stddev'] prices["Bollinger_lower"] = prices['20_Day_moving_av'] - 1.96 * prices['20_Day_stddev'] # small differences between upper and lower bands indicate that a sharp change is likely (chaos) # if the movement goes outside the bands, it is likely to continue # if the market tops or bottoms, first outside the band and then prices["_bollinger_linear_metric"] = (prices["Adj Close"] - prices['20_Day_moving_av']) / prices['20_Day_stddev'] prices["_bollinger_buy_flag"] = prices["_bollinger_linear_metric"] < -2 prices["_bollinger_sell_flag"] = prices["_bollinger_linear_metric"] > 2 prices["BB_upp-finta"], prices["BB_mid-finta"], prices["BB_low-finta"] = TA.BBANDS(ohlc) # indicates the 0.8 std dev over 10 periods to give a similar band to bollinger prices["MOBO"] = TA.MOBO(ohlc) # relative position of price within bands used for stochastics prices["Percent_b"] = TA.PERCENT_B(ohlc) # if candle is completely above the upper band, it will usually keep going up # In a rising market, we are more likely to hit the upper band than the lower band # this forces us to sell and makes us miss out on the gains # if it passes from the lower band across the middle it will keep going to hit the top band # Keltner channels are similar to BBands but with exponential moving averages and average true range # useful to identify overbought or oversold levels in a sideways market prices["Keltner_Channels_upp"], prices["Keltner_Channels_down"] = TA.KC(ohlc) # Donchian channels prices["DC_low"], prices["DC_mid"], prices["DC_upp"] = TA.DO(ohlc)
def on_message(ws, candle): global closes, do_i_own_coin, sells, buys, USD_avaliable, coin_avaliable, was_short_SMA_above is_candle_closed = True close = candle.iloc[-1]['close'] if is_candle_closed: closes.append(1) if len(closes) >= RSI_PERIOD: temp_RSI = TA.RSI(candle, RSI_PERIOD, 'close', True) rsi.append(temp_RSI.iat[-1]) if len(closes) >= RSI_PERIOD: temp_OBV = TA.OBV(candle, 'close') obv.append(temp_OBV.iat[-1]) if len(closes) >= 20: temp_bbands = TA.BBANDS(candle, 20, TA.SMA(candle, 20, "close"), "close", 2) #print(temp_bbands.iloc[-1]) temp = [ temp_bbands.iloc[-1].BB_LOWER, temp_bbands.iloc[-1].BB_MIDDLE, temp_bbands.iloc[-1].BB_UPPER ] bbands.append(temp) # paste the indicator in above this state so that these statements will be inside of it. Changes the true and false # values to represent when you would want the bot to buy or sell based on the indicators # is the closing price above the middle bbands above_mbband = False rsi_in_position = False obv_in_position = False #print(candle.iloc[-1]['close']) #print(bbands[-1][1]) if bbands[-1][1] < candle.iloc[-1]['close']: above_mbband = True if rsi[-1] > 60: rsi_in_position = True if obv[-1] > obv[-2] and obv[-1] > obv[-3] and obv[-1] > obv[-4]: obv_in_position = True if above_mbband and rsi_in_position and obv_in_position: if do_i_own_coin: #buy do_i_own_coin = not do_i_own_coin balance = coin_avaliable * close USD_avaliable = balance USD_avaliable = USD_avaliable * 0.999 coin_avaliable = 0 buys = buys + 1 on_close(6) #print(str(coin_avaliable) + str(USD_avaliable) + str(buys) + str(sells)) elif not above_mbband and not rsi_in_position and not obv_in_position: if not do_i_own_coin: #sell do_i_own_coin = not do_i_own_coin balance = (USD_avaliable * .999) / candle.iloc[-1]['open'] coin_avaliable = balance USD_avaliable = 0 sells = sells + 1 on_close(6)
#df.to_csv(path_or_buf="./data/" + ticker + ".csv" ) '''feature extraction''' df["sma5"] = TA.SMA(df, 5) df["sma7"] = TA.SMA(df, 7) df["sma14"] = TA.SMA(df, 14) df["ema5"] = TA.EMA(df, 5) df["ema7"] = TA.EMA(df, 7) df["ema9"] = TA.EMA(df, 9) df["ema13"] = TA.EMA(df, 13) df["ema20"] = TA.EMA(df, 20) macd = TA.MACD(df, 12, 26, 9) df["macd"] = macd.iloc[:, 0] df["macd_signal"] = macd.iloc[:, 1] df["rsi"] = TA.RSI(df, 14) bb = TA.BBANDS(df, 20) df["ubb"] = bb.iloc[:, 0] df["mbb"] = bb.iloc[:, 1] df["lbb"] = bb.iloc[:, 2] df["avgvol10"] = avg_volume(df, 10) df["incvol"] = inc_volume(df, 3) print(df.size) df = df.dropna() print(df.size) df["SP>SMA5"] = df["close"] > df["sma5"] df["SP>SMA7"] = df["close"] > df["sma7"] df["SP>SMA14"] = df["close"] > df["sma14"] df["SMA5>SMA14"] = df["sma5"] > df["sma14"] df["SP>EMA5"] = df["close"] > df["ema5"] df["SP>EMA7"] = df["close"] > df["ema7"] df["SP>EMA9"] = df["close"] > df["ema9"]
def on_message(ws, candle): global closes, do_i_own_coin, sells, buys, USD_avaliable, coin_avaliable is_candle_closed = True close = 1 if is_candle_closed: closes.append(float(close)) # 2 simple moving average if len(closes) >= MA_SHORT_PERIOD: np_closes = np.array(closes) temp_short_MA = TA.SMA(candle, MA_SHORT_PERIOD, 'close') short_MA.append(temp_short_MA.iat[-1]) if len(closes) >= MA_LONG_PERIOD: temp_long_MA = TA.SMA(candle, MA_LONG_PERIOD, 'close') long_MA.append(temp_long_MA.iat[-1]) # 2 exponential moving averages if len(closes) >= MA_SHORT_PERIOD: temp_short_EMA = TA.EMA(candle, MA_SHORT_PERIOD, 'close', True) short_EMA.append(temp_short_EMA.iat[-1]) if len(closes) >= MA_LONG_PERIOD: temp_long_EMA = TA.EMA(candle, MA_LONG_PERIOD, 'close', True) long_EMA.append(temp_long_EMA.iat[-1]) # Relative strength index if len(closes) >= RSI_PERIOD: temp_RSI = TA.RSI(candle, RSI_PERIOD, 'close', True) rsi.append(temp_RSI.iat[-1]) # Stochastic Oscillator K% if len(closes) >= STOCH_PERIOD: temp_stoch = TA.STOCH(candle, STOCH_PERIOD) stoch.append(temp_stoch.iat[-1]) # Stochastic Oscillator D% # using the same period as stoch if len(closes) >= STOCH_PERIOD: temp_stochd = TA.STOCHD(candle, 3, STOCH_PERIOD) stochd.append(temp_stochd.iat[-1]) # Ultimate Oscillator if len(closes) >= UO_PERIOD: temp_uo = TA.UO(candle, 'close') uo.append(temp_uo.iat[-1]) # On balance volume if len(closes) >= RSI_PERIOD: temp_OBV = TA.OBV(candle, 'close') obv.append(temp_OBV.iat[-1]) # Ichimoku Kinko Hyo (Ichimoku Cloud) if len(closes) >= 52: temp_cloud = TA.ICHIMOKU(candle, 9, 26, 52, 26) # tenkan_sen, kijun_sen, senkou_span_a, senkou_span_b, chikou_span cloud_diff = temp_cloud.iloc[-1].senkou_span_a - temp_cloud.iloc[ -1].SENKOU temp = [ temp_cloud.iloc[-1].TENKAN, temp_cloud.iloc[-1].KIJUN, cloud_diff, temp_cloud.iloc[-1].senkou_span_a, temp_cloud.iloc[-1].SENKOU, temp_cloud.iloc[-1].CHIKOU ] cloud.append(temp) # Bollinger Bands # This is taking a moving average as an input. Currently taking a simple MA but can take any MA if len(closes) >= 20: temp_bbands = TA.BBANDS(candle, 20, TA.SMA(candle, 20, "close"), "close", 2) temp = [ temp_bbands.iloc[-1].BB_LOWER, temp_bbands.iloc[-1].BB_MIDDLE, temp_bbands.iloc[-1].BB_UPPER ] bbands.append(temp) # Bollinger Bands # This is taking a moving average as an input. Currently taking a simple MA but can take any MA if len(closes) >= 22: temp_msd = TA.MSD(candle, 21, 1, "close") msd.append(temp_msd.iat[-1])
indicators = [x.upper() for x in indicators] data = pdr.DataReader(stock, 'yahoo', start, end) opens = data.Open.tolist() highs = data.High.tolist() lows = data.Low.tolist() closes = data.Close.tolist() volumes = data.Volume.tolist() ohlc = pd.DataFrame(list(zip(opens, highs, lows, closes, volumes)), columns=["open", "high", "low", "close", "volume"], index=data.index) if show_price == True: plt.plot(ohlc.close) plt.plot(TA.RSI(ohlc)) indicators.insert(0, 'Close Price') plt.legend(labels=[x for x in indicators], loc="best") plt.title(f'{stock} Indicators') plt.xlabel('Dates') plt.ylabel('Value') rcParams['figure.figsize'] = 15, 10 else: plt.plot(TA.BBANDS(ohlc)) plt.legend(labels=[x for x in indicators], loc="best") plt.title(f'{stock} Indicators') plt.xlabel('Dates') plt.ylabel('Value') rcParams['figure.figsize'] = 15, 10 plt.show()
def get_bbo(self, contract): # Get best b/o excluding own orders j = self.ohlcv[contract].json() fut2 = contract #print(contract) best_bids = [] best_asks = [] o = [] h = [] l = [] c = [] v = [] for b in j['result']['open']: o.append(b) for b in j['result']['high']: h.append(b) for b in j['result']['low']: l.append(b) for b in j['result']['close']: c.append(b) for b in j['result']['volume']: v.append(b) abc = 0 ohlcv2 = [] for b in j['result']['open']: ohlcv2.append([o[abc], h[abc], l[abc], c[abc], v[abc]]) abc = abc + 1 ddf = pd.DataFrame(ohlcv2, columns=['open', 'high', 'low', 'close', 'volume']) if 1 in self.directional: sleep(0) try: self.dsrsi = TA.STOCHRSI(ddf).iloc[-1] * 100 except: self.dsrsi = 50 ##print(self.dsrsi) # Get orderbook if 2 in self.volatility or 3 in self.price or 4 in self.quantity_switch: self.bands[fut2] = TA.BBANDS(ddf).iloc[-1] self.bbw[fut2] = (TA.BBWIDTH(ddf).iloc[-1]) #print(float(self.bands[fut2]['BB_UPPER'] - self.bands[fut2]['BB_LOWER'])) if (float(self.bands[fut2]['BB_UPPER'] - self.bands[fut2]['BB_LOWER'])) > 0: deltab = (self.get_spot() - self.bands[fut2]['BB_LOWER']) / ( self.bands[fut2]['BB_UPPER'] - self.bands[fut2]['BB_LOWER']) if deltab > 50: self.diffdeltab[fut2] = (deltab - 50) / 100 + 1 if deltab < 50: self.diffdeltab[fut2] = (50 - deltab) / 100 + 1 else: self.diffdeltab[fut2] = 25 / 100 + 1 if 3 in self.volatility: self.atr[fut2] = TA.ATR(ddf).iloc[-1] if 0 in self.price: ob = self.client.getorderbook(contract) bids = ob['bids'] asks = ob['asks'] ords = self.client.getopenorders(contract) bid_ords = [o for o in ords if o['direction'] == 'buy'] ask_ords = [o for o in ords if o['direction'] == 'sell'] best_bid = None best_ask = None err = 10**-(self.get_precision(contract) + 1) for b in bids: match_qty = sum([ o['quantity'] for o in bid_ords if math.fabs(b['price'] - o['price']) < err ]) if match_qty < b['quantity']: best_bid = b['price'] break for a in asks: match_qty = sum([ o['quantity'] for o in ask_ords if math.fabs(a['price'] - o['price']) < err ]) if match_qty < a['quantity']: best_ask = a['price'] break best_asks.append(best_ask) best_bids.append(best_bid) if 1 in self.price: dvwap = TA.VWAP(ddf) ##print(dvwap) tsz = self.get_ticksize(contract) try: bid = ticksize_floor(dvwap.iloc[-1], tsz) ask = ticksize_ceil(dvwap.iloc[-1], tsz) except: bid = ticksize_floor(self.get_spot(), tsz) ask = ticksize_ceil(self.get_spot(), tsz) #print( { 'bid': bid, 'ask': ask }) best_asks.append(best_ask) best_bids.append(best_bid) if 2 in self.quantity_switch: dppo = TA.PPO(ddf) self.buysellsignal[fut2] = 1 try: if (dppo.iloc[-1].PPO > 0): self.buysellsignal[fut2] = self.buysellsignal[fut2] * ( 1 + PRICE_MOD) else: self.buysellsignal[fut2] = self.buysellsignal[fut2] * ( 1 - PRICE_MOD) if (dppo.iloc[-1].HISTO > 0): self.buysellsignal[fut2] = self.buysellsignal[fut2] * ( 1 + PRICE_MOD) else: self.buysellsignal[fut2] = self.buysellsignal[fut2] * ( 1 - PRICE_MOD) if (dppo.iloc[-1].SIGNAL > 0): self.buysellsignal[fut2] = self.buysellsignal[fut2] * ( 1 + PRICE_MOD) else: self.buysellsignal[fut2] = self.buysellsignal[fut2] * ( 1 - PRICE_MOD) except: self.buysellsignal[fut2] = 1 ##print({ 'bid': best_bid, 'ask': best_ask }) return { 'bid': self.cal_average(best_bids), 'ask': self.cal_average(best_asks) }
for file in files: df = pandas.read_csv(file) df["sma5"] = TA.SMA(df, 5 * 390) df["sma7"] = TA.SMA(df, 7 * 390) df["sma14"] = TA.SMA(df, 14 * 390) df["ema5"] = TA.EMA(df, 5 * 390) df["ema7"] = TA.EMA(df, 7 * 390) df["ema9"] = TA.EMA(df, 9 * 390) df["ema13"] = TA.EMA(df, 13 * 390) df["ema20"] = TA.EMA(df, 20 * 390) macd = TA.MACD(df, 12 * 390, 26 * 390, 9 * 390) df["macd"] = macd.iloc[:, 0] df["macd_signal"] = macd.iloc[:, 1] df["rsi"] = TA.RSI(df, 14 * 390) bb = TA.BBANDS(df, 20 * 390) df["ubb"] = bb.iloc[:, 0] df["mbb"] = bb.iloc[:, 1] df["lbb"] = bb.iloc[:, 2] df["avgvol10"] = avg_volume(df, 10 * 390) df["incvol"] = inc_volume(df, 3) print(df.size) df = df.dropna() print(df.size) df["SP>SMA5"] = df["close"] > df["sma5"] df["SP>SMA7"] = df["close"] > df["sma7"] df["SP>SMA14"] = df["close"] > df["sma14"] df["SMA5>SMA14"] = df["sma5"] > df["sma14"] df["SP>EMA5"] = df["close"] > df["ema5"] df["SP>EMA7"] = df["close"] > df["ema7"] df["SP>EMA9"] = df["close"] > df["ema9"]