def test_bop(self): """ Test Balance of Power (BOP). """ q = qufilab.bop(self.high, self.low, self.open, self.close) t = talib.BOP(self.open, self.high, self.low, self.close) np.testing.assert_allclose(q, t, rtol=self.tolerance)
def bop(self, opens, highs, lows, closes): """ Balance Of Power (Momentum Indicators) Inputs: prices: ['open', 'high', 'low', 'close'] Outputs: real :param open: :param high: :param low: :param close: :return: """ # nejdříve vyřízneme potřebnou délku # a převedeme na desetinné číslo. open = float(opens[-1]) high = float(highs[-1]) low = float(lows[-1]) close = float(closes[-1]) # převedeme na datová pole open = numpy.asarray((open, )) high = numpy.asarray((high, )) low = numpy.asarray((low, )) close = numpy.asarray((close, )) # Výsledek. result = talib.BOP(open, high, low, close) cutresult = float(result[0]) return cutresult
def bop( client, symbol, timeframe="6m", highcol="high", lowcol="low", closecol="close", volumecol="volume", ): """This will return a dataframe of Balance of power for the given symbol across the given timeframe Args: client (pyEX.Client): Client symbol (string): Ticker timeframe (string): timeframe to use, for pyEX.chart highcol (string): column to use to calculate lowcol (string): column to use to calculate closecol (string): column to use to calculate volumecol (string): column to use to calculate Returns: DataFrame: result """ df = client.chartDF(symbol, timeframe) x = t.BOP(df[highcol].values, df[lowcol].values, df[closecol].values, df[volumecol].values) return pd.DataFrame({ highcol: df[highcol].values, lowcol: df[lowcol].values, closecol: df[closecol].values, volumecol: df[volumecol].values, "bop": x, })
def momentum(self): adx = talib.ADX(self.high,self.low,self.close,self.period) adxr = talib.ADXR(self.high,self.low,self.close,self.period) apo = talib.APO(self.high,self.low,self.close,self.period) aroondown, aroonup = talib.AROON(self.high, self.low, period) aroonosc = talib.AROONOSC(self.high,self.low,self.period) bop = talib.BOP(self.opens,self.high,self.low,self.close) cci = talib.CCI(self.high,self.low,self.close,self.period) cmo = talib.CMO(self.close,self.period) dx = talib.DX(self.high,self.low,self.close,self.period) macd, macdsignal, macdhist = talib.MACD(self.close, fastperiod=period, slowperiod=period*5, signalperiod=period*2) macd1, macdsignal1, macdhist1 = talib.MACDEXT(self.close, fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0) macd2, macdsignal2, macdhist2 = talib.MACDFIX(self.close, signalperiod=9) mfi = talib.MFI(self.high, self.low, self.close, self.volume, timeperiod=14) minus_di = talib.MINUS_DI(self.high, self.low, self.close, timeperiod=14) minus_dm = talib.MINUS_DM(self.high, self.low, timeperiod=14) mom = talib.MOM(self.close, timeperiod=10) plus_di = talib.PLUS_DI(self.high, self.low, self.close, timeperiod=14) plus_dm = talib.PLUS_DM(self.high, self.low, timeperiod=14) ppo = talib.PPO(self.close, fastperiod=12, slowperiod=26, matype=0) roc = talib.ROC(self.close, timeperiod=10) rocp = talib.ROCP(self.close, timeperiod=10) rocr = talib.ROCR(self.close, timeperiod=10) rocr100 = talib.ROCR100(self.close, timeperiod=10) rsi = talib.RSI(self.close, timeperiod=14) slowk, slowd = talib.STOCH(self.high, self.low, self.close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) fastk, fastd = talib.STOCHF(self.high, self.low, self.close, fastk_period=5, fastd_period=3, fastd_matype=0) fastk1, fastd1 = talib.STOCHRSI(self.close, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0) trix = talib.TRIX(self.close, timeperiod=30) ultosc = talib.ULTOSC(self.high, self.low, self.close, timeperiod1=7, timeperiod2=14, timeperiod3=28) willr = talib.WILLR(self.high, self.low, self.close, timeperiod=14)
def add_indicators(df): high = df["HA_High"].values close = df["HA_Close"].values low = df["HA_Low"].values _open = df["HA_Open"].values volume = df["volume"].values.astype('uint32') df["APO"] = talib.APO(close, fastperiod=9, slowperiod=21, matype=0) df["APO"] = talib.APO(close, fastperiod=9, slowperiod=21, matype=0) df["aroondown"], df["aroonup"] = talib.AROON(high, low, timeperiod=14) df["BOP"] = talib.BOP(_open, high, low, close) df["CCI"] = talib.CCI(high, low, close, timeperiod=10) df["DX"] = talib.DX(high, low, close, timeperiod=10) df["MOM"] = talib.MOM(close, timeperiod=10) df["slowk"], df["slowd"] = talib.STOCH(high, low, close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) df["OBV"] = talib.OBV(close, np.asarray(volume, dtype='float')) df["ADOSC"] = talib.ADOSC(high, low, close, np.asarray(volume, dtype='float'), fastperiod=3, slowperiod=10) df["upperband"], df["middleband"], df["lowerband"] = talib.BBANDS( close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0) return df
def logic (ohlc, exchange="NSE"): inputs = {"open":np.array(ohlc.open.values), "high": np.array(ohlc.high.values), "low": np.array(ohlc.low.values), "close": np.array(ohlc.close.values), "volume": np.array(ohlc.volume.values).astype(float)} try: sma8 = talib.SMA(inputs["close"], 8) sma21 = talib.SMA(inputs["close"], 21) rsi = talib.RSI(inputs["close"], timeperiod=15) sma_rsi = talib.SMA(rsi,8) #natr = talib.NATR(inputs["high"],inputs["low"],inputs["close"], timeperiod=14) macd, macdsignal, macdhist = talib.MACDEXT(inputs["close"], fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0) ultosc = talib.ULTOSC(inputs["high"],inputs["low"],inputs["close"],timeperiod1=7, timeperiod2=14, timeperiod3=28) slowk, slowd = talib.STOCH(inputs["high"],inputs["low"],inputs["close"], 5, 3, 0, 3, 0) #obv = talib.OBV(inputs["close"], inputs["volume"]) bop = talib.SMA(talib.BOP(inputs["open"], inputs["high"],inputs["low"],inputs["close"]),5) data = pd.DataFrame({ "sma_rsi":sma_rsi,"slowk": slowk, "slowd": slowd,"rsi":rsi, "ultosc": ultosc, "macd": macd, "macdsignal": macdsignal,"macdhist":macdhist,# "obv":obv, "natr": natr, "bop":bop, "sma8":sma8, "sma21":sma21, }) except Exception as e: print(item + str(e) + " can't process") return data
def extract_features(data): high = data['High'] low = data['Low'] close = data['Close'] volume = data['Volume'] open_ = data['Open'] data['ADX'] = ta.ADX(high, low, close, timeperiod=19) data['CCI'] = ta.CCI(high, low, close, timeperiod=19) data['CMO'] = ta.CMO(close, timeperiod=14) data['MACD'], X, Y = ta.MACD(close, fastperiod=10, slowperiod=30, signalperiod=9) data['MFI'] = ta.MFI(high, low, close, volume, timeperiod=19) data['MOM'] = ta.MOM(close, timeperiod=9) data['ROCR'] = ta.ROCR(close, timeperiod=12) data['RSI'] = ta.RSI(close, timeperiod=19) data['STOCHSLOWK'], data['STOCHSLOWD'] = ta.STOCH(high, low, close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) data['TRIX'] = ta.TRIX(close, timeperiod=30) data['WILLR'] = ta.WILLR(high, low, close, timeperiod=14) data['OBV'] = ta.OBV(close, volume) data['TSF'] = ta.TSF(close, timeperiod=14) data['NATR'] = ta.NATR(high, low, close)#, timeperiod=14) data['ULTOSC'] = ta.ULTOSC(high, low, close) data['AROONOSC'] = ta.AROONOSC(high, low, timeperiod=14) data['BOP'] = ta.BOP(open_, high, low, close) data['LINEARREG'] = ta.LINEARREG(close) data['AP0'] = ta.APO(close, fastperiod=9, slowperiod=23, matype=1) data['TEMA'] = ta.TRIMA(close, 29) return data
def _set_df(self, df): for c in AssetColumns: if str(c) not in df.columns: raise RuntimeError( f"{c} column doesn't exist in the dataframe") df['datetime'] = pd.to_datetime(df['timestamp'], unit='s') df['month'] = df['datetime'].dt.month df['weekday'] = df['datetime'].dt.weekday df['hour'] = df['datetime'].dt.hour df = df.drop(['datetime', 'timestamp', 'index'], 1) df['sma'] = talib.SMA(df['close'], self.window) df['rsi'] = talib.RSI(df['close'], self.window) df['mom'] = talib.MOM(df['close'], self.window) df['bop'] = talib.BOP(df['open'], df['high'], df['low'], df['close']) df['aroonosc'] = talib.AROONOSC(df['high'], df['low'], self.window) self.min = df.min() self.max = df.max() self.df = df self.row_count = len(self.df.index) if self.row_count < EP_LEN: raise RuntimeError(f"not enought rows") # add balance, asset_held, net_worth at each timestamp n_features = (len(df.columns) * self.window) + 3 self.observation_space = spaces.Box(-np.inf, np.inf, shape=((n_features, )), dtype=np.float32)
def _compute_states(self): start = self.current_idx - self.lookback end = self.current_idx df = self._data.iloc[start:end, :] states = {} states['roc1'] = ta.ROC(df.close, timeperiod=5).iloc[-1] states['roc2'] = ta.ROC(df.close, timeperiod=20).iloc[-1] states['rsi1'] = ta.RSI(df.close, timeperiod=14).iloc[-1] states['rsi2'] = ta.RSI(df.close, timeperiod=28).iloc[-1] states['cci1'] = ta.CCI(df.high, df.low, df.close, timeperiod=14).iloc[-1] states['cci2'] = ta.CCI(df.high, df.low, df.close, timeperiod=28).iloc[-1] states['adx1'] = ta.ADX(df.high, df.low, df.close, timeperiod=14).iloc[-1] states['adx2'] = ta.ADX(df.high, df.low, df.close, timeperiod=28).iloc[-1] states['atr'] = ta.ATR(df.high, df.low, df.close, timeperiod=14).iloc[-1] states['aroon1'] = ta.AROONOSC(df.high, df.low, timeperiod=14).iloc[-1] states['aroon2'] = ta.AROONOSC(df.high, df.low, timeperiod=28).iloc[-1] states['bop'] = ta.BOP(df.open, df.high, df.low, df.close).iloc[-1] states['cmo'] = ta.CMO(df.close, timeperiod=14).iloc[-1] states['close'] = df.close.iloc[-1] states['date'] = df.index[-1] states['position'] = self.position states['entry_price'] = self.entry_price states['entry_date'] = self.entry_date return states
def getMomentumIndicators(df): high = df['High'] low = df['Low'] close = df['Close'] open = df['Open'] volume = df['Volume'] df['ADX'] = ta.ADX(high, low, close, timeperiod=14) df['SMA'] = ta.ADXR(high, low, close, timeperiod=14) df['APO'] = ta.APO(close, fastperiod=12, slowperiod=26, matype=0) df['AROONDOWN'], df['AROOONUP'] = ta.AROON(high, low, timeperiod=14) df['AROONOSC'] = ta.AROONOSC(high, low, timeperiod=14) df['BOP'] = ta.BOP(open, high, low, close) df['CCI'] = ta.CCI(high, low, close, timeperiod=14) df['CMO'] = ta.CMO(close, timeperiod=14) df['DX'] = ta.DX(high, low, close, timeperiod=14) df['MACD'], df['MACDSIGNAL'], df['MACDHIST'] = ta.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9) df['MFI'] = ta.MFI(high, low, close, volume, timeperiod=14) df['MINUS_DI'] = ta.MINUS_DI(high, low, close, timeperiod=14) df['MINUS_DM']= ta.MINUS_DM(high, low, timeperiod=14) df['MOM'] = ta.MOM(close, timeperiod=10) df['PLUS_DM'] =ta.PLUS_DM(high, low, timeperiod=14) df['PPO'] = ta.PPO(close, fastperiod=12, slowperiod=26, matype=0) df['ROC'] = ta.ROC(close, timeperiod=10) df['ROCP'] = ta.ROCP(close, timeperiod=10) df['ROCR'] = ta.ROCR(close, timeperiod=10) df['ROCR100'] = ta.ROCR100(close, timeperiod=10) df['RSI'] = ta.RSI(close, timeperiod=14) df['SLOWK'], df['SLOWD'] = ta.STOCH(high, low, close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) df['FASTK'], df['FASTD'] = ta.STOCHF(high, low, close, fastk_period=5, fastd_period=3, fastd_matype=0) df['FASTK2'], df['FASTD2'] = ta.STOCHRSI(close, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0) df['TRIX'] = ta.TRIX(close, timeperiod=30) df['ULTOSC'] = ta.ULTOSC(high, low, close, timeperiod1=7, timeperiod2=14, timeperiod3=28) df['WILLR'] = ta.WILLR(high, low, close, timeperiod=14)
def bop(self, array: bool = False): """ BOP. """ result = talib.BOP(self.open, self.high, self.low, self.close) if array: return result return result[-1]
def BOP(self): real_data = np.array([self.df.open, self.df.high, self.df.low, self.df.close], dtype='f8') bop = talib.BOP(real_data[0], real_data[1], real_data[2], real_data[3]) # return go.Scatter( # x=self.df.index, # y=bop, # name='BOP' # ) return bop
def bop(self, array: bool = False) -> Union[float, np.ndarray]: """ BOP. """ result = talib.BOP(self.open, self.high, self.low, self.close) if array: return result return result[-1]
def BOP(open, high, low, close): ''' Balance Of Power 均势 分组: Momentum Indicator 动量指标 简介: real = BOP(open, high, low, close) ''' return talib.BOP(open, high, low, close)
def _assemble_state(self): '''Here we can add other things such as indicators and times''' self._get_last_N_timebars() bars = [self.last5m, self.last1h, self.last1d] state = [] candles = { j: {k: np.array([]) for k in ['open', 'high', 'low', 'close']} for j in range(len(bars)) } for j, bar in enumerate(bars): for col in ['open', 'high', 'low', 'close']: candles[j][col] = np.asarray(bar[col]) state += (list(np.asarray(bar[col]))[-10:]) self.state = np.array([]) self.state = np.append(self.state, state) self.state = np.append(self.state, self.position) np.append(self.state, np.sign(self.pnl_sum)) self.state = np.append(self.state, self._time_of_day) self.state = np.append(self.state, self._day_of_week) for c in candles: try: sma1 = talib.SMA(candles[c]['close'], self.lkbk - 1)[-1] sma2 = talib.SMA(candles[c]['close'], self.lkbk - 8)[-1] self.state = np.append(self.state, (sma1 - sma2) / sma2) self.state = np.append(self.state, sma1) self.state = np.append( self.state, talib.RSI(candles[c]['close'], self.lkbk - 1)[-1]) self.state = np.append( self.state, talib.MOM(candles[c]['close'], self.lkbk - 1)[-1]) #self.state = np.append(self.state,talib.MACD(candles[c]['close'],fastperiod=11, slowperiod=22, signalperiod=9)[0][0]) self.state = np.append( self.state, talib.BOP(candles[c]['open'], candles[c]['high'], candles[c]['low'], candles[c]['close'])[-1]) #self.state = np.append(self.state,talib.ADXR(candles[c]['high'], # candles[c]['low'], # candles[c]['close'], # self.lkbk-3)[-1]) #self.state = np.append(self.state,talib.STOCH(candles[c]['high'], # candles[c]['low'], # candles[c]['close'],5,3,0,3,0)[-1][0]) self.state = np.append( self.state, talib.AROONOSC(candles[c]['high'], candles[c]['low'], self.lkbk - 3)[-1]) except: print(traceback.format_exc()) #print('-->',self.state) self.state = (np.array(self.state) - np.mean(self.state)) / np.std( self.state)
def bop(self, sym, frequency): if not self.kbars_ready(sym, frequency): return [] opens = self.open(sym, frequency) highs = self.high(sym, frequency) lows = self.low(sym, frequency) closes = self.close(sym, frequency) bop = ta.BOP(opens, highs, lows, closes) return bop
def get_momentum_studies(open, low, high, close, volume, df): # Momentum studies # https://mrjbq7.github.io/ta-lib/func_groups/momentum_indicators.html df['MACD'], df['MACD_SIGN'], df['MACD_HIST'] = talib.MACD( close, fastperiod=12, slowperiod=26, signalperiod=9) df['STOCH-SLOW-K'], df['STOCH-SLOW-D'] = talib.STOCH(high, low, close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) df['STOCH-FAST-K'], df['STOCH-FAST-D'] = talib.STOCHF(high, low, close, fastk_period=5, fastd_period=3, fastd_matype=0) df['STOCH-RSI-K'], df['STOCH-RSI-D'] = talib.STOCHRSI(close, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0) df['AROON-DOWN'], df['AROON-UP'] = talib.AROON(high, low, timeperiod=14) df["MINUS_DI"] = talib.MINUS_DI(high, low, close, timeperiod=14) df["MINUS_DM"] = talib.MINUS_DM(high, low, timeperiod=14) df["PLUS_DI"] = talib.PLUS_DI(high, low, close, timeperiod=14) df["PLUS_DM"] = talib.PLUS_DM(high, low, timeperiod=14) df["MOM"] = talib.MOM(close, timeperiod=10) df["MFI"] = talib.MFI(high, low, close, volume, timeperiod=14) df["ADX"] = talib.ADX(high, low, close, timeperiod=14) df["ADXR"] = talib.ADXR(high, low, close, timeperiod=14) df["APO"] = talib.APO(close, fastperiod=12, slowperiod=26, matype=0) df["AROONOSC"] = talib.AROONOSC(high, low, timeperiod=14) df["BOP"] = talib.BOP(open, high, low, close) df["CCI"] = talib.CCI(high, low, close, timeperiod=14) df["CMO"] = talib.CMO(close, timeperiod=14) df["DX"] = talib.DX(high, low, close, timeperiod=14) df["PPO"] = talib.PPO(close, fastperiod=12, slowperiod=26, matype=0) df["ROC"] = talib.ROC(close, timeperiod=10) df["RSI"] = talib.RSI(close, timeperiod=14) df["TRIX"] = talib.TRIX(close, timeperiod=30) df["ULT"] = talib.ULTOSC(high, low, close, timeperiod1=7, timeperiod2=14, timeperiod3=28) df["WILLR"] = talib.WILLR(high, low, close, timeperiod=14)
def handle_data(context): # 获取历史数据, 取后bop_window根bar hist = context.data.get_price(context.security, count=context.user_data.bop_window * 10, frequency=context.frequency) if len(hist.index) < context.user_data.bop_window * 10: context.log.warn("bar的数量不足, 等待下一根bar...") return # 历史收盘价 hist_open = np.array(hist["open"]) hist_high = np.array(hist["high"]) hist_low = np.array(hist["low"]) hist_close = np.array(hist["close"]) # 初始化买入/卖出信号 long_signal_triggered = False short_signal_triggered = False # 计算AD值 bop = talib.BOP(hist_open, hist_high, hist_low, hist_close) # 产生买入/卖出信号 if bop[-1] > 0: long_signal_triggered = True elif bop[-1] < 0: short_signal_triggered = True # 有卖出信号,且持有仓位,则市价单全仓卖出 if short_signal_triggered: if context.account.huobi_cny_btc >= HUOBI_CNY_BTC_MIN_ORDER_QUANTITY: context.log.info("正在卖出 %s" % context.security) context.log.info("卖出数量为 %s" % context.account.huobi_cny_btc) context.order.sell_limit(context.security, quantity=str( context.account.huobi_cny_btc), price=str(hist_close[-1] * 0.98)) else: context.log.info("仓位不足,无法卖出") # 有买入信号,且持有现金,则市价单全仓买入 elif long_signal_triggered: if context.account.huobi_cny_cash >= HUOBI_CNY_BTC_MIN_ORDER_CASH_AMOUNT: context.log.info("正在买入 %s" % context.security) context.log.info("下单金额为 %s 元" % context.account.huobi_cny_cash) context.order.buy_limit( context.security, quantity=str(context.account.huobi_cny_cash / hist_close[-1] * 0.98), price=str(hist_close[-1] * 1.02)) else: context.log.info("现金不足,无法下单") else: context.log.info("无交易信号,进入下一根bar")
def bop(candles: np.ndarray, sequential: bool = False) -> Union[float, np.ndarray]: """ BOP - Balance Of Power :param candles: np.ndarray :param sequential: bool - default=False :return: float | np.ndarray """ candles = slice_candles(candles, sequential) res = talib.BOP(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2]) return res if sequential else res[-1]
def test_bop(self): result = pandas_ta.bop(self.open, self.high, self.low, self.close) self.assertIsInstance(result, Series) self.assertEqual(result.name, 'BOP') try: expected = tal.BOP(self.open, self.high, self.low, self.close) pdt.assert_series_equal(result, expected, check_names=False) except AssertionError as ae: try: corr = pandas_ta.utils.df_error_analysis(result, expected, col=CORRELATION) self.assertGreater(corr, CORRELATION_THRESHOLD) except Exception as ex: error_analysis(result, CORRELATION, ex)
def generateIndicatorBOP(dictDataSpec): """ https://www.investopedia.com/articles/technical/02/041002.asp """ df = dictDataSpec['df'] sReal = pd.Series(talib.BOP(df.Open.values, df.High.values, df.Low.values, df.Close.values), index=df.index) sIndicator = sReal.apply(lambda x: np.nan) print sReal.describe() ThresholdUpper = 0.8 ThresholdLower = -0.8 sIndicator[(sReal > ThresholdUpper)&(sReal.shift(1) < ThresholdUpper)] = 1 sIndicator[(sReal < ThresholdLower)&(sReal.shift(1) > ThresholdLower)] = -1 return sIndicator
def add_BOP(self, type='histogram', color='tertiary', **kwargs): """Balance of Power.""" if not self.has_OHLC: raise Exception() utils.kwargs_check(kwargs, VALID_TA_KWARGS) if 'kind' in kwargs: type = kwargs['kind'] name = 'BOP' self.sec[name] = dict(type=type, color=color) self.ind[name] = talib.BOP(self.df[self.op].values, self.df[self.hi].values, self.df[self.lo].values, self.df[self.cl].values)
def get_additional_factors(open, high, low, close, volume): # Overlap Studies Functions mat = get_all_factors(open, high, low, close, volume) mat = np.column_stack((mat, talib.HT_TRENDLINE(close))) ## close mat = np.column_stack((mat, talib.KAMA(close, timeperiod=30))) ##close #Momentum Indicator Functions mat = np.column_stack((mat, talib.ADX(high, low, close, timeperiod=14))) mat = np.column_stack((mat, talib.ADXR(high, low, close, timeperiod=14))) mat = np.column_stack( (mat, talib.APO(close, fastperiod=12, slowperiod=26, matype=0))) mat = np.column_stack((mat, talib.AROONOSC(high, low, timeperiod=14))) mat = np.column_stack((mat, talib.BOP(open, high, low, close))) mat = np.column_stack((mat, talib.MOM(close, timeperiod=10))) #Volume Indicator Functions mat = np.column_stack((mat, talib.AD(high, low, close, volume))) mat = np.column_stack( (mat, talib.ADOSC(high, low, close, volume, fastperiod=3, slowperiod=10))) mat = np.column_stack((mat, talib.OBV(close, volume))) #Volatility Indicator Functions mat = np.column_stack((mat, talib.NATR(high, low, close, timeperiod=14))) mat = np.column_stack((mat, talib.TRANGE(high, low, close))) #Price Transform Functions mat = np.column_stack((mat, talib.AVGPRICE(open, high, low, close))) mat = np.column_stack((mat, talib.MEDPRICE(high, low))) mat = np.column_stack((mat, talib.TYPPRICE(high, low, close))) mat = np.column_stack((mat, talib.WCLPRICE(high, low, close))) #Cycle Indicator Functions mat = np.column_stack((mat, talib.HT_DCPERIOD(close))) mat = np.column_stack((mat, talib.HT_DCPHASE(close))) mat = np.column_stack((mat, talib.HT_TRENDMODE(close))) # 20 return mat
def init_state(indata, test=False): openn = indata['open'].values close = indata['close'].values high = indata['high'].values low = indata['low'].values volume = indata['volume'].values diff = np.diff(close) diff = np.insert(diff, 0, 0) sma30 = talib.SMA(close, 30) sma60 = talib.SMA(close, timeperiod=60) rsi = talib.RSI(close, timeperiod=14) atr = talib.ATR(high, low, close, timeperiod=14) trange = talib.TRANGE(high, low, close) macd, macdsignal, macdhist = talib.MACD(close, 12, 26, 9) upper, middle, lower = talib.BBANDS(close, 20, 2, 2) ema = talib.EMA(close, 30) ma = talib.MA(close, 30) wma = talib.WMA(close, timeperiod=30) tema = talib.TEMA(close, 30) obv = talib.OBV(close, np.asarray(volume, dtype='float')) adx = talib.ADX(high, low, close, 14) apo = talib.APO(close, 12, 2, 0) bop = talib.BOP(openn, high, low, close) mom = talib.MOM(close,10) ppo = talib.PPO(close, 12, 26, 0) slowk, slowd = talib.STOCH(high, low, close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) ad = talib.AD(high, low, close, np.asarray(volume, dtype='float')) wcl = talib.WCLPRICE(high, low, close) #--- Preprocess data xdata = np.column_stack((close, diff, sma30, sma60, rsi, atr, macd, macdsignal, macdhist, lower, middle, upper, ema, ma, wma, adx, apo, bop, mom, ppo, slowk, slowd, trange, wcl)) xdata = np.nan_to_num(xdata) if test == False: scaler = preprocessing.StandardScaler() xdata = np.expand_dims(scaler.fit_transform(xdata), axis=1) joblib.dump(scaler, 'data/scaler.pkl') elif test == True: scaler = joblib.load('data/scaler.pkl') xdata = np.expand_dims(scaler.fit_transform(xdata), axis=1) state = xdata[0:1, 0:1, :] return state, xdata, close
def bop(candles: np.ndarray, sequential=False) -> Union[float, np.ndarray]: """ BOP - Balance Of Power :param candles: np.ndarray :param sequential: bool - default=False :return: float | np.ndarray """ if not sequential and len(candles) > 240: candles = candles[-240:] res = talib.BOP(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2]) if sequential: return res else: return None if np.isnan(res[-1]) else res[-1]
def add_BOP(self, type="histogram", color="tertiary", **kwargs): """Balance of Power.""" if not self.has_OHLC: raise Exception() utils.kwargs_check(kwargs, VALID_TA_KWARGS) if "kind" in kwargs: type = kwargs["kind"] name = "BOP" self.sec[name] = dict(type=type, color=color) self.ind[name] = talib.BOP( self.df[self.op].values, self.df[self.hi].values, self.df[self.lo].values, self.df[self.cl].values, )
def bop(data, high_col='High', low_col='Low', close_col='Close', vol_col='Volume', open_col='Open', fillna=False): high = data[high_col] low = data[low_col] close = data[close_col] open_ = data[open_col] real = talib.BOP(open_, high, low, close) if fillna: real = real.replace([np.inf, -np.inf], np.nan).fillna(0) return pd.Series(real, name='bop')
def generate_tech_data(stock, open_name, close_name, high_name, low_name): open_price = stock[open_name].values close_price = stock[close_name].values low_price = stock[low_name].values high_price = stock[high_name].values data = pd.DataFrame(stock) data['MOM'] = talib.MOM(close_price) data['SMA'] = talib.SMA(close_price) data['HT_DCPERIOD'] = talib.HT_DCPERIOD(close_price) data['HT_DCPHASE'] = talib.HT_DCPHASE(close_price) data['sine'], data['leadsine'] = talib.HT_SINE(close_price) data['inphase'], data['quadrature'] = talib.HT_PHASOR(close_price) data['HT_TRENDMODE'] = talib.HT_TRENDMODE(close_price) data['SAREXT'] = talib.SAREXT(high_price, low_price) data['ADX'] = talib.ADX(high_price, low_price, close_price) data['ADXR'] = talib.ADX(high_price, low_price, close_price) data['APO'] = talib.APO(close_price) data['AROON_UP'], data['AROON_DOWN'] = talib.AROON(high_price, low_price) data['AROONOSC'] = talib.AROONOSC(high_price, low_price) data['BOP'] = talib.BOP(open_price, high_price, low_price, close_price) data['CCI'] = talib.CCI(high_price, low_price, close_price) data['PLUS_DI'] = talib.PLUS_DI(high_price, low_price, close_price) data['PLUS_DM'] = talib.PLUS_DM(high_price, low_price) data['PPO'] = talib.PPO(close_price) data['macd'], data['macd_sig'], data['macd_hist'] = talib.MACD(close_price) data['RSI'] = talib.RSI(close_price) data['CMO'] = talib.CMO(close_price) data['ROC'] = talib.ROC(close_price) data['ROCP'] = talib.ROCP(close_price) data['ROCR'] = talib.ROCR(close_price) data['slowk'], data['slowd'] = talib.STOCH(high_price, low_price, close_price) data['fastk'], data['fastd'] = talib.STOCHF(high_price, low_price, close_price) data['TRIX'] = talib.TRIX(close_price) data['ULTOSC'] = talib.ULTOSC(high_price, low_price, close_price) data['WILLR'] = talib.WILLR(high_price, low_price, close_price) data['NATR'] = talib.NATR(high_price, low_price, close_price) data['TRANGE'] = talib.TRANGE(high_price, low_price, close_price) data = data.drop([open_name, close_name, high_name, low_name], axis=1) data = data.dropna() return data
def bop(candles: np.ndarray, sequential: bool = False) -> Union[float, np.ndarray]: """ BOP - Balance Of Power :param candles: np.ndarray :param sequential: bool - default=False :return: float | np.ndarray """ warmup_candles_num = get_config('env.data.warmup_candles_num', 240) if not sequential and len(candles) > warmup_candles_num: candles = candles[-warmup_candles_num:] res = talib.BOP(candles[:, 1], candles[:, 3], candles[:, 4], candles[:, 2]) if sequential: return res else: return None if np.isnan(res[-1]) else res[-1]
def test_BOP(self): self.env.add_operator('bop', { 'operator': OperatorBOP, }) string = 'bop(open, high, low, close)' gene = self.env.parse_string(string) df = gene.eval(self.env, self.dates[14], self.dates[15]) ser0, ser1 = df.iloc[0], df.iloc[1] o = self.env.get_data_value('open').values h = self.env.get_data_value('high').values l = self.env.get_data_value('low').values c = self.env.get_data_value('close').values res0, res1 = [], [] for i in ser0.index: res = talib.BOP(o[:15 + 1, i], h[:15 + 1, i], l[:15 + 1, i], c[:15 + 1, i]) val0, val1 = res[-2], res[-1] res0.append(ser0[i] == val0) res1.append(ser1[i] == val1) self.assertTrue(all(res0) and all(res1))