def macdfix(close_ts, signalperiod=9): # fixed fastperiod=12 and slowperiod=26 import talib close_np = close_ts.cpu().detach().numpy() close_df = pd.DataFrame(close_np) DIF = close_df.apply(lambda x: talib.MACDFIX(x, signalperiod=9)[0]) DEA = close_df.apply(lambda x: talib.MACDFIX(x, signalperiod=9)[1]) MACD = close_df.apply(lambda x: talib.MACDFIX(x, signalperiod=9)[2]) DIF_ts = torch.tensor(DIF.values, dtype=close_ts.dtype, device=close_ts.device) DEA_ts = torch.tensor(DEA.values, dtype=close_ts.dtype, device=close_ts.device) MACD_ts = torch.tensor(MACD.values, dtype=close_ts.dtype, device=close_ts.device) return DIF_ts, DEA_ts, MACD_ts
def MovingAverageConvergenceDivergence(self, fastperiod=12, slowperiod=26, signalperiod=9): """ MACD - Moving Average Convergence/Divergence Parameters ---------- fastperiod : TYPE, optional DESCRIPTION. The default is 12. slowperiod : TYPE, optional DESCRIPTION. The default is 26. signalperiod : TYPE, optional DESCRIPTION. The default is 9. Returns ------- df : TYPE DESCRIPTION. """ df = pd.DataFrame() df['macd'], df['signal'], df['history'] = ta.MACDFIX( self.data.close, 9) return df[-30:]
def compMACDFIX(self): macd,ms,mc = talib.MACDFIX(self.close,signalperiod=self.lookback) self.removeNullID(macd) self.rawFeatures['MACD'] = macd FEATURE_SIZE_DICT['MACD'] = 1 return
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 MACDFIX(Close, signalperiod=9): macd, macdsignal, macdhist = pd.DataFrame(), pd.DataFrame( ), pd.DataFrame() for i in Close.columns: macd[i], macdsignal[i], macdhist[i] = ta.MACDFIX( Close[i], signalperiod) return macd, macdsignal, macdhist
def MACDFIX(self, signalperiod=9): real_data = np.array([self.df.close], dtype='f8') # macd, macdsignal, macdhist = talib.MACDFIX(real_data[0], signalperiod=signalperiod) # return go.Scatter( # x=self.df.index, # y=macd, # name='MACDFIX' # ) return talib.MACDFIX(real_data[0], signalperiod=signalperiod)
def macd_vs_signal(closes): closes = np.array(list(closes), dtype=float) macd = talib.MACDFIX(closes) if macd[0][-1] > macd[1][-1]: ret_val = int(1) else: ret_val = int(0) return ret_val
def MACDFIX(close, signalperiod=9): ''' Moving Average Convergence/Divergence Fix 12/26 分组: Momentum Indicator 动量指标 简介: macd, macdsignal, macdhist = MACDFIX(close, signalperiod=9) ''' return talib.MACDFIX(close, signalperiod)
def get_macdfix(ohlc): # MACD (先行 12 日移動平均、遅行 26 日移動平均、 9 日シグナル線) を求める macd, macdsignal, macdhist = ta.MACDFIX(ohlc['4_close'], signalperiod=9) ohlc = ohlc.assign( macdfix=macd , macdsignalfix=macdsignal , macdhistfix=macdhist ) return ohlc
def get_quota(self): #stock_amount = cral_CNstock_order_ana.main() close = self.__df['close'] high_prices = self.__df['high'].values low_prices = self.__df['low'].values close_prices = close.values ma5 = talib.MA(close_prices,5) ma10 = talib.MA(close_prices,10) ma20 = talib.MA(close_prices,20) ma30 = talib.MA(close_prices,30) K, D = talib.STOCH(high_prices,low_prices,close_prices, fastk_period=9, slowk_period=3) J = K * 3 - D * 2 sar = talib.SAR(high_prices, low_prices, acceleration=0.05, maximum=0.2) sar = pd.DataFrame(sar-close) sar.index = self.__df.date atr = talib.ATR(high_prices,low_prices,close_prices) natr = talib.NATR(high_prices,low_prices,close_prices) trange = talib.TRANGE(high_prices,low_prices,close_prices) cci = talib.CCI(high_prices,low_prices,close_prices,14) dif, dea, bar = talib.MACDFIX(close_prices) bar = bar * 2 df_all = self.__df.drop(['code','open','low', 'high','volume'],axis=1).set_index('date') df_all.insert(0,'ma5',ma5) df_all.insert(0,'ma10',ma10) df_all.insert(0,'ma20',ma20) df_all.insert(0,'ma30',ma30) df_all.insert(0,'K',K) df_all.insert(0,'D',D) df_all.insert(0,'J',J) df_all.insert(0,'cci',cci) df_all.insert(0,'bar',bar) df_all.insert(0,'dif',dif) df_all.insert(0,'dea',dea) df_all.insert(0,'sar',sar) #df_all = pd.concat([df_all,stock_amount],axis=1) df_yesterday = df_all.T index_c = df_all.index added = [np.nan] * len(df_all.columns) df_yesterday.insert(0, len(df_yesterday.columns), added) df_yesterday = df_yesterday.T df_yesterday = df_yesterday.drop(df_all.index[len(df_all.index)-1]) df_yesterday.insert(0, 'index_c', index_c) df_yesterday = df_yesterday.set_index('index_c') df_dif = df_all - df_yesterday df_dif_close_plus_one_day = df_dif.copy() for i in range(len(df_dif_close_plus_one_day['close'])-1): df_dif_close_plus_one_day['close'][i] = df_dif_close_plus_one_day['close'][i+1] df_dif_close_plus_one_day['close'][len(df_dif_close_plus_one_day['close'])-1] = np.nan df_dif = df_dif.dropna(axis=0,how='any') df_dif_close_plus_one_day = df_dif_close_plus_one_day.dropna(axis=0,how='any') return df_dif, df_dif_close_plus_one_day
def tech_indicator(self) -> pd.DataFrame: cp = self.df.copy() close = cp.close.values open_price = cp.close.values high = cp.close.values low = cp.low.values volume = cp.volume.values cp['SMA_5'] = talib.SMA(close, 5) cp['upper'], cp['middle'], cp['low'] = talib.BBANDS(close, matype=MA_Type.T3) cp['slowk'], cp['slowd'] = talib.STOCH(high, low, close, fastk_period=9, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) cp['slowk_slowd'] = cp['slowk'] - cp['slowd'] cp['CCI'] = talib.CCI(high, low, close, timeperoid=10) cp['DIF'], cp['DEA'], cp['HIST'] = talib.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9) cp['BAR'] = (cp['DIF'] - cp['DEA']) * 2 cp['macdext'], cp['signal_xt'], cp['hist_xt'] = talib.MACDFIX( close, signalperiod=9) cp['RSI'] = talib.RSI(close, timepriod=14) cp['AROON_DOWN'], cp['AROON_UP'] = talib.AROON(high, low, timeperiod=14) cp['upperband'], cp['middleband'], cp['lowerband'] = talib.BBANDS( close, timepriod=5, nbdevup=2, nbdevdn=2, matype=0) cp['AD'] = talib.AD(high, low, close, volume) cp['ADX'] = talib.ADX(high, low, close, timeperiod=14) cp['ADXR'] = talib.ADXR(high, low, close, timeperiod=14) cp['OBV'] = talib.OBV(close, volume) return cp
def corr_rate_calc(code): df = pd.read_sql( 'select * from day_k_data where code="' + code + '" order by date asc;', engine) ma5 = talib.MA(df['close'].values, 5) ma10 = talib.MA(df['close'].values, 10) ma20 = talib.MA(df['close'].values, 20) ma30 = talib.MA(df['close'].values, 30) K, D = talib.STOCH(df['high'].values, df['low'].values, df['close'].values, fastk_period=9, slowk_period=3) J = K * 3 - D * 2 atr = talib.ATR(df['high'].values, df['low'].values, df['close'].values) natr = talib.NATR(df['high'].values, df['low'].values, df['close'].values) trange = talib.TRANGE(df['high'].values, df['low'].values, df['close'].values) cci = talib.CCI(df['high'].values, df['low'].values, df['close'].values, 14) dif, dea, bar = talib.MACDFIX(df['close'].values) bar = bar * 2 df = df.drop(['code', 'open', 'low', 'high'], axis=1).set_index('date') df.insert(0, 'ma5', ma5) df.insert(0, 'ma10', ma10) df.insert(0, 'ma20', ma20) df.insert(0, 'ma30', ma30) df.insert(0, 'K', K) df.insert(0, 'D', D) df.insert(0, 'J', J) df.insert(0, 'cci', cci) df.insert(0, 'bar', bar) df.insert(0, 'dif', dif) df.insert(0, 'dea', dea) df_yesterday = df.T index_c = df.index added = [0] * len(df.columns) df_yesterday.insert(0, len(df_yesterday.columns), added) df_yesterday = df_yesterday.T df_yesterday = df_yesterday.drop(df.index[len(df.index) - 1]) df_yesterday.insert(0, 'index_c', index_c) df_yesterday = df_yesterday.set_index('index_c') dfd = df - df_yesterday return dfd.corr()
def macd3(): 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 DIF, DEA, BAR = talib.MACDFIX(close, signalperiod=9) #print("DIF %s DEA %s" % (DIF[-1], DEA[-1])) ForexTraderSwitch.signal[i, 6] = DEA[-2] ForexTraderSwitch.signal[i, 7] = DEA[-1] ForexTraderSwitch.signal[i, 8] = DIF[-2] ForexTraderSwitch.signal[i, 9] = DIF[-1] if DIF[-1] > 0 and DEA[-1] > 0 and DIF[-2] < DEA[-2] and DIF[ -1] > DEA[-1]: #trader.create_buy_order(ticker,units) ForexTraderSwitch.order[i, 4, 1] = 1 elif DIF[-1] < 0 and DEA[-1] < 0 and DIF[-2] > DEA[-2] and DIF[ -1] < DEA[-1]: #trader.create_sell_order(ticker,units) ForexTraderSwitch.order[i, 4, 2] = 1 else: #print("No trade made") ForexTraderSwitch.order[i, 4, 0] = 1
def corr_calc(code): df = pd.read_sql( 'select * from day_k_data where code="' + code + '" order by date asc;', engine) ma5 = talib.MA(df['close'].values, 5) ma10 = talib.MA(df['close'].values, 10) ma20 = talib.MA(df['close'].values, 20) ma30 = talib.MA(df['close'].values, 30) K, D = talib.STOCH(df['high'].values, df['low'].values, df['close'].values, fastk_period=9, slowk_period=3) J = K * 3 - D * 2 atr = talib.ATR(df['high'].values, df['low'].values, df['close'].values) natr = talib.NATR(df['high'].values, df['low'].values, df['close'].values) trange = talib.TRANGE(df['high'].values, df['low'].values, df['close'].values) cci = talib.CCI(df['high'].values, df['low'].values, df['close'].values, 14) dif, dea, bar = talib.MACDFIX(df['close'].values) bar = bar * 2 df = df.drop(['code', 'open', 'low', 'high'], axis=1).set_index('date') #df = df.drop(['code'],axis=1).set_index('date') df.insert(0, 'ma5', ma5) df.insert(0, 'ma10', ma10) df.insert(0, 'ma20', ma20) df.insert(0, 'ma30', ma30) df.insert(0, 'K', K) df.insert(0, 'D', D) df.insert(0, 'J', J) df.insert(0, 'cci', cci) df.insert(0, 'bar', bar) df.insert(0, 'dif', dif) df.insert(0, 'dea', dea) print df.corr()
def calculate(self, para): self.t = self.inputdata[:, 0] self.op = self.inputdata[:, 1] self.high = self.inputdata[:, 2] self.low = self.inputdata[:, 3] self.close = self.inputdata[:, 4] #adjusted close self.close1 = self.inputdata[:, 5] self.volume = self.inputdata[:, 6] #Overlap study #Overlap Studies #Overlap Studies if para is 'BBANDS': #Bollinger Bands upperband, middleband, lowerband = ta.BBANDS(self.close, timeperiod=self.tp, nbdevup=2, nbdevdn=2, matype=0) self.output = [upperband, middleband, lowerband] elif para is 'DEMA': #Double Exponential Moving Average self.output = ta.DEMA(self.close, timeperiod=self.tp) elif para is 'EMA': #Exponential Moving Average self.output = ta.EMA(self.close, timeperiod=self.tp) elif para is 'HT_TRENDLINE': #Hilbert Transform - Instantaneous Trendline self.output = ta.HT_TRENDLINE(self.close) elif para is 'KAMA': #Kaufman Adaptive Moving Average self.output = ta.KAMA(self.close, timeperiod=self.tp) elif para is 'MA': #Moving average self.output = ta.MA(self.close, timeperiod=self.tp, matype=0) elif para is 'MAMA': #MESA Adaptive Moving Average mama, fama = ta.MAMA(self.close, fastlimit=0, slowlimit=0) elif para is 'MAVP': #Moving average with variable period self.output = ta.MAVP(self.close, periods=10, minperiod=self.tp, maxperiod=self.tp1, matype=0) elif para is 'MIDPOINT': #MidPoint over period self.output = ta.MIDPOINT(self.close, timeperiod=self.tp) elif para is 'MIDPRICE': #Midpoint Price over period self.output = ta.MIDPRICE(self.high, self.low, timeperiod=self.tp) elif para is 'SAR': #Parabolic SAR self.output = ta.SAR(self.high, self.low, acceleration=0, maximum=0) elif para is 'SAREXT': #Parabolic SAR - Extended self.output = ta.SAREXT(self.high, self.low, startvalue=0, offsetonreverse=0, accelerationinitlong=0, accelerationlong=0, accelerationmaxlong=0, accelerationinitshort=0, accelerationshort=0, accelerationmaxshort=0) elif para is 'SMA': #Simple Moving Average self.output = ta.SMA(self.close, timeperiod=self.tp) elif para is 'T3': #Triple Exponential Moving Average (T3) self.output = ta.T3(self.close, timeperiod=self.tp, vfactor=0) elif para is 'TEMA': #Triple Exponential Moving Average self.output = ta.TEMA(self.close, timeperiod=self.tp) elif para is 'TRIMA': #Triangular Moving Average self.output = ta.TRIMA(self.close, timeperiod=self.tp) elif para is 'WMA': #Weighted Moving Average self.output = ta.WMA(self.close, timeperiod=self.tp) #Momentum Indicators elif para is 'ADX': #Average Directional Movement Index self.output = ta.ADX(self.high, self.low, self.close, timeperiod=self.tp) elif para is 'ADXR': #Average Directional Movement Index Rating self.output = ta.ADXR(self.high, self.low, self.close, timeperiod=self.tp) elif para is 'APO': #Absolute Price Oscillator self.output = ta.APO(self.close, fastperiod=12, slowperiod=26, matype=0) elif para is 'AROON': #Aroon aroondown, aroonup = ta.AROON(self.high, self.low, timeperiod=self.tp) self.output = [aroondown, aroonup] elif para is 'AROONOSC': #Aroon Oscillator self.output = ta.AROONOSC(self.high, self.low, timeperiod=self.tp) elif para is 'BOP': #Balance Of Power self.output = ta.BOP(self.op, self.high, self.low, self.close) elif para is 'CCI': #Commodity Channel Index self.output = ta.CCI(self.high, self.low, self.close, timeperiod=self.tp) elif para is 'CMO': #Chande Momentum Oscillator self.output = ta.CMO(self.close, timeperiod=self.tp) elif para is 'DX': #Directional Movement Index self.output = ta.DX(self.high, self.low, self.close, timeperiod=self.tp) elif para is 'MACD': #Moving Average Convergence/Divergence macd, macdsignal, macdhist = ta.MACD(self.close, fastperiod=12, slowperiod=26, signalperiod=9) self.output = [macd, macdsignal, macdhist] elif para is 'MACDEXT': #MACD with controllable MA type macd, macdsignal, macdhist = ta.MACDEXT(self.close, fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0) self.output = [macd, macdsignal, macdhist] elif para is 'MACDFIX': #Moving Average Convergence/Divergence Fix 12/26 macd, macdsignal, macdhist = ta.MACDFIX(self.close, signalperiod=9) self.output = [macd, macdsignal, macdhist] elif para is 'MFI': #Money Flow Index self.output = ta.MFI(self.high, self.low, self.close, self.volume, timeperiod=self.tp) elif para is 'MINUS_DI': #Minus Directional Indicator self.output = ta.MINUS_DI(self.high, self.low, self.close, timeperiod=self.tp) elif para is 'MINUS_DM': #Minus Directional Movement self.output = ta.MINUS_DM(self.high, self.low, timeperiod=self.tp) elif para is 'MOM': #Momentum self.output = ta.MOM(self.close, timeperiod=10) elif para is 'PLUS_DI': #Plus Directional Indicator self.output = ta.PLUS_DI(self.high, self.low, self.close, timeperiod=self.tp) elif para is 'PLUS_DM': #Plus Directional Movement self.output = ta.PLUS_DM(self.high, self.low, timeperiod=self.tp) elif para is 'PPO': #Percentage Price Oscillator self.output = ta.PPO(self.close, fastperiod=12, slowperiod=26, matype=0) elif para is 'ROC': #Rate of change : ((price/prevPrice)-1)*100 self.output = ta.ROC(self.close, timeperiod=10) elif para is 'ROCP': #Rate of change Percentage: (price-prevPrice)/prevPrice self.output = ta.ROCP(self.close, timeperiod=10) elif para is 'ROCR': #Rate of change ratio: (price/prevPrice) self.output = ta.ROCR(self.close, timeperiod=10) elif para is 'ROCR100': #Rate of change ratio 100 scale: (price/prevPrice)*100 self.output = ta.ROCR100(self.close, timeperiod=10) elif para is 'RSI': #Relative Strength Index self.output = ta.RSI(self.close, timeperiod=self.tp) elif para is 'STOCH': #Stochastic slowk, slowd = ta.STOCH(self.high, self.low, self.close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) self.output = [slowk, slowd] elif para is 'STOCHF': #Stochastic Fast fastk, fastd = ta.STOCHF(self.high, self.low, self.close, fastk_period=5, fastd_period=3, fastd_matype=0) self.output = [fastk, fastd] elif para is 'STOCHRSI': #Stochastic Relative Strength Index fastk, fastd = ta.STOCHRSI(self.close, timeperiod=self.tp, fastk_period=5, fastd_period=3, fastd_matype=0) self.output = [fastk, fastd] elif para is 'TRIX': #1-day Rate-Of-Change (ROC) of a Triple Smooth EMA self.output = ta.TRIX(self.close, timeperiod=self.tp) elif para is 'ULTOSC': #Ultimate Oscillator self.output = ta.ULTOSC(self.high, self.low, self.close, timeperiod1=self.tp, timeperiod2=self.tp1, timeperiod3=self.tp2) elif para is 'WILLR': #Williams' %R self.output = ta.WILLR(self.high, self.low, self.close, timeperiod=self.tp) # Volume Indicators : # elif para is 'AD': #Chaikin A/D Line self.output = ta.AD(self.high, self.low, self.close, self.volume) elif para is 'ADOSC': #Chaikin A/D Oscillator self.output = ta.ADOSC(self.high, self.low, self.close, self.volume, fastperiod=3, slowperiod=10) elif para is 'OBV': #On Balance Volume self.output = ta.OBV(self.close, self.volume) # Volatility Indicators: # elif para is 'ATR': #Average True Range self.output = ta.ATR(self.high, self.low, self.close, timeperiod=self.tp) elif para is 'NATR': #Normalized Average True Range self.output = ta.NATR(self.high, self.low, self.close, timeperiod=self.tp) elif para is 'TRANGE': #True Range self.output = ta.TRANGE(self.high, self.low, self.close) #Price Transform : # elif para is 'AVGPRICE': #Average Price self.output = ta.AVGPRICE(self.op, self.high, self.low, self.close) elif para is 'MEDPRICE': #Median Price self.output = ta.MEDPRICE(self.high, self.low) elif para is 'TYPPRICE': #Typical Price self.output = ta.TYPPRICE(self.high, self.low, self.close) elif para is 'WCLPRICE': #Weighted Close Price self.output = ta.WCLPRICE(self.high, self.low, self.close) #Cycle Indicators : # elif para is 'HT_DCPERIOD': #Hilbert Transform - Dominant Cycle Period self.output = ta.HT_DCPERIOD(self.close) elif para is 'HT_DCPHASE': #Hilbert Transform - Dominant Cycle Phase self.output = ta.HT_DCPHASE(self.close) elif para is 'HT_PHASOR': #Hilbert Transform - Phasor Components inphase, quadrature = ta.HT_PHASOR(self.close) self.output = [inphase, quadrature] elif para is 'HT_SINE': #Hilbert Transform - SineWave #2 sine, leadsine = ta.HT_SINE(self.close) self.output = [sine, leadsine] elif para is 'HT_TRENDMODE': #Hilbert Transform - Trend vs Cycle Mode self.integer = ta.HT_TRENDMODE(self.close) #Pattern Recognition : # elif para is 'CDL2CROWS': #Two Crows self.integer = ta.CDL2CROWS(self.op, self.high, self.low, self.close) elif para is 'CDL3BLACKCROWS': #Three Black Crows self.integer = ta.CDL3BLACKCROWS(self.op, self.high, self.low, self.close) elif para is 'CDL3INSIDE': #Three Inside Up/Down self.integer = ta.CDL3INSIDE(self.op, self.high, self.low, self.close) elif para is 'CDL3LINESTRIKE': #Three-Line Strike self.integer = ta.CDL3LINESTRIKE(self.op, self.high, self.low, self.close) elif para is 'CDL3OUTSIDE': #Three Outside Up/Down self.integer = ta.CDL3OUTSIDE(self.op, self.high, self.low, self.close) elif para is 'CDL3STARSINSOUTH': #Three Stars In The South self.integer = ta.CDL3STARSINSOUTH(self.op, self.high, self.low, self.close) elif para is 'CDL3WHITESOLDIERS': #Three Advancing White Soldiers self.integer = ta.CDL3WHITESOLDIERS(self.op, self.high, self.low, self.close) elif para is 'CDLABANDONEDBABY': #Abandoned Baby self.integer = ta.CDLABANDONEDBABY(self.op, self.high, self.low, self.close, penetration=0) elif para is 'CDLBELTHOLD': #Belt-hold self.integer = ta.CDLBELTHOLD(self.op, self.high, self.low, self.close) elif para is 'CDLBREAKAWAY': #Breakaway self.integer = ta.CDLBREAKAWAY(self.op, self.high, self.low, self.close) elif para is 'CDLCLOSINGMARUBOZU': #Closing Marubozu self.integer = ta.CDLCLOSINGMARUBOZU(self.op, self.high, self.low, self.close) elif para is 'CDLCONCEALBABYSWALL': #Concealing Baby Swallow self.integer = ta.CDLCONCEALBABYSWALL(self.op, self.high, self.low, self.close) elif para is 'CDLCOUNTERATTACK': #Counterattack self.integer = ta.CDLCOUNTERATTACK(self.op, self.high, self.low, self.close) elif para is 'CDLDARKCLOUDCOVER': #Dark Cloud Cover self.integer = ta.CDLDARKCLOUDCOVER(self.op, self.high, self.low, self.close, penetration=0) elif para is 'CDLDOJI': #Doji self.integer = ta.CDLDOJI(self.op, self.high, self.low, self.close) elif para is 'CDLDOJISTAR': #Doji Star self.integer = ta.CDLDOJISTAR(self.op, self.high, self.low, self.close) elif para is 'CDLDRAGONFLYDOJI': #Dragonfly Doji self.integer = ta.CDLDRAGONFLYDOJI(self.op, self.high, self.low, self.close) elif para is 'CDLENGULFING': #Engulfing Pattern self.integer = ta.CDLENGULFING(self.op, self.high, self.low, self.close) elif para is 'CDLEVENINGDOJISTAR': #Evening Doji Star self.integer = ta.CDLEVENINGDOJISTAR(self.op, self.high, self.low, self.close, penetration=0) elif para is 'CDLEVENINGSTAR': #Evening Star self.integer = ta.CDLEVENINGSTAR(self.op, self.high, self.low, self.close, penetration=0) elif para is 'CDLGAPSIDESIDEWHITE': #Up/Down-gap side-by-side white lines self.integer = ta.CDLGAPSIDESIDEWHITE(self.op, self.high, self.low, self.close) elif para is 'CDLGRAVESTONEDOJI': #Gravestone Doji self.integer = ta.CDLGRAVESTONEDOJI(self.op, self.high, self.low, self.close) elif para is 'CDLHAMMER': #Hammer self.integer = ta.CDLHAMMER(self.op, self.high, self.low, self.close) elif para is 'CDLHANGINGMAN': #Hanging Man self.integer = ta.CDLHANGINGMAN(self.op, self.high, self.low, self.close) elif para is 'CDLHARAMI': #Harami Pattern self.integer = ta.CDLHARAMI(self.op, self.high, self.low, self.close) elif para is 'CDLHARAMICROSS': #Harami Cross Pattern self.integer = ta.CDLHARAMICROSS(self.op, self.high, self.low, self.close) elif para is 'CDLHIGHWAVE': #High-Wave Candle self.integer = ta.CDLHIGHWAVE(self.op, self.high, self.low, self.close) elif para is 'CDLHIKKAKE': #Hikkake Pattern self.integer = ta.CDLHIKKAKE(self.op, self.high, self.low, self.close) elif para is 'CDLHIKKAKEMOD': #Modified Hikkake Pattern self.integer = ta.CDLHIKKAKEMOD(self.op, self.high, self.low, self.close) elif para is 'CDLHOMINGPIGEON': #Homing Pigeon self.integer = ta.CDLHOMINGPIGEON(self.op, self.high, self.low, self.close) elif para is 'CDLIDENTICAL3CROWS': #Identical Three Crows self.integer = ta.CDLIDENTICAL3CROWS(self.op, self.high, self.low, self.close) elif para is 'CDLINNECK': #In-Neck Pattern self.integer = ta.CDLINNECK(self.op, self.high, self.low, self.close) elif para is 'CDLINVERTEDHAMMER': #Inverted Hammer self.integer = ta.CDLINVERTEDHAMMER(self.op, self.high, self.low, self.close) elif para is 'CDLKICKING': #Kicking self.integer = ta.CDLKICKING(self.op, self.high, self.low, self.close) elif para is 'CDLKICKINGBYLENGTH': #Kicking - bull/bear determined by the longer marubozu self.integer = ta.CDLKICKINGBYLENGTH(self.op, self.high, self.low, self.close) elif para is 'CDLLADDERBOTTOM': #Ladder Bottom self.integer = ta.CDLLADDERBOTTOM(self.op, self.high, self.low, self.close) elif para is 'CDLLONGLEGGEDDOJI': #Long Legged Doji self.integer = ta.CDLLONGLEGGEDDOJI(self.op, self.high, self.low, self.close) elif para is 'CDLLONGLINE': #Long Line Candle self.integer = ta.CDLLONGLINE(self.op, self.high, self.low, self.close) elif para is 'CDLMARUBOZU': #Marubozu self.integer = ta.CDLMARUBOZU(self.op, self.high, self.low, self.close) elif para is 'CDLMATCHINGLOW': #Matching Low self.integer = ta.CDLMATCHINGLOW(self.op, self.high, self.low, self.close) elif para is 'CDLMATHOLD': #Mat Hold self.integer = ta.CDLMATHOLD(self.op, self.high, self.low, self.close, penetration=0) elif para is 'CDLMORNINGDOJISTAR': #Morning Doji Star self.integer = ta.CDLMORNINGDOJISTAR(self.op, self.high, self.low, self.close, penetration=0) elif para is 'CDLMORNINGSTAR': #Morning Star self.integer = ta.CDLMORNINGSTAR(self.op, self.high, self.low, self.close, penetration=0) elif para is 'CDLONNECK': #On-Neck Pattern self.integer = ta.CDLONNECK(self.op, self.high, self.low, self.close) elif para is 'CDLPIERCING': #Piercing Pattern self.integer = ta.CDLPIERCING(self.op, self.high, self.low, self.close) elif para is 'CDLRICKSHAWMAN': #Rickshaw Man self.integer = ta.CDLRICKSHAWMAN(self.op, self.high, self.low, self.close) elif para is 'CDLRISEFALL3METHODS': #Rising/Falling Three Methods self.integer = ta.CDLRISEFALL3METHODS(self.op, self.high, self.low, self.close) elif para is 'CDLSEPARATINGLINES': #Separating Lines self.integer = ta.CDLSEPARATINGLINES(self.op, self.high, self.low, self.close) elif para is 'CDLSHOOTINGSTAR': #Shooting Star self.integer = ta.CDLSHOOTINGSTAR(self.op, self.high, self.low, self.close) elif para is 'CDLSHORTLINE': #Short Line Candle self.integer = ta.CDLSHORTLINE(self.op, self.high, self.low, self.close) elif para is 'CDLSPINNINGTOP': #Spinning Top self.integer = ta.CDLSPINNINGTOP(self.op, self.high, self.low, self.close) elif para is 'CDLSTALLEDPATTERN': #Stalled Pattern self.integer = ta.CDLSTALLEDPATTERN(self.op, self.high, self.low, self.close) elif para is 'CDLSTICKSANDWICH': #Stick Sandwich self.integer = ta.CDLSTICKSANDWICH(self.op, self.high, self.low, self.close) elif para is 'CDLTAKURI': #Takuri (Dragonfly Doji with very long lower shadow) self.integer = ta.CDLTAKURI(self.op, self.high, self.low, self.close) elif para is 'CDLTASUKIGAP': #Tasuki Gap self.integer = ta.CDLTASUKIGAP(self.op, self.high, self.low, self.close) elif para is 'CDLTHRUSTING': #Thrusting Pattern self.integer = ta.CDLTHRUSTING(self.op, self.high, self.low, self.close) elif para is 'CDLTRISTAR': #Tristar Pattern self.integer = ta.CDLTRISTAR(self.op, self.high, self.low, self.close) elif para is 'CDLUNIQUE3RIVER': #Unique 3 River self.integer = ta.CDLUNIQUE3RIVER(self.op, self.high, self.low, self.close) elif para is 'CDLUPSIDEGAP2CROWS': #Upside Gap Two Crows self.integer = ta.CDLUPSIDEGAP2CROWS(self.op, self.high, self.low, self.close) elif para is 'CDLXSIDEGAP3METHODS': #Upside/Downside Gap Three Methods self.integer = ta.CDLXSIDEGAP3METHODS(self.op, self.high, self.low, self.close) #Statistic Functions : # elif para is 'BETA': #Beta self.output = ta.BETA(self.high, self.low, timeperiod=5) elif para is 'CORREL': #Pearson's Correlation Coefficient (r) self.output = ta.CORREL(self.high, self.low, timeperiod=self.tp) elif para is 'LINEARREG': #Linear Regression self.output = ta.LINEARREG(self.close, timeperiod=self.tp) elif para is 'LINEARREG_ANGLE': #Linear Regression Angle self.output = ta.LINEARREG_ANGLE(self.close, timeperiod=self.tp) elif para is 'LINEARREG_INTERCEPT': #Linear Regression Intercept self.output = ta.LINEARREG_INTERCEPT(self.close, timeperiod=self.tp) elif para is 'LINEARREG_SLOPE': #Linear Regression Slope self.output = ta.LINEARREG_SLOPE(self.close, timeperiod=self.tp) elif para is 'STDDEV': #Standard Deviation self.output = ta.STDDEV(self.close, timeperiod=5, nbdev=1) elif para is 'TSF': #Time Series Forecast self.output = ta.TSF(self.close, timeperiod=self.tp) elif para is 'VAR': #Variance self.output = ta.VAR(self.close, timeperiod=5, nbdev=1) else: print('You issued command:' + para)
def TALIB_MACDFIX(close, signalperiod=9): '''00355,2,3''' return talib.MACDFIX(close, signalperiod)
macd, macdsignal, macdhist = ta.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9) #MACDEXT - MACD with controllable MA type macd, macdsignal, macdhist = ta.MACDEXT(close, fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0) #MACDFIX - Moving Average Convergence/Divergence Fix 12/26 macd, macdsignal, macdhist = ta.MACDFIX(close, signalperiod=9) #MFI - Money Flow Index mfi = ta.MFI(high, low, close, volume, timeperiod=14) #MINUS_DI - Minus Directional Indicator minus_di = ta.MINUS_DI(high, low, close, timeperiod=14) #MINUS_DM - Minus Directional Movement minus_dm = ta.MINUS_DM(high, low, timeperiod=14) #MOM - Momentum mom = ta.MOM(close, timeperiod=10) #PLUS_DI - Plus Directional Indicator plus_di = ta.PLUS_DI(high, low, close, timeperiod=14)
def momentum_process(event): print(event.widget.get()) momentum = event.widget.get() upperband, middleband, lowerband = ta.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0) fig, axes = plt.subplots(2, 1, sharex=True) ax1, ax2 = axes[0], axes[1] axes[0].plot(close, 'rd-', markersize=3) axes[0].plot(upperband, 'y-') axes[0].plot(middleband, 'b-') axes[0].plot(lowerband, 'y-') axes[0].set_title(momentum, fontproperties='SimHei') if momentum == '绝对价格振荡器': real = ta.APO(close, fastperiod=12, slowperiod=26, matype=0) axes[1].plot(real, 'r-') elif momentum == '钱德动量摆动指标': real = ta.CMO(close, timeperiod=14) axes[1].plot(real, 'r-') elif momentum == '移动平均收敛/散度': macd, macdsignal, macdhist = ta.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9) axes[1].plot(macd, 'r-') axes[1].plot(macdsignal, 'g-') axes[1].plot(macdhist, 'b-') elif momentum == '带可控MA类型的MACD': macd, macdsignal, macdhist = ta.MACDEXT(close, fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0) axes[1].plot(macd, 'r-') axes[1].plot(macdsignal, 'g-') axes[1].plot(macdhist, 'b-') elif momentum == '移动平均收敛/散度 固定 12/26': macd, macdsignal, macdhist = ta.MACDFIX(close, signalperiod=9) axes[1].plot(macd, 'r-') axes[1].plot(macdsignal, 'g-') axes[1].plot(macdhist, 'b-') elif momentum == '动量': real = ta.MOM(close, timeperiod=10) axes[1].plot(real, 'r-') elif momentum == '比例价格振荡器': real = ta.PPO(close, fastperiod=12, slowperiod=26, matype=0) axes[1].plot(real, 'r-') elif momentum == '变化率': real = ta.ROC(close, timeperiod=10) axes[1].plot(real, 'r-') elif momentum == '变化率百分比': real = ta.ROCP(close, timeperiod=10) axes[1].plot(real, 'r-') elif momentum == '变化率的比率': real = ta.ROCR(close, timeperiod=10) axes[1].plot(real, 'r-') elif momentum == '变化率的比率100倍': real = ta.ROCR100(close, timeperiod=10) axes[1].plot(real, 'r-') elif momentum == '相对强弱指数': real = ta.RSI(close, timeperiod=14) axes[1].plot(real, 'r-') elif momentum == '随机相对强弱指标': fastk, fastd = ta.STROCHRSI(close, timeperiod=14, fastk_period=5, fasted_period=3, fasted_matype=0) axes[1].plot(fastk, 'r-') axes[1].plot(fastd, 'r-') elif momentum == '三重光滑EMA的日变化率': real = ta.TRIX(close, timeperiod=30) axes[1].plot(real, 'r-') plt.show()
def parse(code,start_date='0'): df = pd.read_sql('select * from day_k_data where code="'+code+'" order by date asc;',engine) buy_price = {} buy_date = {} sell_price = {} sell_date = {} is_buy = {} rate = {} profit = {} profit['based'] = {} ma5 = talib.MA(df['close'].values,5) ma10 = talib.MA(df['close'].values,10) ma20 = talib.MA(df['close'].values,20) ma30 = talib.MA(df['close'].values,30) K, D = talib.STOCH(df['high'].values,df['low'].values,df['close'].values, fastk_period=9, slowk_period=3) J = K * 3 - D * 2 atr = talib.ATR(df['high'].values,df['low'].values,df['close'].values) natr = talib.NATR(df['high'].values,df['low'].values,df['close'].values) trange = talib.TRANGE(df['high'].values,df['low'].values,df['close'].values) cci = talib.CCI(df['high'].values,df['low'].values,df['close'].values,14) dif, dea, bar = talib.MACDFIX(df['close'].values) bar = bar * 2 close = df['close'] start_date_open = 0 for idx in range(len(ma10)): if df.date[idx] < start_date: continue ma10_buy = 0 ma10_sell = 0 bar_buy = 0 bar_sell = 0 cci_buy = 0 cci_sell = 0 dif_buy = 0 dif_sell = 0 K_buy = 0 K_sell = 0 close_val = close[idx] ma10_val = ma10[idx] ma20_val = ma20[idx] ma5_val = ma5[idx] cci_val = cci[idx] dif_val = dif[idx] dea_val = dea[idx] bar_val = bar[idx] K_val = K[idx] D_val = D[idx] J_val = J[idx] if start_date_open == 0: start_date_open = close_val if idx>=1: bar_val_y = bar[idx-1] dif_val_y = dif[idx-1] dea_val_y = dea[idx-1] cci_val_y = cci[idx-1] K_val_y = K[idx-1] if df.date[idx-1] not in profit['based']: profit['based'][df.date[idx-1]] = 1.0 profit['based'][df.date[idx]] = profit['based'][df.date[idx-1]] * close[idx] / close[idx-1] else: bar_val_y = 0 dif_val_y = 0 dea_val_y = 0 cci_val_y = 0 K_val_y = 0 if close_val > ma10_val: ma10_buy = 1 if bar_val>0 and bar_val>bar_val_y: bar_buy = 1 if cci_val>=100 and cci_val>cci_val_y: cci_buy = 1 if dif_val>dea_val and dif_val>dif_val_y: dif_buy = 1 if K_val>D_val and K_val>K_val_y: K_buy = 1 if close_val<ma10_val: ma10_sell = 1 if bar_val<0 and bar_val<bar_val_y: bar_sell = 1 if cci_val<=100 and cci_val<cci_val_y: cci_sell = 1 if dif_val<dea_val and dif_val<dif_val_y: dif_sell = 1 if K_val<D_val and K_val<K_val_y: K_sell = 1 for elm1 in container: ih, ij, ik, il, im = elm1 ma10_buy_t = ma10_buy bar_buy_t = bar_buy cci_buy_t = cci_buy dif_buy_t = dif_buy K_buy_t = K_buy temp = 1 if ih == 0: ma10_buy_t = temp if ij == 0: bar_buy_t = temp if ik == 0: cci_buy_t = temp if il == 0: dif_buy_t = temp if im == 0: K_buy_t = temp for elm2 in container: ihs, ijs, iks, ils, ims = elm2 bar_sell_t = bar_sell cci_sell_t = cci_sell dif_sell_t = dif_sell ma10_sell_t = ma10_sell K_sell_t = K_sell temp = 0 if ihs == 0: ma10_sell_t = temp if ijs == 0: bar_sell_t = temp if iks == 0: cci_sell_t = temp if ils == 0: dif_sell_t = temp if ims == 0: K_sell_t = temp s_type = str(ih)+str(ij)+str(ik)+str(il)+str(im)+'b|s'+str(ihs)+str(ijs)+str(iks)+str(ils)+str(ims) if s_type not in buy_price: buy_price[s_type] = [] buy_date[s_type] = [] sell_price[s_type] = [] sell_date[s_type] = [] is_buy[s_type] = 0 if ma10_buy_t * bar_buy_t * cci_buy_t * dif_buy_t * K_buy_t: if is_buy[s_type] == 0: is_buy[s_type] = 1 buy_price[s_type].append(close_val) buy_date[s_type].append(df.date[idx]) continue if ma10_sell_t or bar_sell_t or cci_sell_t or dif_sell_t or K_sell_t: if is_buy[s_type] == 1: is_buy[s_type] = 0 sell_price[s_type].append(close_val) sell_date[s_type].append(df.date[idx]) rate['based'] = close[len(close)-1] * (1 - 0.002) / start_date_open for s_type in sell_price: rate[s_type] = 1.0 profit[s_type] = {} for i in range(len(buy_price[s_type])): try: rate[s_type] = rate[s_type] * (sell_price[s_type][i] * (1 - 0.002) / buy_price[s_type][i]) profit[s_type][buy_date[s_type][i]] = rate[s_type] #print s_type,"buy date : %s, buy price : %.2f, sell date : %s, sell price: %.2f" %(buy_date[s_type][i], buy_price[s_type][i], sell_date[s_type][i], sell_price[s_type][i]) except: rate[s_type] = rate[s_type] * (close[len(close)-1] * (1 - 0.002) / buy_price[s_type][len(buy_price[s_type])-1]) profit[s_type][buy_date[s_type][i]] = rate[s_type] rate = sorted(rate.items(),key=lambda x:x[1],reverse=True) return rate,profit
def MACDFIX(data, **kwargs): _check_talib_presence() prices = _extract_series(data) return talib.MACDFIX(prices, **kwargs)
def build_talib_factors(df_ftr, tp=10): tporg = tp mul = 2 rtn_divisor = [1, 1 / 8] # momentum df_ftr['BOP'] = ta.BOP(df_ftr.open.values, df_ftr.high.values, df_ftr.low.values, df_ftr.close.values) # volatility df_ftr['TRANGE'] = ta.TRANGE(df_ftr.high.values, df_ftr.low.values, df_ftr.close.values) # volume df_ftr['AD'] = ta.AD(df_ftr.high.values, df_ftr.low.values, df_ftr.close.values, df_ftr.volume.values) # df_ftr['AD_ANGLE']=ta.LINEARREG_ANGLE(df_ftr['AD'].values, timeperiod=tp) too little variation # overlap df_ftr['OBV'] = ta.OBV(df_ftr.close.values, df_ftr.volume.values) for i in range(len(rtn_divisor)): tp = int(tporg // rtn_divisor[i]) if tp <= 3: continue x = str(i) ######## self defined df_ftr['rtn_disper'] = df_ftr['high'] - df_ftr['low'] df_ftr['rtn_disper_rolling' + x] = df_ftr['rtn_disper'].rolling( int(tp)).mean() ######## momentum indicators # see descriptoin for the values df_ftr['close_slope' + x] and others see the freq it falls into the ranges df_ftr['close_slope' + x] = ta.LINEARREG_SLOPE(df_ftr['close'].values, timeperiod=tp) df_ftr['close_slope_std' + x] = df_ftr['close_slope' + x].rolling( int(tp)).std() # rsi df_ftr['rsi' + x] = ta.RSI(df_ftr.close.values, timeperiod=tp) df_ftr['rsi_mean' + x] = ta.SUM(df_ftr['rsi' + x].values, timeperiod=tp) / tp df_ftr['storsi' + x] = (df_ftr['rsi' + x] - df_ftr['rsi' + x].rolling(tp).min() ) / (df_ftr['rsi' + x].rolling(tp).max() - df_ftr['rsi' + x].rolling(tp).min()) # stochastic df_ftr['slowk' + x], df_ftr['slowd' + x] = ta.STOCH( df_ftr.high.values, df_ftr.low.values, df_ftr.close.values, fastk_period=round(tp * mul), slowk_period=tp, slowk_matype=0, slowd_period=tp, slowd_matype=0) # slowd is slow sto, slowk is fast sto df_ftr['slowj'] = (3 * df_ftr['slowd' + x]) - (2 * df_ftr['slowk' + x]) df_ftr['fastk' + x], df_ftr['fastd' + x] = ta.STOCHF( df_ftr.high.values, df_ftr.low.values, df_ftr.close.values, fastk_period=tp, fastd_period=tp // mul, fastd_matype=0) df_ftr['mom' + x] = ta.MOM(df_ftr.close.values, timeperiod=tp) # directional change df_ftr['plus_di' + x] = ta.PLUS_DI(df_ftr.high.values, df_ftr.low.values, df_ftr.close.values, timeperiod=tp) df_ftr['plus_dm' + x] = ta.PLUS_DM(df_ftr.high.values, df_ftr.low.values, timeperiod=tp) df_ftr['MINUS_DI' + x] = ta.MINUS_DI(df_ftr.high.values, df_ftr.low.values, df_ftr.close.values, timeperiod=tp) df_ftr['MINUS_DM' + x] = ta.MINUS_DM(df_ftr.high.values, df_ftr.low.values, timeperiod=tp) df_ftr['plus_minus_di' + x] = df_ftr['plus_di' + x] - df_ftr['MINUS_DI' + x] df_ftr['DX' + x] = ta.DX(df_ftr.high.values, df_ftr.low.values, df_ftr.close.values, timeperiod=tp) df_ftr['ADX' + x] = ta.ADX(df_ftr.high.values, df_ftr.low.values, df_ftr.close.values, timeperiod=tp) df_ftr['ADXR' + x] = ta.ADXR(df_ftr.high.values, df_ftr.low.values, df_ftr.close.values, timeperiod=tp) # MACD df_ftr['MACD' + x], df_ftr['macdsignal' + x], df_ftr['macdhist' + x] = ta.MACD( df_ftr.close.values, fastperiod=tp, slowperiod=round(tp * 2), signalperiod=tp // mul) # http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_average_convergence_divergence_macd # Aroon # https://tradingsim.com/blog/aroon-indicator/ df_ftr['aroondown' + x], df_ftr['aroonup' + x] = ta.AROON( df_ftr.high.values, df_ftr.low.values, timeperiod=tp) df_ftr['AROONOSC' + x] = ta.AROONOSC(df_ftr.high.values, df_ftr.low.values, timeperiod=tp) # Chande Momentum Oscillator # https://www.investopedia.com/terms/c/chandemomentumoscillator.asp df_ftr['CMO' + x] = ta.CMO(df_ftr.close.values, timeperiod=tp) # Money Flow Index # http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:money_flow_index_mfi df_ftr['MFI' + x] = ta.MFI(df_ftr.high.values, df_ftr.low.values, df_ftr.close.values, df_ftr.volume.values, timeperiod=tp) df_ftr['MFI_slope' + x] = ta.LINEARREG_SLOPE(df_ftr['MFI' + x].values, timeperiod=tp) # MACD with controllable MA type df_ftr['macdEXT' + x], df_ftr['macdEXTsignal' + x], df_ftr['macdEXThist' + x] = ta.MACDEXT( df_ftr.close.values, fastperiod=tp // mul, fastmatype=0, slowperiod=tp, slowmatype=0, signalperiod=9, signalmatype=0) df_ftr['macdEXT_slope' + x] = ta.LINEARREG_SLOPE(df_ftr['macdEXT' + x].values, timeperiod=tp) df_ftr['macdFIX' + x], df_ftr['macdFIXsignal' + x], df_ftr['macdFIXhist' + x] = ta.MACDFIX( df_ftr.close.values, signalperiod=9) # Stochastic Relative Strength Index df_ftr['fastkRSI' + x], df_ftr['fastdRSI' + x] = ta.STOCHRSI( df_ftr.close.values, timeperiod=tp, fastk_period=tp // 2, fastd_period=tp // (mul * 2), fastd_matype=0) # volatility df_ftr['ATR' + x] = ta.ATR(df_ftr.high.values, df_ftr.low.values, df_ftr.close.values, timeperiod=tp) df_ftr['NATR' + x] = ta.NATR(df_ftr.high.values, df_ftr.low.values, df_ftr.close.values, timeperiod=tp) # volume df_ftr['ADOSC' + x] = ta.ADOSC(df_ftr.high.values, df_ftr.low.values, df_ftr.close.values, df_ftr.volume.values, fastperiod=tp, slowperiod=tp * mul) df_ftr['AD_SLOPE' + x] = ta.LINEARREG_SLOPE(df_ftr['AD'].values, timeperiod=tp) df_ftr['AD_SLOPE_std' + x] = df_ftr['AD_SLOPE' + x].rolling( int(tp * 20)).std() df_ftr['OBV_slope' + x] = ta.LINEARREG_SLOPE(df_ftr['OBV'].values, timeperiod=tp) # cycle df_ftr['HT_DCPERIOD' + x] = df_ftr['HT_DCPERIOD'].pct_change(periods=int(tp)).values df_ftr['HT_TRENDLINE' + x] = pd.DataFrame( ta.HT_TRENDLINE( df_ftr.close.values)).pct_change(periods=int(tp)).values # statistics df_ftr['STDDEV' + x] = ta.STDDEV(df_ftr.close.values, timeperiod=tp, nbdev=1) # NbDev = How may deviations you want this function to return (normally = 1). df_ftr[ 'TSF' + x] = ta.TSF(df_ftr.close.values, timeperiod=tp) / df_ftr.close - 1 df_ftr['BETA' + x] = ta.BETA(df_ftr.high.values, df_ftr.low.values, timeperiod=tp) df_ftr['LINEARREG_SLOPE' + x] = ta.LINEARREG_SLOPE(df_ftr.close.values, timeperiod=tp) df_ftr['CORREL' + x] = ta.CORREL(df_ftr.high.values, df_ftr.low.values, timeperiod=tp) # candle indicators - pattern recognition - unused features df_ftr = df_ftr.replace([np.inf, -np.inf], np.nan) col = list(df_ftr.columns.values) df_ftr.to_pickle(r'../data/ftr_ta.pkl')
def MACDFIX(Series, timeperiod=9): macd, macdsignal, macdhist = talib.MACDFIX(Series.values, timeperiod) return pd.Series(macd, index=Series.index), pd.Series( macdsignal, index=Series.index), pd.Series(macdhist, index=Series.index)
aroondown_real, aroonup_real = talib.AROON( resorted['high'], resorted['low']) aroonosc_real = talib.AROONOSC(resorted['high'], resorted['low']) bop_real = talib.BOP(resorted['open'], resorted['high'], resorted['low'], resorted['close']) cci_real = talib.CCI(resorted['high'], resorted['low'], resorted['close']) cmo_real = talib.CMO(resorted['close']) dx_real = talib.DX(resorted['high'], resorted['low'], resorted['close']) macd_real, macdsignal_real, macdhist_real = talib.MACD( resorted['close']) macdext_real, macdsignalext_real, macdhistext_real = talib.MACDEXT( resorted['close']) macdfix_real, macdsignalfix_real, macdhistfix_real = talib.MACDFIX( resorted['close']) mfi_real = talib.MFI(resorted['high'], resorted['low'], resorted['close'], resorted['volume']) minus_di_real = talib.MINUS_DI(resorted['high'], resorted['low'], resorted['close']) minus_dm_real = talib.MINUS_DM(resorted['high'], resorted['low']) mom_real = talib.MOM(resorted['close']) plus_di_real = talib.PLUS_DI(resorted['high'], resorted['low'], resorted['close']) plus_dm_real = talib.PLUS_DM(resorted['high'], resorted['low']) ppo_real = talib.PPO(resorted['close']) roc_real = talib.ROC(resorted['close']) rocp_real = talib.ROCP(resorted['close']) rocr_real = talib.ROCR(resorted['close'])
def add_ta_features(df, ta_settings): """Add technial analysis features from typical financial dataset that typically include columns such as "open", "high", "low", "price" and "volume". http://mrjbq7.github.io/ta-lib/ Args: df(pandas.DataFrame): original DataFrame. ta_settings(dict): configuration. Returns: pandas.DataFrame: DataFrame with new features included. """ open = df['open'] high = df['high'] low = df['low'] close = df['price'] volume = df['volume'] if ta_settings['overlap']: df['ta_overlap_bbands_upper'], df['ta_overlap_bbands_middle'], df[ 'ta_overlap_bbands_lower'] = ta.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0) df['ta_overlap_dema'] = ta.DEMA( close, timeperiod=15) # NOTE: Changed to avoid a lot of Nan values df['ta_overlap_ema'] = ta.EMA(close, timeperiod=30) df['ta_overlap_kama'] = ta.KAMA(close, timeperiod=30) df['ta_overlap_ma'] = ta.MA(close, timeperiod=30, matype=0) df['ta_overlap_mama_mama'], df['ta_overlap_mama_fama'] = ta.MAMA(close) period = np.random.randint(10, 20, size=len(close)).astype(float) df['ta_overlap_mavp'] = ta.MAVP(close, period, minperiod=2, maxperiod=30, matype=0) df['ta_overlap_midpoint'] = ta.MIDPOINT(close, timeperiod=14) df['ta_overlap_midprice'] = ta.MIDPRICE(high, low, timeperiod=14) df['ta_overlap_sar'] = ta.SAR(high, low, acceleration=0, maximum=0) df['ta_overlap_sarext'] = ta.SAREXT(high, low, startvalue=0, offsetonreverse=0, accelerationinitlong=0, accelerationlong=0, accelerationmaxlong=0, accelerationinitshort=0, accelerationshort=0, accelerationmaxshort=0) df['ta_overlap_sma'] = ta.SMA(close, timeperiod=30) df['ta_overlap_t3'] = ta.T3(close, timeperiod=5, vfactor=0) df['ta_overlap_tema'] = ta.TEMA( close, timeperiod=12) # NOTE: Changed to avoid a lot of Nan values df['ta_overlap_trima'] = ta.TRIMA(close, timeperiod=30) df['ta_overlap_wma'] = ta.WMA(close, timeperiod=30) # NOTE: Commented to avoid a lot of Nan values # df['ta_overlap_ht_trendline'] = ta.HT_TRENDLINE(close) if ta_settings['momentum']: df['ta_momentum_adx'] = ta.ADX(high, low, close, timeperiod=14) df['ta_momentum_adxr'] = ta.ADXR(high, low, close, timeperiod=14) df['ta_momentum_apo'] = ta.APO(close, fastperiod=12, slowperiod=26, matype=0) df['ta_momentum_aroondown'], df['ta_momentum_aroonup'] = ta.AROON( high, low, timeperiod=14) df['ta_momentum_aroonosc'] = ta.AROONOSC(high, low, timeperiod=14) df['ta_momentum_bop'] = ta.BOP(open, high, low, close) df['ta_momentum_cci'] = ta.CCI(high, low, close, timeperiod=14) df['ta_momentum_cmo'] = ta.CMO(close, timeperiod=14) df['ta_momentum_dx'] = ta.DX(high, low, close, timeperiod=14) df['ta_momentum_macd_macd'], df['ta_momentum_macd_signal'], df[ 'ta_momentum_macd_hist'] = ta.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9) df['ta_momentum_macdext_macd'], df['ta_momentum_macdext_signal'], df[ 'ta_momentum_macdext_hist'] = ta.MACDEXT(close, fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0) df['ta_momentum_macdfix_macd'], df['ta_momentum_macdfix_signal'], df[ 'ta_momentum_macdfix_hist'] = ta.MACDFIX(close, signalperiod=9) df['ta_momentum_mfi'] = ta.MFI(high, low, close, volume, timeperiod=14) df['ta_momentum_minus_di'] = ta.MINUS_DI(high, low, close, timeperiod=14) df['ta_momentum_minus_dm'] = ta.MINUS_DM(high, low, timeperiod=14) df['ta_momentum_mom'] = ta.MOM(close, timeperiod=10) df['ta_momentum_plus_di'] = ta.PLUS_DI(high, low, close, timeperiod=14) df['ta_momentum_plus_dm'] = ta.PLUS_DM(high, low, timeperiod=14) df['ta_momentum_ppo'] = ta.PPO(close, fastperiod=12, slowperiod=26, matype=0) df['ta_momentum_roc'] = ta.ROC(close, timeperiod=10) df['ta_momentum_rocp'] = ta.ROCP(close, timeperiod=10) df['ta_momentum_rocr'] = ta.ROCR(close, timeperiod=10) df['ta_momentum_rocr100'] = ta.ROCR100(close, timeperiod=10) df['ta_momentum_rsi'] = ta.RSI(close, timeperiod=14) df['ta_momentum_slowk'], df['ta_momentum_slowd'] = ta.STOCH( high, low, close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) df['ta_momentum_fastk'], df['ta_momentum_fastd'] = ta.STOCHF( high, low, close, fastk_period=5, fastd_period=3, fastd_matype=0) df['ta_momentum_fastk'], df['ta_momentum_fastd'] = ta.STOCHRSI( close, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0) df['ta_momentum_trix'] = ta.TRIX( close, timeperiod=12) # NOTE: Changed to avoid a lot of Nan values df['ta_momentum_ultosc'] = ta.ULTOSC(high, low, close, timeperiod1=7, timeperiod2=14, timeperiod3=28) df['ta_momentum_willr'] = ta.WILLR(high, low, close, timeperiod=14) if ta_settings['volume']: df['ta_volume_ad'] = ta.AD(high, low, close, volume) df['ta_volume_adosc'] = ta.ADOSC(high, low, close, volume, fastperiod=3, slowperiod=10) df['ta_volume_obv'] = ta.OBV(close, volume) if ta_settings['volatility']: df['ta_volatility_atr'] = ta.ATR(high, low, close, timeperiod=14) df['ta_volatility_natr'] = ta.NATR(high, low, close, timeperiod=14) df['ta_volatility_trange'] = ta.TRANGE(high, low, close) if ta_settings['price']: df['ta_price_avgprice'] = ta.AVGPRICE(open, high, low, close) df['ta_price_medprice'] = ta.MEDPRICE(high, low) df['ta_price_typprice'] = ta.TYPPRICE(high, low, close) df['ta_price_wclprice'] = ta.WCLPRICE(high, low, close) if ta_settings['cycle']: df['ta_cycle_ht_dcperiod'] = ta.HT_DCPERIOD(close) df['ta_cycle_ht_phasor_inphase'], df[ 'ta_cycle_ht_phasor_quadrature'] = ta.HT_PHASOR(close) df['ta_cycle_ht_trendmode'] = ta.HT_TRENDMODE(close) # NOTE: Commented to avoid a lot of Nan values # df['ta_cycle_ht_dcphase'] = ta.HT_DCPHASE(close) # df['ta_cycle_ht_sine_sine'], df['ta_cycle_ht_sine_leadsine'] = ta.HT_SINE(close) if ta_settings['pattern']: df['ta_pattern_cdl2crows'] = ta.CDL2CROWS(open, high, low, close) df['ta_pattern_cdl3blackrows'] = ta.CDL3BLACKCROWS( open, high, low, close) df['ta_pattern_cdl3inside'] = ta.CDL3INSIDE(open, high, low, close) df['ta_pattern_cdl3linestrike'] = ta.CDL3LINESTRIKE( open, high, low, close) df['ta_pattern_cdl3outside'] = ta.CDL3OUTSIDE(open, high, low, close) df['ta_pattern_cdl3starsinsouth'] = ta.CDL3STARSINSOUTH( open, high, low, close) df['ta_pattern_cdl3whitesoldiers'] = ta.CDL3WHITESOLDIERS( open, high, low, close) df['ta_pattern_cdlabandonedbaby'] = ta.CDLABANDONEDBABY(open, high, low, close, penetration=0) df['ta_pattern_cdladvanceblock'] = ta.CDLADVANCEBLOCK( open, high, low, close) df['ta_pattern_cdlbelthold'] = ta.CDLBELTHOLD(open, high, low, close) df['ta_pattern_cdlbreakaway'] = ta.CDLBREAKAWAY(open, high, low, close) df['ta_pattern_cdlclosingmarubozu'] = ta.CDLCLOSINGMARUBOZU( open, high, low, close) df['ta_pattern_cdlconcealbabyswall'] = ta.CDLCONCEALBABYSWALL( open, high, low, close) df['ta_pattern_cdlcounterattack'] = ta.CDLCOUNTERATTACK( open, high, low, close) df['ta_pattern_cdldarkcloudcover'] = ta.CDLDARKCLOUDCOVER( open, high, low, close, penetration=0) df['ta_pattern_cdldoji'] = ta.CDLDOJI(open, high, low, close) df['ta_pattern_cdldojistar'] = ta.CDLDOJISTAR(open, high, low, close) df['ta_pattern_cdldragonflydoji'] = ta.CDLDRAGONFLYDOJI( open, high, low, close) df['ta_pattern_cdlengulfing'] = ta.CDLENGULFING(open, high, low, close) df['ta_pattern_cdleveningdojistar'] = ta.CDLEVENINGDOJISTAR( open, high, low, close, penetration=0) df['ta_pattern_cdleveningstar'] = ta.CDLEVENINGSTAR(open, high, low, close, penetration=0) df['ta_pattern_cdlgapsidesidewhite'] = ta.CDLGAPSIDESIDEWHITE( open, high, low, close) df['ta_pattern_cdlgravestonedoji'] = ta.CDLGRAVESTONEDOJI( open, high, low, close) df['ta_pattern_cdlhammer'] = ta.CDLHAMMER(open, high, low, close) df['ta_pattern_cdlhangingman'] = ta.CDLHANGINGMAN( open, high, low, close) df['ta_pattern_cdlharami'] = ta.CDLHARAMI(open, high, low, close) df['ta_pattern_cdlharamicross'] = ta.CDLHARAMICROSS( open, high, low, close) df['ta_pattern_cdlhighwave'] = ta.CDLHIGHWAVE(open, high, low, close) df['ta_pattern_cdlhikkake'] = ta.CDLHIKKAKE(open, high, low, close) df['ta_pattern_cdlhikkakemod'] = ta.CDLHIKKAKEMOD( open, high, low, close) df['ta_pattern_cdlhomingpigeon'] = ta.CDLHOMINGPIGEON( open, high, low, close) df['ta_pattern_cdlidentical3crows'] = ta.CDLIDENTICAL3CROWS( open, high, low, close) df['ta_pattern_cdlinneck'] = ta.CDLINNECK(open, high, low, close) df['ta_pattern_cdlinvertedhammer'] = ta.CDLINVERTEDHAMMER( open, high, low, close) df['ta_pattern_cdlkicking'] = ta.CDLKICKING(open, high, low, close) df['ta_pattern_cdlkickingbylength'] = ta.CDLKICKINGBYLENGTH( open, high, low, close) df['ta_pattern_cdlladderbottom'] = ta.CDLLADDERBOTTOM( open, high, low, close) df['ta_pattern_cdllongleggeddoji'] = ta.CDLLONGLEGGEDDOJI( open, high, low, close) df['ta_pattern_cdllongline'] = ta.CDLLONGLINE(open, high, low, close) df['ta_pattern_cdlmarubozu'] = ta.CDLMARUBOZU(open, high, low, close) df['ta_pattern_cdlmatchinglow'] = ta.CDLMATCHINGLOW( open, high, low, close) df['ta_pattern_cdlmathold'] = ta.CDLMATHOLD(open, high, low, close, penetration=0) df['ta_pattern_cdlmorningdojistar'] = ta.CDLMORNINGDOJISTAR( open, high, low, close, penetration=0) df['ta_pattern_cdlmorningstar'] = ta.CDLMORNINGSTAR(open, high, low, close, penetration=0) df['ta_pattern_cdllonneck'] = ta.CDLONNECK(open, high, low, close) df['ta_pattern_cdlpiercing'] = ta.CDLPIERCING(open, high, low, close) df['ta_pattern_cdlrickshawman'] = ta.CDLRICKSHAWMAN( open, high, low, close) df['ta_pattern_cdlrisefall3methods'] = ta.CDLRISEFALL3METHODS( open, high, low, close) df['ta_pattern_cdlseparatinglines'] = ta.CDLSEPARATINGLINES( open, high, low, close) df['ta_pattern_cdlshootingstar'] = ta.CDLSHOOTINGSTAR( open, high, low, close) df['ta_pattern_cdlshortline'] = ta.CDLSHORTLINE(open, high, low, close) df['ta_pattern_cdlspinningtop'] = ta.CDLSPINNINGTOP( open, high, low, close) df['ta_pattern_cdlstalledpattern'] = ta.CDLSTALLEDPATTERN( open, high, low, close) df['ta_pattern_cdlsticksandwich'] = ta.CDLSTICKSANDWICH( open, high, low, close) df['ta_pattern_cdltakuri'] = ta.CDLTAKURI(open, high, low, close) df['ta_pattern_cdltasukigap'] = ta.CDLTASUKIGAP(open, high, low, close) df['ta_pattern_cdlthrusting'] = ta.CDLTHRUSTING(open, high, low, close) df['ta_pattern_cdltristar'] = ta.CDLTRISTAR(open, high, low, close) df['ta_pattern_cdlunique3river'] = ta.CDLUNIQUE3RIVER( open, high, low, close) df['ta_pattern_cdlupsidegap2crows'] = ta.CDLUPSIDEGAP2CROWS( open, high, low, close) df['ta_pattern_cdlxsidegap3methods'] = ta.CDLXSIDEGAP3METHODS( open, high, low, close) if ta_settings['statistic']: df['ta_statistic_beta'] = ta.BETA(high, low, timeperiod=5) df['ta_statistic_correl'] = ta.CORREL(high, low, timeperiod=30) df['ta_statistic_linearreg'] = ta.LINEARREG(close, timeperiod=14) df['ta_statistic_linearreg_angle'] = ta.LINEARREG_ANGLE(close, timeperiod=14) df['ta_statistic_linearreg_intercept'] = ta.LINEARREG_INTERCEPT( close, timeperiod=14) df['ta_statistic_linearreg_slope'] = ta.LINEARREG_SLOPE(close, timeperiod=14) df['ta_statistic_stddev'] = ta.STDDEV(close, timeperiod=5, nbdev=1) df['ta_statistic_tsf'] = ta.TSF(close, timeperiod=14) df['ta_statistic_var'] = ta.VAR(close, timeperiod=5, nbdev=1) if ta_settings['math_transforms']: df['ta_math_transforms_atan'] = ta.ATAN(close) df['ta_math_transforms_ceil'] = ta.CEIL(close) df['ta_math_transforms_cos'] = ta.COS(close) df['ta_math_transforms_floor'] = ta.FLOOR(close) df['ta_math_transforms_ln'] = ta.LN(close) df['ta_math_transforms_log10'] = ta.LOG10(close) df['ta_math_transforms_sin'] = ta.SIN(close) df['ta_math_transforms_sqrt'] = ta.SQRT(close) df['ta_math_transforms_tan'] = ta.TAN(close) if ta_settings['math_operators']: df['ta_math_operators_add'] = ta.ADD(high, low) df['ta_math_operators_div'] = ta.DIV(high, low) df['ta_math_operators_min'], df['ta_math_operators_max'] = ta.MINMAX( close, timeperiod=30) df['ta_math_operators_minidx'], df[ 'ta_math_operators_maxidx'] = ta.MINMAXINDEX(close, timeperiod=30) df['ta_math_operators_mult'] = ta.MULT(high, low) df['ta_math_operators_sub'] = ta.SUB(high, low) df['ta_math_operators_sum'] = ta.SUM(close, timeperiod=30) return df
def ta(name, price_h, price_l, price_c, price_v, price_o): # function 'MAX'/'MAXINDEX'/'MIN'/'MININDEX'/'MINMAX'/'MINMAXINDEX'/'SUM' is missing if name == 'AD': return talib.AD(np.array(price_h), np.array(price_l), np.array(price_c), np.asarray(price_v, dtype='float')) if name == 'ADOSC': return talib.ADOSC(np.array(price_h), np.array(price_l), np.array(price_c), np.asarray(price_v, dtype='float'), fastperiod=2, slowperiod=10) if name == 'ADX': return talib.ADX(np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float'), timeperiod=14) if name == 'ADXR': return talib.ADXR(np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float'), timeperiod=14) if name == 'APO': return talib.APO(np.asarray(price_c, dtype='float'), fastperiod=12, slowperiod=26, matype=0) if name == 'AROON': AROON_DWON, AROON2_UP = talib.AROON(np.array(price_h), np.asarray(price_l, dtype='float'), timeperiod=90) return (AROON_DWON, AROON2_UP) if name == 'AROONOSC': return talib.AROONOSC(np.array(price_h), np.asarray(price_l, dtype='float'), timeperiod=14) if name == 'ATR': return talib.ATR(np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float'), timeperiod=14) if name == 'AVGPRICE': return talib.AVGPRICE(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'BBANDS': BBANDS1, BBANDS2, BBANDS3 = talib.BBANDS(np.asarray(price_c, dtype='float'), matype=MA_Type.T3) return BBANDS1 if name == 'BETA': return talib.BETA(np.array(price_h), np.asarray(price_l, dtype='float'), timeperiod=5) if name == 'BOP': return talib.BOP(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CCI': return talib.CCI(np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float'), timeperiod=14) if name == 'CDL2CROWS': return talib.CDL2CROWS(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDL3BLACKCROWS': return talib.CDL3BLACKCROWS(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDL3INSIDE': return talib.CDL3INSIDE(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDL3LINESTRIKE': return talib.CDL3LINESTRIKE(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDL3OUTSIDE': return talib.CDL3OUTSIDE(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDL3STARSINSOUTH': return talib.CDL3STARSINSOUTH(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDL3WHITESOLDIERS': return talib.CDL3WHITESOLDIERS(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLABANDONEDBABY': return talib.CDLABANDONEDBABY(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float'), penetration=0) if name == 'CDLADVANCEBLOCK': return talib.CDLADVANCEBLOCK(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLBELTHOLD': return talib.CDLBELTHOLD(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLBREAKAWAY': return talib.CDLBREAKAWAY(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLCLOSINGMARUBOZU': return talib.CDLCLOSINGMARUBOZU(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLCONCEALBABYSWALL': return talib.CDLCONCEALBABYSWALL(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLCOUNTERATTACK': return talib.CDLCOUNTERATTACK(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLDARKCLOUDCOVER': return talib.CDLDARKCLOUDCOVER(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float'), penetration=0) if name == 'CDLDOJI': return talib.CDLDOJI(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLDOJISTAR': return talib.CDLDOJISTAR(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLDRAGONFLYDOJI': return talib.CDLDRAGONFLYDOJI(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLENGULFING': return talib.CDLENGULFING(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLEVENINGDOJISTAR': return talib.CDLEVENINGDOJISTAR(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float'), penetration=0) if name == 'CDLEVENINGSTAR': return talib.CDLEVENINGSTAR(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float'), penetration=0) if name == 'CDLGAPSIDESIDEWHITE': return talib.CDLGAPSIDESIDEWHITE(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLGRAVESTONEDOJI': return talib.CDLGRAVESTONEDOJI(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLHAMMER': return talib.CDLHAMMER(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLHANGINGMAN': return talib.CDLHANGINGMAN(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLHARAMI': return talib.CDLHARAMI(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLHARAMICROSS': return talib.CDLHARAMICROSS(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLHIGHWAVE': return talib.CDLHIGHWAVE(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLHIKKAKE': return talib.CDLHIKKAKE(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLHIKKAKEMOD': return talib.CDLHIKKAKEMOD(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLHOMINGPIGEON': return talib.CDLHOMINGPIGEON(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLIDENTICAL3CROWS': return talib.CDLIDENTICAL3CROWS(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLINNECK': return talib.CDLINNECK(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLINVERTEDHAMMER': return talib.CDLINVERTEDHAMMER(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLKICKING': return talib.CDLKICKING(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLKICKINGBYLENGTH': return talib.CDLKICKINGBYLENGTH(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLLADDERBOTTOM': return talib.CDLLADDERBOTTOM(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLLONGLEGGEDDOJI': return talib.CDLLONGLEGGEDDOJI(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLLONGLINE': return talib.CDLLONGLINE(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLMARUBOZU': return talib.CDLMARUBOZU(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLMATCHINGLOW': return talib.CDLMATCHINGLOW(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLMATHOLD': return talib.CDLMATHOLD(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLMORNINGDOJISTAR': return talib.CDLMORNINGDOJISTAR(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float'), penetration=0) if name == 'CDLMORNINGSTAR': return talib.CDLMORNINGSTAR(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float'), penetration=0) if name == 'CDLONNECK': return talib.CDLONNECK(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLPIERCING': return talib.CDLPIERCING(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLRICKSHAWMAN': return talib.CDLRICKSHAWMAN(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLRISEFALL3METHODS': return talib.CDLRISEFALL3METHODS(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLSEPARATINGLINES': return talib.CDLSEPARATINGLINES(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLSHOOTINGSTAR': return talib.CDLSHOOTINGSTAR(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLSHORTLINE': return talib.CDLSHORTLINE(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLSPINNINGTOP': return talib.CDLSPINNINGTOP(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLSTALLEDPATTERN': return talib.CDLSTALLEDPATTERN(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLSTICKSANDWICH': return talib.CDLSTICKSANDWICH(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLTAKURI': return talib.CDLTAKURI(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLTASUKIGAP': return talib.CDLTASUKIGAP(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLTHRUSTING': return talib.CDLTHRUSTING(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLTRISTAR': return talib.CDLTRISTAR(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLUNIQUE3RIVER': return talib.CDLUNIQUE3RIVER(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLUPSIDEGAP2CROWS': return talib.CDLUPSIDEGAP2CROWS(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CDLXSIDEGAP3METHODS': return talib.CDLXSIDEGAP3METHODS(np.array(price_o), np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'CMO': return talib.CMO(np.asarray(price_c, dtype='float'), timeperiod=14) if name == 'CORREL': return talib.CORREL(np.array(price_h), np.asarray(price_l, dtype='float'), timeperiod=30) if name == 'DEMA': return talib.DEMA(np.asarray(price_c, dtype='float'), timeperiod=30) if name == 'DX': return talib.DX(np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float'), timeperiod=14) if name == 'EMA': return talib.EMA(np.asarray(price_c, dtype='float'), timeperiod=30) if name == 'HT_DCPERIOD': return talib.HT_DCPERIOD(np.asarray(price_c, dtype='float')) if name == 'HT_DCPHASE': return talib.HT_DCPHASE(np.asarray(price_c, dtype='float')) if name == 'HT_PHASOR': HT_PHASOR1, HT_PHASOR2 = talib.HT_PHASOR( np.asarray(price_c, dtype='float') ) # use HT_PHASOR1 for the indication of up and down return HT_PHASOR1 if name == 'HT_SINE': HT_SINE1, HT_SINE2 = talib.HT_SINE(np.asarray(price_c, dtype='float')) return HT_SINE1 if name == 'HT_TRENDLINE': return talib.HT_TRENDLINE(np.asarray(price_c, dtype='float')) if name == 'HT_TRENDMODE': return talib.HT_TRENDMODE(np.asarray(price_c, dtype='float')) if name == 'KAMA': return talib.KAMA(np.asarray(price_c, dtype='float'), timeperiod=30) if name == 'LINEARREG': return talib.LINEARREG(np.asarray(price_c, dtype='float'), timeperiod=14) if name == 'LINEARREG_ANGLE': return talib.LINEARREG_ANGLE(np.asarray(price_c, dtype='float'), timeperiod=14) if name == 'LINEARREG_INTERCEPT': return talib.LINEARREG_INTERCEPT(np.asarray(price_c, dtype='float'), timeperiod=14) if name == 'LINEARREG_SLOPE': return talib.LINEARREG_SLOPE(np.asarray(price_c, dtype='float'), timeperiod=14) if name == 'MA': return talib.MA(np.asarray(price_c, dtype='float'), timeperiod=30, matype=0) if name == 'MACD': MACD1, MACD2, MACD3 = talib.MACD(np.asarray(price_c, dtype='float'), fastperiod=12, slowperiod=26, signalperiod=9) return MACD1 if nam == 'MACDEXT': return talib.MACDEXT(np.asarray(price_c, dtype='float'), fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0) if name == 'MACDFIX': MACDFIX1, MACDFIX2, MACDFIX3 = talib.MACDFIX(np.asarray(price_c, dtype='float'), signalperiod=9) return MACDFIX1 if name == 'MAMA': MAMA1, MAMA2 = talib.MAMA(np.asarray(price_c, dtype='float'), fastlimit=0, slowlimit=0) return MAMA1 if name == 'MEDPRICE': return talib.MEDPRICE(np.array(price_h), np.asarray(price_l, dtype='float')) if name == 'MINUS_DI': return talib.MINUS_DI(np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float'), timeperiod=14) if name == 'MINUS_DM': return talib.MINUS_DM(np.array(price_h), np.asarray(price_l, dtype='float'), timeperiod=14) if name == 'MOM': return talib.MOM(np.asarray(price_c, dtype='float'), timeperiod=10) if name == 'NATR': return talib.NATR(np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float'), timeperiod=14) if name == 'OBV': return talib.OBV(np.array(price_c), np.asarray(price_v, dtype='float')) if name == 'PLUS_DI': return talib.PLUS_DI(np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float'), timeperiod=14) if name == 'PLUS_DM': return talib.PLUS_DM(np.array(price_h), np.asarray(price_l, dtype='float'), timeperiod=14) if name == 'PPO': return talib.PPO(np.asarray(price_c, dtype='float'), fastperiod=12, slowperiod=26, matype=0) if name == 'ROC': return talib.ROC(np.asarray(price_c, dtype='float'), timeperiod=10) if name == 'ROCP': return talib.ROCP(np.asarray(price_c, dtype='float'), timeperiod=10) if name == 'ROCR100': return talib.ROCR100(np.asarray(price_c, dtype='float'), timeperiod=10) if name == 'RSI': return talib.RSI(np.asarray(price_c, dtype='float'), timeperiod=14) if name == 'SAR': return talib.SAR(np.array(price_h), np.asarray(price_l, dtype='float'), acceleration=0, maximum=0) if name == 'SAREXT': return talib.SAREXT(np.array(price_h), np.asarray(price_l, dtype='float'), startvalue=0, offsetonreverse=0, accelerationinitlong=0, accelerationlong=0, accelerationmaxlong=0, accelerationinitshort=0, accelerationshort=0, accelerationmaxshort=0) if name == 'SMA': return talib.SMA(np.asarray(price_c, dtype='float'), timeperiod=30) if name == 'STDDEV': return talib.STDDEV(np.asarray(price_c, dtype='float'), timeperiod=5, nbdev=1) if name == 'STOCH': STOCH1, STOCH2 = talib.STOCH(np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float'), fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) return STOCH1 if name == 'STOCHF': STOCHF1, STOCHF2 = talib.STOCHF(np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float'), fastk_period=5, fastd_period=3, fastd_matype=0) return STOCHF1 if name == 'STOCHRSI': STOCHRSI1, STOCHRSI2 = talib.STOCHRSI(np.asarray(price_c, dtype='float'), timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0) return STOCHRSI1 if name == 'T3': return talib.T3(np.asarray(price_c, dtype='float'), timeperiod=5, vfactor=0) if name == 'TEMA': return talib.TEMA(np.asarray(price_c, dtype='float'), timeperiod=30) if name == 'TRANGE': return talib.TRANGE(np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'TRIMA': return talib.TRIMA(np.asarray(price_c, dtype='float'), timeperiod=30) if name == 'TRIX': return talib.TRIX(np.asarray(price_c, dtype='float'), timeperiod=30) if name == 'TSF': return talib.TSF(np.asarray(price_c, dtype='float'), timeperiod=14) if name == 'TYPPRICE': return talib.TYPPRICE(np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'ULTOSC': return talib.ULTOSC(np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float'), timeperiod1=7, timeperiod2=14, timeperiod3=28) if name == 'VAR': return talib.VAR(np.asarray(price_c, dtype='float'), timeperiod=5, nbdev=1) if name == 'WCLPRICE': return talib.WCLPRICE(np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float')) if name == 'WILLR': return talib.WILLR(np.array(price_h), np.array(price_l), np.asarray(price_c, dtype='float'), timeperiod=14) if name == 'WMA': return talib.WMA(np.asarray(price_c, dtype='float'), timeperiod=30)
def macdfix(col, signalperiod=9): values = ta.MACDFIX(col, signalperiod) return {"macd": values[0], "macdsignal": values[1], "macdhist": values[2]}
def Set_indicators(data, period): """ :param data: dataframe containing ohlcv prices and indexed with date :param period: period used to calculate indicators :return: dataframe of Technical indicators of specefic timeframe """ df = pd.DataFrame(index=data.index) df["mom" + str(period)] = talib.MOM(data[USED_CLOSE_PRICE], timeperiod=period) #change it later df["slowk" + str(period)], df["slowd" + str(period)] = talib.STOCH( data["High"], data["Low"], data[USED_CLOSE_PRICE], fastk_period=period, slowk_period=period, slowk_matype=0, slowd_period=period, slowd_matype=0) #WILLR df["willr" + str(period)] = talib.WILLR(data["High"], data["Low"], data[USED_CLOSE_PRICE], timeperiod=period) #MACDFIX - Moving Average Convergence/Divergence Fix 12/26 df["macd" + str(period)], df["macdsignal" + str(period)], df["macdhist" + str(period)] = talib.MACDFIX( data[USED_CLOSE_PRICE], signalperiod=period) #CCI df["cci" + str(period)] = talib.CCI(data["High"], data["Low"], data[USED_CLOSE_PRICE], timeperiod=period) #Bollinger Bands df["upperband" + str(period)], df["middleband" + str(period)], df["lowerband" + str(period)] = talib.BBANDS( data[USED_CLOSE_PRICE], timeperiod=period, nbdevup=2, nbdevdn=2, matype=0) #HIGH SMA df["smaHigh" + str(period)] = talib.SMA(data["High"], timeperiod=period) # SMA Adj Prices df["sma" + str(period)] = talib.SMA(data[USED_CLOSE_PRICE], timeperiod=period) df["smaHighLow" + str(period)] = talib.SMA(talib.MEDPRICE( data["High"], data["Low"]), timeperiod=period) #DEMA - Double Exponential Moving Average df["DEMA" + str(period)] = talib.DEMA(data[USED_CLOSE_PRICE], timeperiod=period) #EMA - Exponential Moving Average df["EMA" + str(period)] = talib.EMA(data[USED_CLOSE_PRICE], timeperiod=period) #HT_TRENDLINE - Hilbert Transform - Instantaneous Trendline df["HT_TRENDLINE" + str(period)] = talib.HT_TRENDLINE( data[USED_CLOSE_PRICE]) #KAMA - Kaufman Adaptive Moving Average df["KAMA" + str(period)] = talib.KAMA(data[USED_CLOSE_PRICE], timeperiod=period) #T3 - Triple Exponential Moving Average (T3) df["T3-" + str(period)] = talib.T3(data[USED_CLOSE_PRICE], timeperiod=period, vfactor=0) #TEMA - Triple Exponential Moving Average df["TEMA" + str(period)] = talib.TEMA(data[USED_CLOSE_PRICE], timeperiod=period) #TRIMA - Triangular Moving Average df["TRIMA" + str(period)] = talib.TRIMA(data[USED_CLOSE_PRICE], timeperiod=period) #WMA - Weighted Moving Average df["TRIMA" + str(period)] = talib.WMA(data[USED_CLOSE_PRICE], timeperiod=period) ########## #ADX - Average Directional Movement Index df["ADX" + str(period)] = talib.ADX(data["High"], data["Low"], data[USED_CLOSE_PRICE], timeperiod=period) #ADXR - Average Directional Movement Index Rating df["ADXR" + str(period)] = talib.ADXR(data["High"], data["Low"], data[USED_CLOSE_PRICE], timeperiod=period) #AROON - Aroon df["aroondown" + str(period)], df["aroonup" + str(period)] = talib.AROON( data["High"], data["Low"], timeperiod=period) #AROONOSC - Aroon Oscillator df["aroondown" + str(period)] = talib.AROONOSC(data["High"], data["Low"], timeperiod=period) #CMO - Chande Momentum Oscillator df["CMO" + str(period)] = talib.CMO(data[USED_CLOSE_PRICE], timeperiod=period) #DX - Directional Movement Index df["DX" + str(period)] = talib.DX(data["High"], data["Low"], data[USED_CLOSE_PRICE], timeperiod=period) #MINUS_DI - Minus Directional Indicator df["MINUS_DI" + str(period)] = talib.MINUS_DI(data["High"], data["Low"], data[USED_CLOSE_PRICE], timeperiod=period) #MINUS_DM - Minus Directional Movement df["MINUS_DM" + str(period)] = talib.MINUS_DM(data["High"], data["Low"], timeperiod=period) #PLUS_DI - Plus Directional Indicator df["PLUS_DI" + str(period)] = talib.PLUS_DI(data["High"], data["Low"], data[USED_CLOSE_PRICE], timeperiod=period) #PLUS_DM - Plus Directional Movement df["PLUS_DM" + str(period)] = talib.PLUS_DM(data["High"], data["Low"], timeperiod=period) #ROC - Rate of change : ((price/prevPrice)-1)*100 df["roc" + str(period)] = talib.ROC(data[USED_CLOSE_PRICE], timeperiod=period) #ROCP - Rate of change Percentage: (price-prevPrice)/prevPrice df["ROCP" + str(period)] = talib.ROCP(data[USED_CLOSE_PRICE], timeperiod=period) #ROCR - Rate of change ratio: (price/prevPrice) df["ROCR" + str(period)] = talib.ROCR(data[USED_CLOSE_PRICE], timeperiod=period) #ROCR100 - Rate of change ratio 100 scale: (price/prevPrice)*100 df["ROCR100-" + str(period)] = talib.ROCR100(data[USED_CLOSE_PRICE], timeperiod=period) #RSI - Relative Strength Index df["RSI-" + str(period)] = talib.RSI(data[USED_CLOSE_PRICE], timeperiod=period) #TRIX - 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA df["TRIX" + str(period)] = talib.TRIX(data[USED_CLOSE_PRICE], timeperiod=period) #MFI - Money Flow Index df["MFI" + str(period)] = talib.MFI(data["High"], data["Low"], data[USED_CLOSE_PRICE], data["Volume"], timeperiod=period) #ADOSC - Chaikin A/D Oscillator set periods later please df["ADOSC" + str(period)] = talib.ADOSC(data["High"], data["Low"], data[USED_CLOSE_PRICE], data["Volume"], fastperiod=np.round(period / 3), slowperiod=period) return df
def generateTechnicalDataframe(coin_dataframe): """Param: coin_dataframe: Dataframe type, exact same format as output of getCoinData Returns: dataframe of technical data, with index representing dates and columns representing each technical indicator""" Low_df = coin_dataframe['Low'] High_df = coin_dataframe['High'] Price_df = coin_dataframe['Adj. Close'] LowList = Low_df.values.tolist() HighList = High_df.values.tolist() PriceList = Price_df.values.tolist() DateList = coin_dataframe.index.tolist() #converted to list z = 0 while z < len(LowList): if isinstance(LowList[z], str): LowList[z] = float(LowList[z].replace(',', '')) z = z + 1 y = 0 while y < len(HighList): if isinstance(HighList[y], str): HighList[y] = float(HighList[y].replace(',', '')) y = y + 1 x = 0 while x < len(PriceList): if isinstance(PriceList[x], str): PriceList[x] = float(PriceList[x].replace(',', '')) x = x + 1 #type conversions complete, string --> float Low = np.array(LowList) High = np.array(HighList) Close = np.array(PriceList) #Low, High, and Close converted to Array format (TA-Lib calls require Array) SARtoList = (talib.SAR(High, Low, acceleration = 0.2, maximum = 0.20)) BBandsArray = (talib.BBANDS(Close, timeperiod = 5, nbdevup = 2, nbdevdn = 2, matype = 0)) EMAList = talib.EMA(Close, timeperiod=30) KAMAList = talib.KAMA(Close, timeperiod=30) MAList = talib.MA(Close, timeperiod=30, matype=0) WMAList = talib.WMA(Close, timeperiod=30) TRIMAList = talib.TRIMA(Close, timeperiod=30) TEMAList = talib.TEMA(Close, timeperiod=30) HTList = talib.HT_TRENDLINE(Close) ADXList = talib.ADX(High, Low, Close, timeperiod=14) ADXRList = talib.ADXR(High, Low, Close, timeperiod=14) CMOList = talib.CMO(Close, timeperiod=14) DXList = talib.DX(High, Low, Close, timeperiod=14) MACDArray = talib.MACDFIX(Close, signalperiod=9) MINUS_DI_List = talib.MINUS_DI(High, Low, Close, timeperiod=14) PLUS_DI_List = talib.PLUS_DI(High, Low, Close, timeperiod=14) MOMList = talib.MOM(Close, timeperiod=10) RSIList = talib.RSI(Close, timeperiod=14) NATRList = talib.NATR(High, Low, Close, timeperiod=14) BETAList = talib.BETA(High, Low, timeperiod=5) ROCList = talib.ROC(Close, timeperiod=10) WILLRList = talib.WILLR(High, Low, Close, timeperiod=14) ULTOSCList = talib.ULTOSC(High, Low, Close, timeperiod1=7, timeperiod2=14, timeperiod3=28) #method calls to TA-Lib complete, results stored in SARtoList (list) and BBandsArray (array) toCombine = [] BBandsUpperDF = pd.DataFrame(BBandsArray[0], columns = ['Upper Band',]) toCombine.append(BBandsUpperDF) BBandsMiddleDF = pd.DataFrame(BBandsArray[1], columns = ['Middle Band',]) toCombine.append(BBandsMiddleDF) BBandsLowerDF = pd.DataFrame(BBandsArray[2], columns = ['Lower Band',]) toCombine.append(BBandsLowerDF) MACD_df = pd.DataFrame(MACDArray[0], columns = ['MACD',]) toCombine.append(MACD_df) MACD_Hist_df = pd.DataFrame(MACDArray[1], columns = ['MACD_Hist',]) toCombine.append(MACD_Hist_df) MACD_Sig_df = pd.DataFrame(MACDArray[2], columns = ['MACD_Sig',]) toCombine.append(MACD_Sig_df) DateDF = pd.DataFrame({'Date': DateList,}) toCombine.append(DateDF) SARdf = pd.DataFrame({'SAR': SARtoList,}) toCombine.append(SARdf) EMAdf = pd.DataFrame({'EMA': EMAList,}) toCombine.append(EMAdf) KAMAdf = pd.DataFrame({'KAMA': KAMAList,}) toCombine.append(KAMAdf) MAdf = pd.DataFrame({'MA': MAList,}) toCombine.append(MAdf) WMAdf = pd.DataFrame({'WMA': WMAList,}) toCombine.append(WMAdf) TRIMAdf = pd.DataFrame({'TRIMA': TRIMAList,}) toCombine.append(TRIMAdf) TEMAdf = pd.DataFrame({'TEMA': TEMAList,}) toCombine.append(TEMAdf) HTdf = pd.DataFrame({'HT Trendline': HTList,}) toCombine.append(HTdf) ADXdf = pd.DataFrame({'ADX': ADXList,}) toCombine.append(ADXdf) ADXRdf = pd.DataFrame({'ADXR': ADXRList,}) toCombine.append(ADXdf) CMOdf = pd.DataFrame({'CMO': CMOList,}) toCombine.append(CMOdf) MINUSDI_df = pd.DataFrame({'MINUSDI': MINUS_DI_List,}) toCombine.append(MINUSDI_df) PLUSDI_df = pd.DataFrame({'PLUSDI': PLUS_DI_List,}) toCombine.append(PLUSDI_df) MOMdf = pd.DataFrame({'MOM': MOMList,}) toCombine.append(MOMdf) RSIdf = pd.DataFrame({'RSI': RSIList,}) toCombine.append(RSIdf) NATRdf = pd.DataFrame({'NATR': NATRList,}) toCombine.append(NATRdf) BETAdf = pd.DataFrame({'BETA': BETAList,}) toCombine.append(BETAdf) ROCdf = pd.DataFrame({'ROC': ROCList,}) toCombine.append(ROCdf) WILLRdf = pd.DataFrame({'WILLR': WILLRList,}) toCombine.append(WILLRdf) ULTOSCdf = pd.DataFrame({'ULTOSC': ULTOSCList,}) toCombine.append(ULTOSCdf) #All data converted to DataFrame type TA_df = pd.concat(toCombine, axis = 1,) TA_df = TA_df.set_index('Date') return TA_df
def process_stock(ticker): returnString = "" buySignal = 0 sellSignal = 0 df = pd.read_csv(ticker) # print(df) if(not df.empty): # print(ticker) df["<DTYYYYMMDD>"] = pd.to_datetime(df["<DTYYYYMMDD>"], format="%Y%m%d") df.reset_index(inplace=True) df.set_index("<DTYYYYMMDD>", inplace=True) df = df.drop("<PER>", axis=1) df = df.drop("index", axis=1) # df = df.dropna(inplace=True) # print(df) df = df.iloc[::-1] else: return "", "" # print(df) #print(df['<CLOSE>']) RSI = ta.RSI(np.array(df['<CLOSE>'].astype(float)))#under 30 should buy, higher than 70 should sell if RSI[-1]<30: buySignal += 1 returnString += " RSI:buy " if RSI[-1]>70: sellSignal += 1 returnString += " RSI:sell " #print("RSI") #print(RSI) MA10 = ta.EMA(np.array(df['<CLOSE>'].astype(float)), timeperiod=10) #print("MA10")d #print(MA10) MA30 = ta.EMA(np.array(df['<CLOSE>'].astype(float)), timeperiod=30) #print("MA30") #print(MA30) MA50 = ta.EMA(np.array(df['<CLOSE>'].astype(float)), timeperiod=50)#exponantial moving average #print("MA50") #print(MA50) if((MA10[-1] >= MA30[-1] and MA10[-2] < MA30[-2]) or ((MA30[-1] >= MA50[-1] and MA30[-2] < MA50[-2]))): buySignal += 1 returnString += " MA:buy(simillar to MACDFIX) " if((MA10[-1] <= MA30[-1] and MA10[-2] > MA30[-2]) or (MA30[-1] <= MA50[-1] and MA30[-2] > MA50[-2])): sellSignal += 1 returnString += " MA:sell(simillar to MACDFIX) " SAR = ta.SAR(np.array(df['<HIGH>'].astype(float)), np.array(df['<LOW>'].astype(float)))#best for stable markets and may cause premature signals if(SAR[-2]<df['<CLOSE>'].iloc[-2] and SAR[-1]>=df['<CLOSE>'].iloc[-1]): sellSignal += 1 returnString += " SAR:buy(best for stable markets) " if(SAR[-2]>df['<CLOSE>'].iloc[-2] and SAR[-1]<=df['<CLOSE>'].iloc[-1]): buySignal += 1 returnString += " SAR:sell(best for stable markets) " #print("SAR") # print(SAR) # Stoch = ta.STOCH(np.array(df['<HIGH>']), np.array(df['<LOW>']), np.array(df['<CLOSE>'])) STOCH = np.array(STOD(df['<CLOSE>'], df['<LOW>'], df['<HIGH>'], 14))#Readings above 80 are considered overbought while readings below 20 are considered oversold. if STOCH[-1]<20: buySignal += 1 returnString += " STOCH:buy(similar to RSI) " if STOCH[-1]>80: sellSignal += 1 returnString += " STOCH:sell(similar to RSI) " # print("STOCH") # print(STOCH) ''' print(Stoch[0][8:].max()) print(Stoch[1].max()) for i in range(len(Stoch[0])-8): Stoch[0][i+8] = Stoch[0][i+8]/Stoch[0][8:].max()*100 Stoch[1][i+8] = Stoch[1][i+8]/Stoch[1][8:].max()*100 print(Stoch) ''' # ATR = ta.ATR(np.array(df['<HIGH>'].astype(float)), np.array(df['<LOW>'].astype(float)), np.array(df['<CLOSE>'].astype(float)), timeperiod=10)#difrrent in each case # print("ATR") # print(ATR) AD = ta.AD(np.array(df['<HIGH>'].astype(float)), np.array(df['<LOW>'].astype(float)), np.array(df['<CLOSE>'].astype(float)), np.array(df['<VOL>'], dtype=np.double))#Upward :more buying than selling if(AD[-1] > AD[-2] and AD[-2] > AD[-3]): buySignal += 1 returnString += " AD:buy(not defenitive) " elif(AD[-1] < AD[-2] and AD[-2] < AD[-3]): sellSignal += 1 returnString += " AD:sell(not defenitive) " # print("AD") # print(AD) ADX = ta.ADX(np.array(df['<HIGH>'].astype(float)), np.array(df['<LOW>'].astype(float)), np.array(df['<CLOSE>'].astype(float)))#readings below 20 that signal a weak trend or readings above 40 that signal a strong trend. if(ADX[-1]>40): buySignal += 1 sellSignal += 1 returnString += " ADX:strong trend " elif(ADX[-1]<20): buySignal -= 1 sellSignal -= 1 returnString += " ADX:week trend " # print("ADX") # print(ADX) AROONOSC = ta.AROONOSC(np.array(df['<HIGH>'].astype(float)), np.array(df['<LOW>'].astype(float))) if(AROONOSC[-1]>50): buySignal += 1 returnString += " AROONOSC:buy " elif(AROONOSC[-1]<-50): sellSignal += 1 returnString += " AROONOSC:sell " # print("AROONOSC") # print(AROONOSC) MACDFIX = ta.MACDFIX(np.array(df['<CLOSE>'].astype(float))) if(MACDFIX[0][-1]<0 and MACDFIX[0][-1]>=0): buySignal += 1 returnString += " MACDFIX:buy " if(MACDFIX[0][-1]>0 and MACDFIX[0][-1]<=0): sellSignal += 1 returnString += " MACDFIX:sell " # print(df['<CLOSE>']) # print(type(df['<DTYYYYMMDD>'].iloc[-1])) # print(MACDFIX) # plt.plot(df['<DTYYYYMMDD>'], df['<CLOSE>']) # df.plot(x='<DTYYYYMMDD>', y='<CLOSE>') # df['<CLOSE>'].plot() # plt.plot(ADX) # plt.plot(MACDFIX[1]) # plt.plot(MACDFIX[2]) # plt.legend(loc=4) # plt.xlabel('Date') # plt.ylabel('Price') # plt.show() # print(buySignal) # print(sellSignal) ''' if(buySignal>sellSignal and buySignal>=3): # print("buy: {}".format(buySignal)) return "buy: {}".format(buySignal) elif(buySignal<sellSignal and sellSignal>=3): # print("sell: {}".format(sellSignal)) return "sell: {}".format(sellSignal) else: # print("hold") return "hold" ''' return "buy: {} - sell: {}".format(buySignal, sellSignal), returnString '''
def all_algo(self,curr_pair_history_data,db=False): order = np.zeros((self.num_curr,7,3)) signal = np.zeros((self.num_curr,16)) for i in range(len(self.curr_pair_list)): # Processing data close5=(curr_pair_history_data[i]['closeAsk'].tail(5).values+\ curr_pair_history_data[i]['closeBid'].tail(5).values)/2 high5=(curr_pair_history_data[i]['highAsk'].tail(5).values+\ curr_pair_history_data[i]['highBid'].tail(5).values)/2 low5=(curr_pair_history_data[i]['lowAsk'].tail(5).values+\ curr_pair_history_data[i]['lowBid'].tail(5).values)/2 openv5=(curr_pair_history_data[i]['openAsk'].tail(5).values+\ curr_pair_history_data[i]['openBid'].tail(5).values)/2 close=(curr_pair_history_data[i]['closeAsk'].values+\ curr_pair_history_data[i]['closeBid'].values)/2 high=(curr_pair_history_data[i]['highAsk'].values+\ curr_pair_history_data[i]['highBid'].values)/2 low=(curr_pair_history_data[i]['lowAsk'].values+\ curr_pair_history_data[i]['lowBid'].values)/2 openv=(curr_pair_history_data[i]['openAsk'].values+\ curr_pair_history_data[i]['openBid'].values)/2 # Generating signals pattern=talib.CDL3BLACKCROWS(openv5,high5,low5,close5) pattern_signal=pattern[-1] adx=talib.ADX(high,low,close,timeperiod=14) rsi=talib.RSI(close,timeperiod=14) adx_signal=adx[-1] rsi_signal=rsi[-1] bull, bear=talib.AROON(high,low,timeperiod=14) sma=talib.SMA(close,timeperiod=30) kama=talib.KAMA(close,timeperiod=30) DIF,DEA,BAR=talib.MACDFIX(close,signalperiod=9) mfi=talib.MFI(high,low,close,curr_pair_history_data[i]['volume'].values.astype(float),timeperiod=14) mfi_signal=mfi[-1] # Storing signals signal[i,0] = pattern_signal signal[i,1] = adx_signal signal[i,13] = rsi_signal signal[i,2] = bear[-2] signal[i,3] = bear[-1] signal[i,4] = bull[-2] signal[i,5] = bull[-1] signal[i,10] = kama[-2] signal[i,11] = kama[-1] signal[i,14] = sma[-2] signal[i,15] = sma[-1] signal[i,6] = DEA[-2] signal[i,7] = DEA[-1] signal[i,8] = DIF[-2] signal[i,9] = DIF[-1] signal[i,12] = mfi_signal # Creating orders if pattern_signal>0: #trader.create_buy_order(ticker,units) order[i,0,1] = 1 elif pattern_signal<0: #trader.create_sell_order(ticker,units) order[i,0,2] = 1 else: #print('No trade made') order[i,0,0] = 1 if rsi_signal>70 and adx_signal>50: #trader.create_buy_order(ticker,units) order[i,1,1] = 1 elif rsi_signal<30 and adx_signal>50: #trader.create_sell_order(ticker,units) order[i,1,2] = 1 else: #print('No trade made') order[i,1,0] = 1 if rsi_signal>70: #trader.create_buy_order(ticker,units) order[i,6,1] = 1 elif rsi_signal<30: #trader.create_sell_order(ticker,units) order[i,6,2] = 1 else: #print('No trade made') order[i,6,0] = 1 if (bull[-1]>70 and bear[-1]<30) or (bull[-2]<bear[-2] and bull[-1]>=bear[-1]): #trader.create_buy_order(ticker,units) order[i,2,1] = 1 elif (bull[-1]<30 and bear[-1]>70) or (bull[-2]>=bear[-2] and bull[-1]<bear[-1]): #trader.create_sell_order(ticker,units) order[i,2,2] = 1 else: #print('No trade made') order[i,2,0] = 1 if kama[-1]>=sma[-1] and kama[-2]<sma[-2]: #trader.create_buy_order(ticker,units) order[i,3,1] = 1 elif kama[-1]<=sma[-1] and kama[-2]>=sma[-2]: #trader.create_sell_order(ticker,units) order[i,3,2] = 1 else: #print("No trade made") order[i,3,0] = 1 if DIF[-1]>0 and DEA[-1]>0 and DIF[-2]<DEA[-2] and DIF[-1]>DEA[-1]: #trader.create_buy_order(ticker,units) order[i,4,1] = 1 elif DIF[-1]<0 and DEA[-1]<0 and DIF[-2]>DEA[-2] and DIF[-1]<DEA[-1]: #trader.create_sell_order(ticker,units) order[i,4,2] = 1 else: #print("No trade made") order[i,4,0] = 1 if mfi_signal>70: #trader.create_buy_order(ticker,units) order[i,5,1] = 1 elif mfi_signal<30: #trader.create_sell_order(ticker,units) order[i,5,2] = 1 else: #print('No trade made') order[i,5,0] = 1 if db: #write to database here pass return order,signal