def TKE(dataframe, *, length=14, emaperiod=5): """ Source: https://www.tradingview.com/script/Pcbvo0zG/ Author: Dr Yasar ERDINC The calculation is simple: TKE=(RSI+STOCHASTIC+ULTIMATE OSCILLATOR+MFI+WIILIAMS %R+MOMENTUM+CCI)/7 Buy signal: when TKE crosses above 20 value Oversold region: under 20 value Overbought region: over 80 value Another usage of TKE is with its EMA , the default value is defined as 5 bars of EMA of the TKE line, Go long: when TKE crosses above EMALine Go short: when TKE crosses below EMALine Usage: `dataframe['TKE'], dataframe['TKEema'] = TKE1(dataframe)` """ import talib.abstract as ta df = dataframe.copy() # TKE=(RSI+STOCHASTIC+ULTIMATE OSCILLATOR+MFI+WIILIAMS %R+MOMENTUM+CCI)/7 df["rsi"] = ta.RSI(df, timeperiod=length) df['stoch'] = (100 * (df['close'] - df['low'].rolling(window=length).min()) / (df['high'].rolling(window=length).max() - df['low'].rolling(window=length).min())) df["ultosc"] = ta.ULTOSC(df, timeperiod1=7, timeperiod2=14, timeperiod3=28) df["mfi"] = ta.MFI(df, timeperiod=length) df["willr"] = ta.WILLR(df, timeperiod=length) df["mom"] = ta.MOM(df, timeperiod=length) df["cci"] = ta.CCI(df, timeperiod=length) df['TKE'] = df[['rsi', 'stoch', 'ultosc', 'mfi', 'willr', 'mom', 'cci']].mean(axis='columns') df["TKEema"] = ta.EMA(df["TKE"], timeperiod=emaperiod) return df["TKE"], df["TKEema"]
def compMFI(self): mfi = talib.MFI(self.high,self.low,self.close,self.tickVol,timeperiod=self.lookback) self.removeNullID(mfi) self.rawFeatures['MFI'] = mfi FEATURE_SIZE_DICT['MFI'] = 1 return
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 MFI_factor(self, df, timeperiod): return talib.MFI( df.loc[:, self.map_dict['high']].values, df.loc[:, self.map_dict['low']].values, df.loc[:, self.map_dict['close']].values, df.loc[:, self.map_dict['volume']].values, timeperiod)
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 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 mfi(candles: np.ndarray, period=14, sequential=False) -> Union[float, np.ndarray]: """ MFI - Money Flow Index :param candles: np.ndarray :param period: int - default=14 :param sequential: bool - default=False :return: float | np.ndarray """ if not sequential and len(candles) > 240: candles = candles[-240:] res = talib.MFI(candles[:, 3], candles[:, 4], candles[:, 2], candles[:, 5], timeperiod=period) if sequential: return res else: return None if np.isnan(res[-1]) else res[-1]
def mfi(): for i in range(len(ForexTraderSwitch.curr_pair_list)): close=(ForexTraderSwitch.curr_pair_history_data[i]['closeAsk'].values+\ ForexTraderSwitch.curr_pair_history_data[i]['closeBid'].values)/2 high=(ForexTraderSwitch.curr_pair_history_data[i]['highAsk'].values+\ ForexTraderSwitch.curr_pair_history_data[i]['highBid'].values)/2 low=(ForexTraderSwitch.curr_pair_history_data[i]['lowAsk'].values+\ ForexTraderSwitch.curr_pair_history_data[i]['lowBid'].values)/2 #open=(history['openAsk']+history['openBid'])/2 mfi = talib.MFI(high, low, close, history['volume'].values.astype(float), timeperiod=14) mfi_signal = mfi[-1] #print(mfi_signal) ForexTraderSwitch.signal[i, 12] = mfi_signal if mfi_signal > 70: #trader.create_buy_order(ticker,units) ForexTraderSwitch.order[i, 5, 1] = 1 elif mfi_signal < 30: #trader.create_sell_order(ticker,units) ForexTraderSwitch.order[i, 5, 2] = 1 else: #print('No trade made') ForexTraderSwitch.order[i, 5, 0] = 1
def on_preparing_data(self, data, **kwargs): """附加计算顺势指标""" real = 'mfi_{}'.format(self.timeperiod) data[real] = talib.MFI(data[self.col_high].values, data[self.col_low].values, data[self.col_close].values, data[self.col_vol].values, self.timeperiod)
def MFI(matrix, timeperiod=14): matrix['MFI' + str(timeperiod)] = talib.MFI(high=matrix['High'].values, low=matrix['Low'].values, close=matrix['1-Close'].values, volume=matrix['Volume'].values, timeperiod=timeperiod) return matrix
def get(self, idx): """Get the prediction for given idx. """ # No Information yet if (idx <= (self.lag + self.timeperiod)): return (0) # No Signal # Calculate mfi mfi = talib.MFI( self.series_high[(idx - self.lag - self.timeperiod):(idx - self.lag + 1)], self.series_low[(idx - self.lag - self.timeperiod):(idx - self.lag + 1)], self.series_close[(idx - self.lag - self.timeperiod):(idx - self.lag + 1)], self.series_volume[(idx - self.lag - self.timeperiod):(idx - self.lag + 1)], timeperiod=self.timeperiod)[-1] # Result if (mfi >= self.sell_threshold): result = -1 elif (mfi <= self.buy_thershold): result = 1 else: result = 0 # Return return (result)
def MFI(high=None, low=None, close=None, volume=None, timeperiod=None, verbose=False): """MFI Wrapper for talib.MFI for running unittests on ci/cd tools that do not provide talib .. code-block:: python real = MFI( high, low, close, volume, timeperiod=14) :param high: high list :param low: low list :param close: close list :param timeperiod: number of values in ``high``, ``low`` and ``close`` :param verbose: show logs """ if verbose: log.info('mfi - start') return talib.MFI(high, low, close, volume, timeperiod)
def _mfi(data): result = talib.MFI(data.highest_price.values, data.lowest_price.values, data.close_price, data.turnover_vol, timeperiod=14) return result.iloc[-1]
def test_mfi(self): """ Test Money Flow Index. """ q = qufilab.mfi(self.high, self.low, self.close, self.volume, 200) t = talib.MFI(self.high, self.low, self.close, self.volume, 200) np.testing.assert_allclose(q, t, rtol=self.tolerance)
def get_mfi(high, low, close, volume, period, max_period): mfi = talib.MFI(np.array(high), np.array(low), np.array(close), np.array(volume, dtype=np.double), timeperiod=period) return mfi[max_period:]
def buildTAindicators(stock_df): stock_df['REDORGREEN'] = stock_df.loc[:, 'Open'].subtract( stock_df.loc[:, 'Close']).apply(lambda x: 1 if x > 0 else 0).values stock_df['CANDLE_HEIGHT'] = stock_df.loc[:, 'Open'].subtract( stock_df.loc[:, 'Close']).values stock_df['NATR'] = ta.NATR(stock_df.loc[:, 'High'].values, stock_df.loc[:, 'Low'].values, stock_df.loc[:, 'Close'].values, 5) close = stock_df.loc[:, 'Close'].values high = stock_df.loc[:, 'High'].values low = stock_df.loc[:, 'Low'].values volume = pd.Series.astype(stock_df.loc[:, 'Volume'], dtype='double').values adx = ta.ADX(high, low, close, timeperiod=14) macd, macdsignal, macdhist = ta.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9) mfi = ta.MFI(high, low, close, volume, timeperiod=14) rsi = ta.RSI(close, timeperiod=14) beta = ta.BETA(high, low, timeperiod=5) stock_df['ADX'] = pd.Series(adx).values stock_df['MFI'] = pd.Series(mfi).values stock_df['RSI'] = pd.Series(rsi).values stock_df['MACD'] = pd.Series(macd).values stock_df['BETA'] = pd.Series(beta).values stock_df = stock_df.iloc[33:, :] return stock_df
def test_feature(date_after,bar,count): d1 = dt.datetime.now() engine = sa.create_engine('mysql+pymysql://gupiao:[email protected]/stocktool?charset=utf8') stock_df = pd.read_sql_query("select DISTINCT code from StockPrediction_stock_price;",engine) stock_s = pd.Series(stock_df['code']).sort_values() stock_list = stock_s.tolist() counter = 0 for i in stock_list: counter += 1 sql_price = "SELECT * FROM StockPrediction_stock_price WHERE code = "+i+" and date > '2018-04-01' ORDER BY date;"# 4月1日只是为了缩短预测时获取的数据量,应该是随着时间增加而增加的 price_data = pd.read_sql(sql_price,engine) if(price_data.empty): print(i) else: macd,macds,price_data['macdh'] =ta.MACD(price_data['close'].values, fastperiod=12, slowperiod=26, signalperiod=9) price_data['stoK'],price_data['stoD'] =ta.STOCH(price_data['high'].values,price_data['low'].values,price_data['close'].values) price_data['rsi'] =ta.RSI(price_data['close'].values) price_data['willR'] =ta.WILLR(price_data['high'].values,price_data['low'].values,price_data['close'].values) price_data['ultosc'] =ta.ULTOSC(price_data['high'].values,price_data['low'].values,price_data['close'].values) price_data['mfi'] =ta.MFI(price_data['high'].values,price_data['low'].values,price_data['close'].values,price_data['volume'].values) price_data.pop('id')# pandas算出结果后会多出一列 存入数据库会报错就pop掉 """ 判断是否下跌""" iD = pd.DataFrame(np.zeros((price_data.shape[0], 1)), columns=['down']) iD['down'] = False row_number = price_data.shape[0] for j in range(0,row_number): if(j<2): continue elif(price_data.iloc[j-2].high*0.95>price_data.iloc[j].open):#FIXME:两天前的最高价*0.95>预测日的开盘价 iD.iloc[j].down = True else: continue price_data.insert(price_data.shape[1],'down',iD) print(price_data[price_data.date>=dt.datetime.strptime(date_after,'%Y-%m-%d').date()]) price_data[price_data.date>=dt.datetime.strptime(date_after,'%Y-%m-%d').date()].to_sql('StockPrediction_stock_pred',engine,if_exists='append',index=False) bar.update(count+counter) # 最终手机提示 if(Notifi): d2 = dt.datetime.now() print("time used: ") print(d2 - d1) print_str = "\ntime used: " + str(d2 - d1) if(result is not None): msg = "done !\n" + print_str+"\nresult: "+str(result) else: msg = "done !\n" + print_str conn = http.client.HTTPSConnection("api.pushover.net:443") conn.request("POST", "/1/messages.json", urllib.parse.urlencode({ "token": "a22vgia8q7vszh4zromzgd2jgikxeh", "user": "******", "message": msg, "title": os.path.basename(__file__), }), {"Content-type": "application/x-www-form-urlencoded"}) conn.getresponse() return len(stock_list)
def run_indicators(symbol, file): try: if os.path.exists(file): # read file df = np.genfromtxt(file, delimiter=',') # run talib indicators using dataframe # create additional columns in the datafarame closePrice = df[:, 4] openPrice = df[:, 1] highPrice = df[:, 2] lowPrice = df[:, 3] volume = df[:, 5] sma = talib.SMA(closePrice) atr = talib.ATR(highPrice, lowPrice, closePrice) natr = talib.NATR(highPrice, lowPrice, closePrice) adx = talib.ADX(highPrice, lowPrice, closePrice) mfi = talib.MFI(highPrice, lowPrice, closePrice, volume) ppo = talib.PPO(closePrice, fastperiod=12, slowperiod=26, matype=0) rsi = talib.RSI(closePrice) slowk, slowd = talib.STOCH(highPrice, lowPrice, closePrice, fastk_period=14, slowk_period=3, slowd_period=3) macd, macdsignal, macdhist = talib.MACD(closePrice, fastperiod=12, slowperiod=26, signalperiod=9) # get ticker current price client = Client(os.environ.get('BINANCE_API_KEY'), os.environ.get('BINANCE_SECRET_KEY'), {"timeout": 100}) closing_price = client.get_symbol_ticker(symbol=symbol) # create crypto object crypto = {} crypto['ticker'] = symbol crypto['price'] = closing_price['price'] crypto['SMA14'] = sma[-1] crypto['ATR'] = atr[-1] crypto['NATR'] = natr[-1] crypto['ADX'] = adx[-1] crypto['MFI'] = mfi[-1] crypto['RSI'] = rsi[-1] crypto['STO'] = slowk[-1], slowd[-1] crypto['MACD'] = macd[-1] crypto['PPO'] = ppo[-1] else: crypto = {} crypto['ticker'] = symbol return crypto except Exception as e: print(str(e))
def calc_mfi(self, timeperiod=14): column = 'mfi' + str(timeperiod) self.stock[column] = ta.MFI(self.high, self.low, self.close, self.volume, timeperiod=timeperiod) return self.stock
def mfi(self, n: int, array: bool = False) -> Union[float, np.ndarray]: """ Money Flow Index. """ result = talib.MFI(self.high, self.low, self.close, self.volume, n) if array: return result return result[-1]
def ta_mfi(n, k_data): mfi = pd.DataFrame() mfi['mfi'] = ta.MFI(k_data.high, k_data.low, k_data.close, k_data.volume, timeperiod=n) return (mfi.round(2))
def test_mfi(): '''test TA.MFI''' mfi = TA.MFI(ohlc, 9) talib_mfi = talib.MFI(ohlc['high'], ohlc['low'], ohlc['close'], ohlc['volume'], 9) assert int(talib_mfi[-1]) == int(mfi.values[-1])
def mfi(self, n, array=False): """ Money Flow Index. """ result = talib.MFI(self.high, self.low, self.close, self.volume, n) if array: return result return result[-1]
def add_mfi(df): mfi = talib.MFI(df['high'].values, df['low'].values, df['close'].values, df['volume'].values, timeperiod=14) df['mfi'] = mfi return df
def calculate_mfi(df, period=14): df, data = reset_index(df) df['MFI'] = ta.MFI(df['High'], df['Low'], df['Close'], df['Volume'], timeperiod=period) return df
def MFI(self, timeperiod=14): real_data = np.array([self.df.high, self.df.low, self.df.close, self.df.volume], dtype='f8') mfi = talib.MFI(real_data[0], real_data[1], real_data[2], real_data[3], timeperiod=timeperiod) # return go.Scatter( # x=self.df.index, # y=mfi, # name='MFI' # ) return mfi
def mfiIndicator(self, am, paraDict): mfiPeriod = paraDict['bandPeriod'] mfiThreshold = paraDict['bPctThreshold'] mfiSignal = ta.MFI(am.high, am.low, am.close, am.volume, mfiPeriod) mfiStatus = 0 if mfiSignal[-1] > mfiThreshold: mfiStatus = 1 if mfiSignal[-1] < (100 - mfiThreshold): mfiStatus = -1 return mfiStatus, mfiSignal
def MFI(high, low, close, volume, timeperiod=14): ''' Money Flow Index 资金流量指标 分组: Momentum Indicator 动量指标 简介: 属于量价类指标,反映市场的运行趋势 real = MFI(high, low, close, volume, timeperiod=14) ''' return talib.MFI(high, low, close, volume, timeperiod)
def _get_indicators(security, open_name, close_name, high_name, low_name, volume_name): """ expand the features of the data through technical analysis across 26 different signals :param security: data which features are going to be expanded :param open_name: open price column name :param close_name: close price column name :param high_name: high price column name :param low_name: low price column name :param volume_name: traded volumn column name :return: expanded and extracted data """ open_price = security[open_name].values close_price = security[close_name].values low_price = security[low_name].values high_price = security[high_name].values volume = security[volume_name].values if volume_name else None security['MOM'] = talib.MOM(close_price) security['HT_DCPERIOD'] = talib.HT_DCPERIOD(close_price) security['HT_DCPHASE'] = talib.HT_DCPHASE(close_price) security['SINE'], security['LEADSINE'] = talib.HT_SINE(close_price) security['INPHASE'], security['QUADRATURE'] = talib.HT_PHASOR( close_price) security['ADXR'] = talib.ADXR(high_price, low_price, close_price) security['APO'] = talib.APO(close_price) security['AROON_UP'], _ = talib.AROON(high_price, low_price) security['CCI'] = talib.CCI(high_price, low_price, close_price) security['PLUS_DI'] = talib.PLUS_DI(high_price, low_price, close_price) security['PPO'] = talib.PPO(close_price) security['MACD'], security['MACD_SIG'], security[ 'MACD_HIST'] = talib.MACD(close_price) security['CMO'] = talib.CMO(close_price) security['ROCP'] = talib.ROCP(close_price) security['FASTK'], security['FASTD'] = talib.STOCHF( high_price, low_price, close_price) security['TRIX'] = talib.TRIX(close_price) security['ULTOSC'] = talib.ULTOSC(high_price, low_price, close_price) security['WILLR'] = talib.WILLR(high_price, low_price, close_price) security['NATR'] = talib.NATR(high_price, low_price, close_price) security['RSI'] = talib.RSI(close_price) security['EMA'] = talib.EMA(close_price) security['SAREXT'] = talib.SAREXT(high_price, low_price) # security['TEMA'] = talib.EMA(close_price) security['RR'] = security[close_name] / security[close_name].shift( 1).fillna(1) security['LOG_RR'] = np.log(security['RR']) if volume_name: security['MFI'] = talib.MFI(high_price, low_price, close_price, volume) # security['AD'] = talib.AD(high_price, low_price, close_price, volume) # security['OBV'] = talib.OBV(close_price, volume) security[volume_name] = np.log(security[volume_name]) security.drop([open_name, close_name, high_name, low_name], axis=1) security = security.dropna().astype(np.float32) return security
def get_SP500_4hrStateEvery1hour(self): while self.running: monthAgo = time.time() - 2419200 sp_df = self.get_Yahoo_Data('%5EGSPC', str(monthAgo).split('.')[0], '60m') moneyFlow = talib.MFI(sp_df, 14) print('last 10 values of latest 1hr Money Flow:') Trade = Query() self.db.update({'SP500_4hrMF': moneyFlow.values[-1:][0]}, Trade.type == 'current_state') time.sleep(3600)