def tema(close, graph=False, **kwargs): ''' TEMA - Triple Exponential Moving Average ''' result = talib.TEMA(close, **kwargs) df = pd.concat([pd.DataFrame(close), pd.DataFrame(result)], axis=1) df.columns = ['close', 'tema'] if graph: title = 'TEMA - Triple Exponential Moving Average' style = ['r-'] + ['--'] * (len(df.columns) - 1) fname = '15_tema.png' make_graph(title, df, style=style, fname=fname) return df
def measure_tema(values_n: int, period: int): close = numpy.random.random(values_n) start = time.time_ns() output = TEMA(period, close) output[-1] t1 = (time.time_ns() - start) / 1000000 start = time.time_ns() output = talib.TEMA(close, timeperiod = period) output[-1] t2 = (time.time_ns() - start) / 1000000 t3 = 0.0 output = None for i in range(period, values_n): close = numpy.random.random(i) start = time.time_ns() output = talib.TEMA(close, timeperiod = period) t3 += (time.time_ns() - start) / 1000000 print(f"TEMA({period});{values_n:,};{round(t1, 3)};{round(t2, 3)};{round(t3, 3)}")
def add_TEMA(self, timeperiod=26, type="line", color="secondary", **kwargs): """Triple Moving Exponential Average.""" if not self.has_close: raise Exception() utils.kwargs_check(kwargs, VALID_TA_KWARGS) if "kind" in kwargs: type = kwargs["kind"] name = "TEMA({})".format(str(timeperiod)) self.pri[name] = dict(type=type, color=color) self.ind[name] = talib.TEMA(self.df[self.cl].values, timeperiod)
def test_tema(self): result = self.overlap.tema(self.close) self.assertIsInstance(result, Series) self.assertEqual(result.name, 'TEMA_10') try: expected = tal.TEMA(self.close, 10) pdt.assert_series_equal(result, expected, check_names=False) except AssertionError as ae: try: corr = pandas_ta.utils.df_error_analysis(result, expected, col=CORRELATION) self.assertGreater(corr, CORRELATION_THRESHOLD) except Exception as ex: error_analysis(result, CORRELATION, ex)
def trix(df, window=[11]): column = func.Cl(df) # iterate through each window for wind in window: # create labels label = 'trix' + str(wind) errlabel = label + 'err' # calc trix df[label] = ta.TEMA(column, wind) df[errlabel] = df[label] - 0 return df
def overlap(self): upper, middle, lower = talib.BBANDS(self.close,timeperiod=5,nbdevup=2,nbdevdn=2,matype=0) EMA = talib.EMA(self.close,self.period) HT_trendline = talib.HT_TRENDLINE(self.close) KAMA = talib.KAMA(self.close,self.period) MA = talib.MA(self.close,self.period,matype=0) mama, fama = talib.MAMA(self.close,fastlimit = 0.5,slowlimit = 0.05) mavp = talib.MAVP(self.close, minperiod = 5,maxperiod = 30,matype=0) midpoint = talib.MIDPOINT(self.close,self.period) midprice = talib.MIDPRICE(self.high,self.low,self.period) sar = talib.SAR(self.high,self.low,acceleration = 0, maximum = 0) sarext = talib.SAREXT(self.high,self.low,startvalue=0,offsetonreverse=0,accelerationinitlong=0, accelerationlong=0, accelerationmaxlong=0, accelerationinitshort=0, accelerationshort=0, accelerationmaxshort=0) sma = talib.SMA(self.close,self.period) t3 = talib.T3(self.close, self.period, vfactor = 0) tema = talib.TEMA(self.close,self.period) trima = talib.TRIMA(self.close,period) wma = talib.WMA(self.close, self.period)
def triple_EMA(self, df, period): """Triple MA a smoothing indicator with less lag than a straight exponential moving average. Args: close: Closing price of instrument period: number of time periods in the calculation feature_dict: Dictionary of added features Return: tripleEMA feature_dict """ col_name = 'TripleEMA_' + str(period) current_feature['Latest'] = col_name feature_dict[col_name] = 'Keep' df[col_name] = ta.TEMA(df.Close, period) return df
def init_state(indata, test=False): openn = indata['open'].values close = indata['close'].values high = indata['high'].values low = indata['low'].values volume = indata['volume'].values diff = np.diff(close) diff = np.insert(diff, 0, 0) sma30 = talib.SMA(close, 30) sma60 = talib.SMA(close, timeperiod=60) rsi = talib.RSI(close, timeperiod=14) atr = talib.ATR(high, low, close, timeperiod=14) trange = talib.TRANGE(high, low, close) macd, macdsignal, macdhist = talib.MACD(close, 12, 26, 9) upper, middle, lower = talib.BBANDS(close, 20, 2, 2) ema = talib.EMA(close, 30) ma = talib.MA(close, 30) wma = talib.WMA(close, timeperiod=30) tema = talib.TEMA(close, 30) obv = talib.OBV(close, np.asarray(volume, dtype='float')) adx = talib.ADX(high, low, close, 14) apo = talib.APO(close, 12, 2, 0) bop = talib.BOP(openn, high, low, close) mom = talib.MOM(close,10) ppo = talib.PPO(close, 12, 26, 0) slowk, slowd = talib.STOCH(high, low, close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) ad = talib.AD(high, low, close, np.asarray(volume, dtype='float')) wcl = talib.WCLPRICE(high, low, close) #--- Preprocess data xdata = np.column_stack((close, diff, sma30, sma60, rsi, atr, macd, macdsignal, macdhist, lower, middle, upper, ema, ma, wma, adx, apo, bop, mom, ppo, slowk, slowd, trange, wcl)) xdata = np.nan_to_num(xdata) if test == False: scaler = preprocessing.StandardScaler() xdata = np.expand_dims(scaler.fit_transform(xdata), axis=1) joblib.dump(scaler, 'data/scaler.pkl') elif test == True: scaler = joblib.load('data/scaler.pkl') xdata = np.expand_dims(scaler.fit_transform(xdata), axis=1) state = xdata[0:1, 0:1, :] return state, xdata, close
def ts_analysis(self, event=None): print("Time series analysis for CLOSE position") timeperiod = int(self.ui.timeperiod_test.value()) # Integration n = 1 integr = np.diff(self.closep, n=n) date1 = self.date[n:] first_not_nan_index = 3 * timeperiod - 3 date2 = date1[first_not_nan_index + 1:] _TEMA = talib.TEMA(integr, timeperiod=timeperiod)[first_not_nan_index + 1:] # Autocorrelation fig = plt.figure("Time series analysis for CLOSE position", figsize=(12, 8)) ax0 = fig.add_subplot(411) ax0.set_title("Original timeseries (TEMA)") ax0.grid() ax0.plot(self.date, self.candle_price_TEMA, '-bo') ax1 = fig.add_subplot(412, sharex=ax0) ax1.set_title("Integrated original timeseries. diff=1 (TEMA)") ax1.grid() ax1.axis('on') # ax1.axhline(0, color='k') # ax0.plot(date1, integr, 'b') ax1.plot(date2, _TEMA, 'r') lags = int(100) ax2 = fig.add_subplot(413) fig = sm.graphics.tsa.plot_acf(_TEMA, lags=lags, ax=ax2) ax3 = fig.add_subplot(414) fig = sm.graphics.tsa.plot_pacf(_TEMA, lags=lags, ax=ax3) fig.set_tight_layout(True) # plt.tight_layout() plt.show()
def handle_data(context): # 获取历史数据, 取后window根bar hist = context.data.get_price(context.security, count=context.user_data.team_window * 4, frequency=context.frequency) if len(hist.index) < context.user_data.team_window * 4: context.log.warn("bar的数量不足, 等待下一根bar...") return # 历史收盘价 close = np.array(hist["close"]) # 初始化买入/卖出信号 long_signal_triggered = False short_signal_triggered = False # 计算指标值 tema = talib.TEMA(close, timeperiod=context.user_data.team_window) current_price = context.data.get_current_price(context.security) # 产生买入/卖出信号 if current_price > tema[-1]: long_signal_triggered = True elif current_price < tema[-1]: short_signal_triggered = True # 有卖出信号,且持有仓位,则全仓卖出 if short_signal_triggered: if context.account.huobi_cny_btc >= HUOBI_CNY_BTC_MIN_ORDER_QUANTITY: context.log.info("正在卖出 %s" % context.security) context.log.info("卖出数量为 %s" % context.account.huobi_cny_btc) context.order.sell(context.security, quantity=str(context.account.huobi_cny_btc)) else: context.log.info("仓位不足,无法卖出") # 有买入信号,且持有现金,则全仓买入 elif long_signal_triggered: if context.account.huobi_cny_cash >= HUOBI_CNY_BTC_MIN_ORDER_CASH_AMOUNT: context.log.info("正在买入 %s" % context.security) context.log.info("下单金额为 %s 元" % context.account.huobi_cny_cash) context.order.buy(context.security, cash_amount=str(context.account.huobi_cny_cash)) else: context.log.info("现金不足,无法下单") else: context.log.info("无交易信号,进入下一根bar")
def test_TEMA(self): class MyTEMA(OperatorTEMA): def __init__(self, name, **kwargs): super(MyTEMA, self).__init__(100, name, **kwargs) self.env.add_operator('tema', { 'operator': MyTEMA, }) string = 'tema(30, open)' gene = self.env.parse_string(string) self.assertRaises(IndexError, gene.eval, self.env, self.dates[98], self.dates[-1]) ser = gene.eval(self.env, self.dates[99], self.dates[99]).iloc[0] o = self.env.get_data_value('open').values res = [] for i, val in ser.iteritems(): res.append(talib.TEMA(o[:100, i], 30)[-1] == val) self.assertTrue(all(res))
def tema(candles: np.ndarray, period=9, sequential=False) -> Union[float, np.ndarray]: """ TEMA - Triple Exponential Moving Average :param candles: np.ndarray :param period: int - default: 9 :param sequential: bool - default=False :return: float | np.ndarray """ if not sequential and len(candles) > 240: candles = candles[-240:] res = talib.TEMA(candles[:, 2], timeperiod=period) return res if sequential else res[-1]
def tema(candles: np.ndarray, period: int = 9, source_type: str = "close", sequential: bool = False) -> Union[ float, np.ndarray]: """ TEMA - Triple Exponential Moving Average :param candles: np.ndarray :param period: int - default: 9 :param source_type: str - default: "close" :param sequential: bool - default=False :return: float | np.ndarray """ if not sequential and len(candles) > 240: candles = candles[-240:] source = get_candle_source(candles, source_type=source_type) res = talib.TEMA(source, timeperiod=period) return res if sequential else res[-1]
def getIndicators(currency, period, ind_length): # 2D array of 5 market indicators date_arr, market = db_access.read_table(currency, period) date_t = (date_arr[:, 0].flatten()) #date_t = np.array([[date_t,date_t],[date_t,date_t]],dtype='M8[m]').astype('O')[0,1] close_price = market[:, 5].flatten() volume = market[:, 1].flatten() high = market[:, 3].flatten() low = market[:, 4].flatten() rsi_long = talib.RSI(close_price, ind_length['rsi_l']) # @UndefinedVariable rsi_short = talib.RSI(close_price, ind_length['rsi_s']) # @UndefinedVariable tema_result = talib.TEMA(close_price, 30) # @UndefinedVariable on_balance = talib.OBV(close_price, volume) # @UndefinedVariable # will_r = talib.WILLR(high, low, close_price, timeperiod=1440) # @UndefinedVariable #will_r = talib.LINEARREG_ANGLE(close_price, timeperiod=ind_length['reg']) # @UndefinedVariable return date_arr, close_price, rsi_long, rsi_short, tema_result, on_balance
def get_df(filename): tech = pd.read_csv(filename,index_col=0) dclose = np.array(tech.close) volume = np.array(tech.volume) tech['RSI'] = ta.RSI(np.array(tech.close)) tech['OBV'] = ta.OBV(np.array(tech.close),np.array(tech.volume)) tech['NATR'] = ta.NATR(np.array(tech.high),np.array(tech.low),np.array(tech.close)) tech['upper'],tech['middle'],tech['lower'] = ta.BBANDS(np.array(tech.close), timeperiod=10, nbdevup=2, nbdevdn=2, matype=0) tech['DEMA'] = ta.DEMA(dclose, timeperiod=30) tech['EMA'] = ta.EMA(dclose, timeperiod=30) tech['HT_TRENDLINE'] = ta.HT_TRENDLINE(dclose) tech['KAMA'] = ta.KAMA(dclose, timeperiod=30) tech['MA'] = ta.MA(dclose, timeperiod=30, matype=0) # tech['mama'], tech['fama'] = ta.MAMA(dclose, fastlimit=0, slowlimit=0) tech['MIDPOINT'] = ta.MIDPOINT(dclose, timeperiod=14) tech['SMA'] = ta.SMA(dclose, timeperiod=30) tech['T3'] = ta.T3(dclose, timeperiod=5, vfactor=0) tech['TEMA'] = ta.TEMA(dclose, timeperiod=30) tech['TRIMA'] = ta.TRIMA(dclose, timeperiod=30) tech['WMA'] = ta.WMA(dclose, timeperiod=30) tech['APO'] = ta.APO(dclose, fastperiod=12, slowperiod=26, matype=0) tech['CMO'] = ta.CMO(dclose, timeperiod=14) tech['macd'], tech['macdsignal'], tech['macdhist'] = ta.MACD(dclose, fastperiod=12, slowperiod=26, signalperiod=9) tech['MOM'] = ta.MOM(dclose, timeperiod=10) tech['PPO'] = ta.PPO(dclose, fastperiod=12, slowperiod=26, matype=0) tech['ROC'] = ta.ROC(dclose, timeperiod=10) tech['ROCR'] = ta.ROCR(dclose, timeperiod=10) tech['ROCP'] = ta.ROCP(dclose, timeperiod=10) tech['ROCR100'] = ta.ROCR100(dclose, timeperiod=10) tech['RSI'] = ta.RSI(dclose, timeperiod=14) tech['fastk'], tech['fastd'] = ta.STOCHRSI(dclose, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0) tech['TRIX'] = ta.TRIX(dclose, timeperiod=30) tech['OBV'] = ta.OBV(dclose,volume) tech['HT_DCPHASE'] = ta.HT_DCPHASE(dclose) tech['inphase'], tech['quadrature'] = ta.HT_PHASOR(dclose) tech['sine'], tech['leadsine'] = ta.HT_SINE(dclose) tech['HT_TRENDMODE'] = ta.HT_TRENDMODE(dclose) df = tech.fillna(method='bfill') return df
def getOverlapFunctions(df): high = df['High'] low = df['Low'] close = df['Close'] open = df['Open'] volume = df['Volume'] df['UPPERBB'],df['MIDDLEBB'],df['LOWERBB'] = ta.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0) df['DEMA'] = ta.DEMA(close,timeperiod=30) df['EMA'] = ta.EMA(close, timeperiod=30) df['HT_TREND'] = ta.HT_TRENDLINE(close) df['KAMA'] = ta.KAMA(close, timeperiod=30) df['MA'] = ta.MA(close, timeperiod=30, matype=0) #df['MAMA'],df['FAMA'] = ta.MAMA(close, fastlimit=0, slowlimit=0) #df['MAVP'] = ta.MAVP(close, periods, minperiod=2, maxperiod=30, matype=0) df['MIDPOINT'] = ta.MIDPOINT(close, timeperiod=14) df['MIDPRICE'] = ta.MIDPRICE(high, low, timeperiod=14) df['SAR'] = ta.SAR(high, low, acceleration=0, maximum=0) df['SAREXT'] = ta.SAREXT(high, low, startvalue=0, offsetonreverse=0, accelerationinitlong=0, accelerationlong=0, accelerationmaxlong=0, accelerationinitshort=0, accelerationshort=0, accelerationmaxshort=0) df['SMA'] = ta.SMA(close, timeperiod=30) df['T3'] = ta.T3(close, timeperiod=5, vfactor=0) df['TEMA'] = ta.TEMA(close, timeperiod=30) df['TRIMA'] = ta.TRIMA(close, timeperiod=30) df['WMA'] = ta.WMA(close, timeperiod=30)
def tema(client, symbol, timeframe="6m", col="close", periods=None): """This will return a dataframe of triple exponential moving average for the given symbol across the given timeframe Args: client (pyEX.Client); Client symbol (string); Ticker timeframe (string); timeframe to use, for pyEX.chart col (string); column to use to calculate periods (int); periods Returns: DataFrame: result """ if periods is None: periods = [30] periods = tolist(periods) df = client.chartDF(symbol, timeframe) build = {col: df[col].values} for per in periods: build["sma-{}".format(per)] = t.TEMA(df[col].values.astype(float), per) return pd.DataFrame(build)
def get_average_studies(open, low, high, close, df): # https://mrjbq7.github.io/ta-lib/func_groups/overlap_studies.html # Bollinger bands df['UP_BB'], df['MID_BB'], df['LOW_BB'] = talib.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0) # HT_TRENDLINE - Hilbert Transform - Instantaneous Trendline df["HT"] = talib.HT_TRENDLINE(close) # SAR - Parabolic SAR df["SAR"] = talib.SAR(high, low, acceleration=0, maximum=0) # periods = [5, 15, 30, 50, 100, 200] for period in periods: df['SMA-' + str(period)] = talib.SMA(close, timeperiod=period) df['DEMA-' + str(period)] = talib.DEMA(close, timeperiod=period) df['TEMA-' + str(period)] = talib.TEMA(close, timeperiod=period) df['WMA-' + str(period)] = talib.WMA(close, timeperiod=period) df['MIDPOINT-' + str(period)] = talib.MIDPOINT(close, timeperiod=period) df['MIDPRICE-' + str(period)] = talib.MIDPRICE(high, low, timeperiod=period)
def calc_features(df): open = df['op'] high = df['hi'] low = df['lo'] close = df['cl'] volume = df['volume'] orig_columns = df.columns hilo = (df['hi'] + df['lo']) / 2 df['BBANDS_upperband'], df['BBANDS_middleband'], df[ 'BBANDS_lowerband'] = talib.BBANDS(close, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0) df['BBANDS_upperband'] -= hilo df['BBANDS_middleband'] -= hilo df['BBANDS_lowerband'] -= hilo df['DEMA'] = talib.DEMA(close, timeperiod=30) - hilo df['EMA'] = talib.EMA(close, timeperiod=30) - hilo df['HT_TRENDLINE'] = talib.HT_TRENDLINE(close) - hilo df['KAMA'] = talib.KAMA(close, timeperiod=30) - hilo df['MA'] = talib.MA(close, timeperiod=30, matype=0) - hilo df['MIDPOINT'] = talib.MIDPOINT(close, timeperiod=14) - hilo df['SMA'] = talib.SMA(close, timeperiod=30) - hilo df['T3'] = talib.T3(close, timeperiod=5, vfactor=0) - hilo df['TEMA'] = talib.TEMA(close, timeperiod=30) - hilo df['TRIMA'] = talib.TRIMA(close, timeperiod=30) - hilo df['WMA'] = talib.WMA(close, timeperiod=30) - hilo df['ADX'] = talib.ADX(high, low, close, timeperiod=14) df['ADXR'] = talib.ADXR(high, low, close, timeperiod=14) df['APO'] = talib.APO(close, fastperiod=12, slowperiod=26, matype=0) df['AROON_aroondown'], df['AROON_aroonup'] = talib.AROON(high, low, timeperiod=14) df['AROONOSC'] = talib.AROONOSC(high, low, timeperiod=14) df['BOP'] = talib.BOP(open, high, low, close) df['CCI'] = talib.CCI(high, low, close, timeperiod=14) df['DX'] = talib.DX(high, low, close, timeperiod=14) df['MACD_macd'], df['MACD_macdsignal'], df['MACD_macdhist'] = talib.MACD( close, fastperiod=12, slowperiod=26, signalperiod=9) # skip MACDEXT MACDFIX たぶん同じなので df['MFI'] = talib.MFI(high, low, close, volume, timeperiod=14) df['MINUS_DI'] = talib.MINUS_DI(high, low, close, timeperiod=14) df['MINUS_DM'] = talib.MINUS_DM(high, low, timeperiod=14) df['MOM'] = talib.MOM(close, timeperiod=10) df['PLUS_DI'] = talib.PLUS_DI(high, low, close, timeperiod=14) df['PLUS_DM'] = talib.PLUS_DM(high, low, timeperiod=14) df['RSI'] = talib.RSI(close, timeperiod=14) df['STOCH_slowk'], df['STOCH_slowd'] = talib.STOCH(high, low, close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) df['STOCHF_fastk'], df['STOCHF_fastd'] = talib.STOCHF(high, low, close, fastk_period=5, fastd_period=3, fastd_matype=0) df['STOCHRSI_fastk'], df['STOCHRSI_fastd'] = talib.STOCHRSI(close, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0) df['TRIX'] = talib.TRIX(close, timeperiod=30) df['ULTOSC'] = talib.ULTOSC(high, low, close, timeperiod1=7, timeperiod2=14, timeperiod3=28) df['WILLR'] = talib.WILLR(high, low, close, timeperiod=14) df['AD'] = talib.AD(high, low, close, volume) df['ADOSC'] = talib.ADOSC(high, low, close, volume, fastperiod=3, slowperiod=10) df['OBV'] = talib.OBV(close, volume) df['ATR'] = talib.ATR(high, low, close, timeperiod=14) df['NATR'] = talib.NATR(high, low, close, timeperiod=14) df['TRANGE'] = talib.TRANGE(high, low, close) df['HT_DCPERIOD'] = talib.HT_DCPERIOD(close) df['HT_DCPHASE'] = talib.HT_DCPHASE(close) df['HT_PHASOR_inphase'], df['HT_PHASOR_quadrature'] = talib.HT_PHASOR( close) df['HT_SINE_sine'], df['HT_SINE_leadsine'] = talib.HT_SINE(close) df['HT_TRENDMODE'] = talib.HT_TRENDMODE(close) df['BETA'] = talib.BETA(high, low, timeperiod=5) df['CORREL'] = talib.CORREL(high, low, timeperiod=30) df['LINEARREG'] = talib.LINEARREG(close, timeperiod=14) - close df['LINEARREG_ANGLE'] = talib.LINEARREG_ANGLE(close, timeperiod=14) df['LINEARREG_INTERCEPT'] = talib.LINEARREG_INTERCEPT( close, timeperiod=14) - close df['LINEARREG_SLOPE'] = talib.LINEARREG_SLOPE(close, timeperiod=14) df['STDDEV'] = talib.STDDEV(close, timeperiod=5, nbdev=1) return df
def get_factors(index, Open, Close, High, Low, Volume, rolling=26, drop=False, normalization=True): tmp = pd.DataFrame() tmp['tradeTime'] = index # 累积/派发线(Accumulation / Distribution Line,该指标将每日的成交量通过价格加权累计, # 用以计算成交量的动量。属于趋势型因子 tmp['AD'] = talib.AD(High, Low, Close, Volume) # 佳庆指标(Chaikin Oscillator),该指标基于AD曲线的指数移动均线而计算得到。属于趋势型因子 tmp['ADOSC'] = talib.ADOSC(High, Low, Close, Volume, fastperiod=3, slowperiod=10) # 平均动向指数,DMI因子的构成部分。属于趋势型因子 tmp['ADX'] = talib.ADX(High, Low, Close, timeperiod=14) # 相对平均动向指数,DMI因子的构成部分。属于趋势型因子 tmp['ADXR'] = talib.ADXR(High, Low, Close, timeperiod=14) # 绝对价格振荡指数 tmp['APO'] = talib.APO(Close, fastperiod=12, slowperiod=26) # Aroon通过计算自价格达到近期最高值和最低值以来所经过的期间数,帮助投资者预测证券价格从趋势到区域区域或反转的变化, # Aroon指标分为Aroon、AroonUp和AroonDown3个具体指标。属于趋势型因子 tmp['AROONDown'], tmp['AROONUp'] = talib.AROON(High, Low, timeperiod=14) tmp['AROONOSC'] = talib.AROONOSC(High, Low, timeperiod=14) # 均幅指标(Average TRUE Ranger),取一定时间周期内的股价波动幅度的移动平均值, # 是显示市场变化率的指标,主要用于研判买卖时机。属于超买超卖型因子。 tmp['ATR14'] = talib.ATR(High, Low, Close, timeperiod=14) tmp['ATR6'] = talib.ATR(High, Low, Close, timeperiod=6) # 布林带 tmp['Boll_Up'], tmp['Boll_Mid'], tmp['Boll_Down'] = talib.BBANDS( Close, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0) # 均势指标 tmp['BOP'] = talib.BOP(Open, High, Low, Close) # 5日顺势指标(Commodity Channel Index),专门测量股价是否已超出常态分布范围。属于超买超卖型因子。 tmp['CCI5'] = talib.CCI(High, Low, Close, timeperiod=5) tmp['CCI10'] = talib.CCI(High, Low, Close, timeperiod=10) tmp['CCI20'] = talib.CCI(High, Low, Close, timeperiod=20) tmp['CCI88'] = talib.CCI(High, Low, Close, timeperiod=88) # 钱德动量摆动指标(Chande Momentum Osciliator),与其他动量指标摆动指标如相对强弱指标(RSI)和随机指标(KDJ)不同, # 钱德动量指标在计算公式的分子中采用上涨日和下跌日的数据。属于超买超卖型因子 tmp['CMO_Close'] = talib.CMO(Close, timeperiod=14) tmp['CMO_Open'] = talib.CMO(Close, timeperiod=14) # DEMA双指数移动平均线 tmp['DEMA6'] = talib.DEMA(Close, timeperiod=6) tmp['DEMA12'] = talib.DEMA(Close, timeperiod=12) tmp['DEMA26'] = talib.DEMA(Close, timeperiod=26) # DX 动向指数 tmp['DX'] = talib.DX(High, Low, Close, timeperiod=14) # EMA 指数移动平均线 tmp['EMA6'] = talib.EMA(Close, timeperiod=6) tmp['EMA12'] = talib.EMA(Close, timeperiod=12) tmp['EMA26'] = talib.EMA(Close, timeperiod=26) # KAMA 适应性移动平均线 tmp['KAMA'] = talib.KAMA(Close, timeperiod=30) # MACD tmp['MACD_DIF'], tmp['MACD_DEA'], tmp['MACD_bar'] = talib.MACD( Close, fastperiod=12, slowperiod=24, signalperiod=9) # 中位数价格 不知道是什么意思 tmp['MEDPRICE'] = talib.MEDPRICE(High, Low) # 负向指标 负向运动 tmp['MiNUS_DI'] = talib.MINUS_DI(High, Low, Close, timeperiod=14) tmp['MiNUS_DM'] = talib.MINUS_DM(High, Low, timeperiod=14) # 动量指标(Momentom Index),动量指数以分析股价波动的速度为目的,研究股价在波动过程中各种加速, # 减速,惯性作用以及股价由静到动或由动转静的现象。属于趋势型因子 tmp['MOM'] = talib.MOM(Close, timeperiod=10) # 归一化平均值范围 tmp['NATR'] = talib.NATR(High, Low, Close, timeperiod=14) # OBV 能量潮指标(On Balance Volume,OBV),以股市的成交量变化来衡量股市的推动力, # 从而研判股价的走势。属于成交量型因子 tmp['OBV'] = talib.OBV(Close, Volume) # PLUS_DI 更向指示器 tmp['PLUS_DI'] = talib.PLUS_DI(High, Low, Close, timeperiod=14) tmp['PLUS_DM'] = talib.PLUS_DM(High, Low, timeperiod=14) # PPO 价格振荡百分比 tmp['PPO'] = talib.PPO(Close, fastperiod=6, slowperiod=26, matype=0) # ROC 6日变动速率(Price Rate of Change),以当日的收盘价和N天前的收盘价比较, # 通过计算股价某一段时间内收盘价变动的比例,应用价格的移动比较来测量价位动量。属于超买超卖型因子。 tmp['ROC6'] = talib.ROC(Close, timeperiod=6) tmp['ROC20'] = talib.ROC(Close, timeperiod=20) # 12日量变动速率指标(Volume Rate of Change),以今天的成交量和N天前的成交量比较, # 通过计算某一段时间内成交量变动的幅度,应用成交量的移动比较来测量成交量运动趋向, # 达到事先探测成交量供需的强弱,进而分析成交量的发展趋势及其将来是否有转势的意愿, # 属于成交量的反趋向指标。属于成交量型因子 tmp['VROC6'] = talib.ROC(Volume, timeperiod=6) tmp['VROC20'] = talib.ROC(Volume, timeperiod=20) # ROC 6日变动速率(Price Rate of Change),以当日的收盘价和N天前的收盘价比较, # 通过计算股价某一段时间内收盘价变动的比例,应用价格的移动比较来测量价位动量。属于超买超卖型因子。 tmp['ROCP6'] = talib.ROCP(Close, timeperiod=6) tmp['ROCP20'] = talib.ROCP(Close, timeperiod=20) # 12日量变动速率指标(Volume Rate of Change),以今天的成交量和N天前的成交量比较, # 通过计算某一段时间内成交量变动的幅度,应用成交量的移动比较来测量成交量运动趋向, # 达到事先探测成交量供需的强弱,进而分析成交量的发展趋势及其将来是否有转势的意愿, # 属于成交量的反趋向指标。属于成交量型因子 tmp['VROCP6'] = talib.ROCP(Volume, timeperiod=6) tmp['VROCP20'] = talib.ROCP(Volume, timeperiod=20) # RSI tmp['RSI'] = talib.RSI(Close, timeperiod=14) # SAR 抛物线转向 tmp['SAR'] = talib.SAR(High, Low, acceleration=0.02, maximum=0.2) # TEMA tmp['TEMA6'] = talib.TEMA(Close, timeperiod=6) tmp['TEMA12'] = talib.TEMA(Close, timeperiod=12) tmp['TEMA26'] = talib.TEMA(Close, timeperiod=26) # TRANGE 真实范围 tmp['TRANGE'] = talib.TRANGE(High, Low, Close) # TYPPRICE 典型价格 tmp['TYPPRICE'] = talib.TYPPRICE(High, Low, Close) # TSF 时间序列预测 tmp['TSF'] = talib.TSF(Close, timeperiod=14) # ULTOSC 极限振子 tmp['ULTOSC'] = talib.ULTOSC(High, Low, Close, timeperiod1=7, timeperiod2=14, timeperiod3=28) # 威廉指标 tmp['WILLR'] = talib.WILLR(High, Low, Close, timeperiod=14) # 标准化 if normalization: factors_list = tmp.columns.tolist()[1:] if rolling >= 26: for i in factors_list: tmp[i] = (tmp[i] - tmp[i].rolling(window=rolling, center=False).mean()) \ / tmp[i].rolling(window=rolling, center=False).std() elif rolling < 26 & rolling > 0: print('Recommended rolling range greater than 26') elif rolling <= 0: for i in factors_list: tmp[i] = (tmp[i] - tmp[i].mean()) / tmp[i].std() if drop: tmp.dropna(inplace=True) tmp.set_index('tradeTime', inplace=True) return tmp
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 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 main(): ohlcv = api_ohlcv('20191017') open, high, low, close, volume, timestamp = [], [], [], [], [], [] for i in ohlcv: open.append(int(i[0])) high.append(int(i[1])) low.append(int(i[2])) close.append(int(i[3])) volume.append(float(i[4])) time_str = str(i[5]) timestamp.append( datetime.fromtimestamp(int( time_str[:10])).strftime('%Y/%m/%d %H:%M:%M')) date_time_index = pd.to_datetime( timestamp) # convert to DateTimeIndex type df = pd.DataFrame( { 'open': open, 'high': high, 'low': low, 'close': close, 'volume': volume }, index=date_time_index) # df.index += pd.offsets.Hour(9) # adjustment for JST if required print(df.shape) print(df.columns) # pct_change f = lambda x: 1 if x > 0.0001 else -1 if x < -0.0001 else 0 if -0.0001 <= x <= 0.0001 else np.nan y = df.rename(columns={ 'close': 'y' }).loc[:, 'y'].pct_change(1).shift(-1).fillna(0) X = df.copy() y_ = pd.DataFrame(y.map(f), columns=['y']) y = df.rename(columns={'close': 'y'}).loc[:, 'y'].pct_change(1).fillna(0) df_ = pd.concat([X, y_], axis=1) # check the shape print( '----------------------------------------------------------------------------------------' ) print('X shape: (%i,%i)' % X.shape) print('y shape: (%i,%i)' % y_.shape) print( '----------------------------------------------------------------------------------------' ) print(y_.groupby('y').size()) print('y=1 up, y=0 stay, y=-1 down') print( '----------------------------------------------------------------------------------------' ) # feature calculation open = pd.Series(df['open']) high = pd.Series(df['high']) low = pd.Series(df['low']) close = pd.Series(df['close']) volume = pd.Series(df['volume']) # pct_change for new column X['diff'] = y # Exponential Moving Average ema = talib.EMA(close, timeperiod=3) ema = ema.fillna(ema.mean()) # Momentum momentum = talib.MOM(close, timeperiod=5) momentum = momentum.fillna(momentum.mean()) # RSI rsi = talib.RSI(close, timeperiod=14) rsi = rsi.fillna(rsi.mean()) # ADX adx = talib.ADX(high, low, close, timeperiod=14) adx = adx.fillna(adx.mean()) # ADX change adx_change = adx.pct_change(1).shift(-1) adx_change = adx_change.fillna(adx_change.mean()) # AD ad = talib.AD(high, low, close, volume) ad = ad.fillna(ad.mean()) X_ = pd.concat([X, ema, momentum, rsi, adx_change, ad], axis=1).drop(['open', 'high', 'low', 'close'], axis=1) X_.columns = ['volume', 'diff', 'ema', 'momentum', 'rsi', 'adx', 'ad'] X_.join(y_).head(10) # default parameter models X_train, X_test, y_train, y_test = train_test_split(X_, y_, test_size=0.33, random_state=42) print('X_train shape: {}'.format(X_train.shape)) print('X_test shape: {}'.format(X_test.shape)) print('y_train shape: {}'.format(y_train.shape)) print('y_test shape: {}'.format(y_test.shape)) pipe_knn = Pipeline([('scl', StandardScaler()), ('est', KNeighborsClassifier(n_neighbors=3))]) pipe_logistic = Pipeline([('scl', StandardScaler()), ('est', LogisticRegression(solver='lbfgs', multi_class='multinomial', random_state=39))]) pipe_rf = Pipeline([('scl', StandardScaler()), ('est', RandomForestClassifier(random_state=39))]) pipe_gb = Pipeline([('scl', StandardScaler()), ('est', GradientBoostingClassifier(random_state=39))]) pipe_names = ['KNN', 'Logistic', 'RandomForest', 'GradientBoosting'] pipe_lines = [pipe_knn, pipe_logistic, pipe_rf, pipe_gb] for (i, pipe) in enumerate(pipe_lines): pipe.fit(X_train, y_train.values.ravel()) print(pipe) print('%s: %.3f' % (pipe_names[i] + ' Train Accuracy', accuracy_score(y_train.values.ravel(), pipe.predict(X_train)))) print('%s: %.3f' % (pipe_names[i] + ' Test Accuracy', accuracy_score(y_test.values.ravel(), pipe.predict(X_test)))) print('%s: %.3f' % (pipe_names[i] + ' Train F1 Score', f1_score(y_train.values.ravel(), pipe.predict(X_train), average='micro'))) print('%s: %.3f' % (pipe_names[i] + ' Test F1 Score', f1_score(y_test.values.ravel(), pipe.predict(X_test), average='micro'))) for (i, pipe) in enumerate(pipe_lines): predict = pipe.predict(X_test) cm = confusion_matrix(y_test.values.ravel(), predict, labels=[-1, 0, 1]) print('{} Confusion Matrix'.format(pipe_names[i])) print(cm) ## Overlap Studies Functions # DEMA - Double Exponential Moving Average dema = talib.DEMA(close, timeperiod=3) dema = dema.fillna(dema.mean()) print('DEMA - Double Exponential Moving Average shape: {}'.format( dema.shape)) # EMA - Exponential Moving Average ema = talib.EMA(close, timeperiod=3) ema = ema.fillna(ema.mean()) print('EMA - Exponential Moving Average shape: {}'.format(ema.shape)) # HT_TRENDLINE - Hilbert Transform - Instantaneous Trendline hilbert = talib.HT_TRENDLINE(close) hilbert = hilbert.fillna(hilbert.mean()) print( 'HT_TRENDLINE - Hilbert Transform - Instantaneous Trendline shape: {}'. format(hilbert.shape)) # KAMA - Kaufman Adaptive Moving Average kama = talib.KAMA(close, timeperiod=3) kama = kama.fillna(kama.mean()) print('KAMA - Kaufman Adaptive Moving Average shape: {}'.format( kama.shape)) # MA - Moving average ma = talib.MA(close, timeperiod=3, matype=0) ma = ma.fillna(ma.mean()) print('MA - Moving average shape: {}'.format(kama.shape)) # MIDPOINT - MidPoint over period midpoint = talib.MIDPOINT(close, timeperiod=7) midpoint = midpoint.fillna(midpoint.mean()) print('MIDPOINT - MidPoint over period shape: {}'.format(midpoint.shape)) # MIDPRICE - Midpoint Price over period midprice = talib.MIDPRICE(high, low, timeperiod=7) midprice = midprice.fillna(midprice.mean()) print('MIDPRICE - Midpoint Price over period shape: {}'.format( midprice.shape)) # SAR - Parabolic SAR sar = talib.SAR(high, low, acceleration=0, maximum=0) sar = sar.fillna(sar.mean()) print('SAR - Parabolic SAR shape: {}'.format(sar.shape)) # SAREXT - Parabolic SAR - Extended sarext = talib.SAREXT(high, low, startvalue=0, offsetonreverse=0, accelerationinitlong=0, accelerationlong=0, accelerationmaxlong=0, accelerationinitshort=0, accelerationshort=0, accelerationmaxshort=0) sarext = sarext.fillna(sarext.mean()) print('SAREXT - Parabolic SAR - Extended shape: {}'.format(sarext.shape)) # SMA - Simple Moving Average sma = talib.SMA(close, timeperiod=3) sma = sma.fillna(sma.mean()) print('SMA - Simple Moving Average shape: {}'.format(sma.shape)) # T3 - Triple Exponential Moving Average (T3) t3 = talib.T3(close, timeperiod=5, vfactor=0) t3 = t3.fillna(t3.mean()) print('T3 - Triple Exponential Moving Average shape: {}'.format(t3.shape)) # TEMA - Triple Exponential Moving Average tema = talib.TEMA(close, timeperiod=3) tema = tema.fillna(tema.mean()) print('TEMA - Triple Exponential Moving Average shape: {}'.format( tema.shape)) # TRIMA - Triangular Moving Average trima = talib.TRIMA(close, timeperiod=3) trima = trima.fillna(trima.mean()) print('TRIMA - Triangular Moving Average shape: {}'.format(trima.shape)) # WMA - Weighted Moving Average wma = talib.WMA(close, timeperiod=3) wma = wma.fillna(wma.mean()) print('WMA - Weighted Moving Average shape: {}'.format(wma.shape)) ## Momentum Indicator Functions # ADX - Average Directional Movement Index adx = talib.ADX(high, low, close, timeperiod=14) adx = adx.fillna(adx.mean()) print('ADX - Average Directional Movement Index shape: {}'.format( adx.shape)) # ADXR - Average Directional Movement Index Rating adxr = talib.ADXR(high, low, close, timeperiod=7) adxr = adxr.fillna(adxr.mean()) print('ADXR - Average Directional Movement Index Rating shape: {}'.format( adxr.shape)) # APO - Absolute Price Oscillator apo = talib.APO(close, fastperiod=12, slowperiod=26, matype=0) apo = apo.fillna(apo.mean()) print('APO - Absolute Price Oscillator shape: {}'.format(apo.shape)) # AROONOSC - Aroon Oscillator aroon = talib.AROONOSC(high, low, timeperiod=14) aroon = aroon.fillna(aroon.mean()) print('AROONOSC - Aroon Oscillator shape: {}'.format(apo.shape)) # BOP - Balance Of Power bop = talib.BOP(open, high, low, close) bop = bop.fillna(bop.mean()) print('BOP - Balance Of Power shape: {}'.format(apo.shape)) # CCI - Commodity Channel Index cci = talib.CCI(high, low, close, timeperiod=7) cci = cci.fillna(cci.mean()) print('CCI - Commodity Channel Index shape: {}'.format(cci.shape)) # CMO - Chande Momentum Oscillator cmo = talib.CMO(close, timeperiod=7) cmo = cmo.fillna(cmo.mean()) print('CMO - Chande Momentum Oscillator shape: {}'.format(cmo.shape)) # DX - Directional Movement Index dx = talib.DX(high, low, close, timeperiod=7) dx = dx.fillna(dx.mean()) print('DX - Directional Movement Index shape: {}'.format(dx.shape)) # MFI - Money Flow Index mfi = talib.MFI(high, low, close, volume, timeperiod=7) mfi = mfi.fillna(mfi.mean()) print('MFI - Money Flow Index shape: {}'.format(mfi.shape)) # MINUS_DI - Minus Directional Indicator minusdi = talib.MINUS_DI(high, low, close, timeperiod=14) minusdi = minusdi.fillna(minusdi.mean()) print('MINUS_DI - Minus Directional Indicator shape: {}'.format( minusdi.shape)) # MINUS_DM - Minus Directional Movement minusdm = talib.MINUS_DM(high, low, timeperiod=14) minusdm = minusdm.fillna(minusdm.mean()) print('MINUS_DM - Minus Directional Movement shape: {}'.format( minusdm.shape)) # MOM - Momentum mom = talib.MOM(close, timeperiod=5) mom = mom.fillna(mom.mean()) print('MOM - Momentum shape: {}'.format(mom.shape)) # PLUS_DI - Plus Directional Indicator plusdi = talib.PLUS_DI(high, low, close, timeperiod=14) plusdi = plusdi.fillna(plusdi.mean()) print('PLUS_DI - Plus Directional Indicator shape: {}'.format( plusdi.shape)) # PLUS_DM - Plus Directional Movement plusdm = talib.PLUS_DM(high, low, timeperiod=14) plusdm = plusdm.fillna(plusdm.mean()) print('PLUS_DM - Plus Directional Movement shape: {}'.format(plusdi.shape)) # PPO - Percentage Price Oscillator ppo = talib.PPO(close, fastperiod=12, slowperiod=26, matype=0) ppo = ppo.fillna(ppo.mean()) print('PPO - Percentage Price Oscillator shape: {}'.format(ppo.shape)) # ROC - Rate of change:((price/prevPrice)-1)*100 roc = talib.ROC(close, timeperiod=10) roc = roc.fillna(roc.mean()) print('ROC - Rate of change : ((price/prevPrice)-1)*100 shape: {}'.format( roc.shape)) # RSI - Relative Strength Index rsi = talib.RSI(close, timeperiod=14) rsi = rsi.fillna(rsi.mean()) print('RSI - Relative Strength Index shape: {}'.format(rsi.shape)) # TRIX - 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA trix = talib.TRIX(close, timeperiod=30) trix = trix.fillna(trix.mean()) print('TRIX - 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA shape: {}'. format(trix.shape)) # ULTOSC - Ultimate Oscillator ultosc = talib.ULTOSC(high, low, close, timeperiod1=7, timeperiod2=14, timeperiod3=28) ultosc = ultosc.fillna(ultosc.mean()) print('ULTOSC - Ultimate Oscillator shape: {}'.format(ultosc.shape)) # WILLR - Williams'%R willr = talib.WILLR(high, low, close, timeperiod=7) willr = willr.fillna(willr.mean()) print("WILLR - Williams'%R shape: {}".format(willr.shape)) ## Volume Indicator Functions # AD - Chaikin A/D Line ad = talib.AD(high, low, close, volume) ad = ad.fillna(ad.mean()) print('AD - Chaikin A/D Line shape: {}'.format(ad.shape)) # ADOSC - Chaikin A/D Oscillator adosc = talib.ADOSC(high, low, close, volume, fastperiod=3, slowperiod=10) adosc = adosc.fillna(adosc.mean()) print('ADOSC - Chaikin A/D Oscillator shape: {}'.format(adosc.shape)) # OBV - On Balance Volume obv = talib.OBV(close, volume) obv = obv.fillna(obv.mean()) print('OBV - On Balance Volume shape: {}'.format(obv.shape)) ## Volatility Indicator Functions # ATR - Average True Range atr = talib.ATR(high, low, close, timeperiod=7) atr = atr.fillna(atr.mean()) print('ATR - Average True Range shape: {}'.format(atr.shape)) # NATR - Normalized Average True Range natr = talib.NATR(high, low, close, timeperiod=7) natr = natr.fillna(natr.mean()) print('NATR - Normalized Average True Range shape: {}'.format(natr.shape)) # TRANGE - True Range trange = talib.TRANGE(high, low, close) trange = trange.fillna(trange.mean()) print('TRANGE - True Range shape: {}'.format(natr.shape)) ## Price Transform Functions # AVGPRICE - Average Price avg = talib.AVGPRICE(open, high, low, close) avg = avg.fillna(avg.mean()) print('AVGPRICE - Average Price shape: {}'.format(natr.shape)) # MEDPRICE - Median Price medprice = talib.MEDPRICE(high, low) medprice = medprice.fillna(medprice.mean()) print('MEDPRICE - Median Price shape: {}'.format(medprice.shape)) # TYPPRICE - Typical Price typ = talib.TYPPRICE(high, low, close) typ = typ.fillna(typ.mean()) print('TYPPRICE - Typical Price shape: {}'.format(typ.shape)) # WCLPRICE - Weighted Close Price wcl = talib.WCLPRICE(high, low, close) wcl = wcl.fillna(wcl.mean()) print('WCLPRICE - Weighted Close Price shape: {}'.format(wcl.shape)) ## Cycle Indicator Functions # HT_DCPERIOD - Hilbert Transform - Dominant Cycle Period dcperiod = talib.HT_DCPERIOD(close) dcperiod = dcperiod.fillna(dcperiod.mean()) print('HT_DCPERIOD - Hilbert Transform - Dominant Cycle Period shape: {}'. format(dcperiod.shape)) # HT_DCPHASE - Hilbert Transform - Dominant Cycle Phase dcphase = talib.HT_DCPHASE(close) dcphase = dcphase.fillna(dcphase.mean()) print('HT_DCPHASE - Hilbert Transform - Dominant Cycle Phase shape: {}'. format(dcperiod.shape)) ## Statistic Functions # BETA - Beta beta = talib.BETA(high, low, timeperiod=3) beta = beta.fillna(beta.mean()) print('BETA - Beta shape: {}'.format(beta.shape)) # CORREL - Pearson's Correlation Coefficient(r) correl = talib.CORREL(high, low, timeperiod=30) correl = correl.fillna(correl.mean()) print("CORREL - Pearson's Correlation Coefficient(r) shape: {}".format( beta.shape)) # LINEARREG - Linear Regression linreg = talib.LINEARREG(close, timeperiod=7) linreg = linreg.fillna(linreg.mean()) print("LINEARREG - Linear Regression shape: {}".format(linreg.shape)) # STDDEV - Standard Deviation stddev = talib.STDDEV(close, timeperiod=5, nbdev=1) stddev = stddev.fillna(stddev.mean()) print("STDDEV - Standard Deviation shape: {}".format(stddev.shape)) # TSF - Time Series Forecast tsf = talib.TSF(close, timeperiod=7) tsf = tsf.fillna(tsf.mean()) print("TSF - Time Series Forecast shape: {}".format(tsf.shape)) # VAR - Variance var = talib.VAR(close, timeperiod=5, nbdev=1) var = var.fillna(var.mean()) print("VAR - Variance shape: {}".format(var.shape)) ## Feature DataFrame X_full = pd.concat([ X, dema, ema, hilbert, kama, ma, midpoint, midprice, sar, sarext, sma, t3, tema, trima, wma, adx, adxr, apo, aroon, bop, cci, cmo, mfi, minusdi, minusdm, mom, plusdi, plusdm, ppo, roc, rsi, trix, ultosc, willr, ad, adosc, obv, atr, natr, trange, avg, medprice, typ, wcl, dcperiod, dcphase, beta, correl, linreg, stddev, tsf, var ], axis=1).drop(['open', 'high', 'low', 'close'], axis=1) X_full.columns = [ 'volume', 'diff', 'dema', 'ema', 'hilbert', 'kama', 'ma', 'midpoint', 'midprice', 'sar', 'sarext', 'sma', 't3', 'tema', 'trima', 'wma', 'adx', 'adxr', 'apo', 'aroon', 'bop', 'cci', 'cmo', 'mfi', 'minusdi', 'minusdm', 'mom', 'plusdi', 'plusdm', 'ppo', 'roc', 'rsi', 'trix', 'ultosc', 'willr', 'ad', 'adosc', 'obv', 'atr', 'natr', 'trange', 'avg', 'medprice', 'typ', 'wcl', 'dcperiod', 'dcphase', 'beta', 'correl', 'linreg', 'stddev', 'tsf', 'var' ] X_full.join(y_).head(10) # full feature models X_train_full, X_test_full, y_train_full, y_test_full = train_test_split( X_full, y_, test_size=0.33, random_state=42) print('X_train shape: {}'.format(X_train_full.shape)) print('X_test shape: {}'.format(X_test_full.shape)) print('y_train shape: {}'.format(y_train_full.shape)) print('y_test shape: {}'.format(y_test_full.shape)) pipe_knn_full = Pipeline([('scl', StandardScaler()), ('est', KNeighborsClassifier(n_neighbors=3))]) pipe_logistic_full = Pipeline([ ('scl', StandardScaler()), ('est', LogisticRegression(solver='lbfgs', multi_class='multinomial', random_state=39)) ]) pipe_rf_full = Pipeline([('scl', StandardScaler()), ('est', RandomForestClassifier(random_state=39))]) pipe_gb_full = Pipeline([('scl', StandardScaler()), ('est', GradientBoostingClassifier(random_state=39))]) pipe_names = ['KNN', 'Logistic', 'RandomForest', 'GradientBoosting'] pipe_lines_full = [ pipe_knn_full, pipe_logistic_full, pipe_rf_full, pipe_gb_full ] for (i, pipe) in enumerate(pipe_lines_full): pipe.fit(X_train_full, y_train_full.values.ravel()) print(pipe) print('%s: %.3f' % (pipe_names[i] + ' Train Accuracy', accuracy_score(y_train_full.values.ravel(), pipe.predict(X_train_full)))) print('%s: %.3f' % (pipe_names[i] + ' Test Accuracy', accuracy_score(y_test_full.values.ravel(), pipe.predict(X_test_full)))) print('%s: %.3f' % (pipe_names[i] + ' Train F1 Score', f1_score(y_train_full.values.ravel(), pipe.predict(X_train_full), average='micro'))) print('%s: %.3f' % (pipe_names[i] + ' Test F1 Score', f1_score(y_test_full.values.ravel(), pipe.predict(X_test_full), average='micro'))) # Univariate Statistics select = SelectPercentile(percentile=25) select.fit(X_train_full, y_train_full.values.ravel()) X_train_selected = select.transform(X_train_full) X_test_selected = select.transform(X_test_full) # GradientBoost Classifier print( '--------------------------Without Univariate Statistics-------------------------------------' ) pipe_gb = Pipeline([('scl', StandardScaler()), ('est', GradientBoostingClassifier(random_state=39))]) pipe_gb.fit(X_train_full, y_train_full.values.ravel()) print('Train Accuracy: {:.3f}'.format( accuracy_score(y_train_full.values.ravel(), pipe_gb.predict(X_train_full)))) print('Test Accuracy: {:.3f}'.format( accuracy_score(y_test_full.values.ravel(), pipe_gb.predict(X_test_full)))) print('Train F1 Score: {:.3f}'.format( f1_score(y_train_full.values.ravel(), pipe_gb.predict(X_train_full), average='micro'))) print('Test F1 Score: {:.3f}'.format( f1_score(y_test_full.values.ravel(), pipe_gb.predict(X_test_full), average='micro'))) # GradientBoost Cllassifier with Univariate Statistics print( '---------------------------With Univariate Statistics--------------------------------------' ) pipe_gb_percentile = Pipeline([ ('scl', StandardScaler()), ('est', GradientBoostingClassifier(random_state=39)) ]) pipe_gb_percentile.fit(X_train_selected, y_train_full.values.ravel()) print('Train Accuracy: {:.3f}'.format( accuracy_score(y_train_full.values.ravel(), pipe_gb_percentile.predict(X_train_selected)))) print('Test Accuracy: {:.3f}'.format( accuracy_score(y_test_full.values.ravel(), pipe_gb_percentile.predict(X_test_selected)))) print('Train F1 Score: {:.3f}'.format( f1_score(y_train_full.values.ravel(), pipe_gb_percentile.predict(X_train_selected), average='micro'))) print('Test F1 Score: {:.3f}'.format( f1_score(y_test_full.values.ravel(), pipe_gb_percentile.predict(X_test_selected), average='micro'))) # Model-based Selection select = SelectFromModel(RandomForestClassifier(n_estimators=100, random_state=42), threshold="1.25*mean") select.fit(X_train_full, y_train_full.values.ravel()) X_train_model = select.transform(X_train_full) X_test_model = select.transform(X_test_full) # GradientBoost Classifier print( '--------------------------Without Model-based Selection--------------------------------------' ) pipe_gb = Pipeline([('scl', StandardScaler()), ('est', GradientBoostingClassifier(random_state=39))]) pipe_gb.fit(X_train_full, y_train_full.values.ravel()) print('Train Accuracy: {:.3f}'.format( accuracy_score(y_train_full.values.ravel(), pipe_gb.predict(X_train_full)))) print('Test Accuracy: {:.3f}'.format( accuracy_score(y_test_full.values.ravel(), pipe_gb.predict(X_test_full)))) print('Train F1 Score: {:.3f}'.format( f1_score(y_train_full.values.ravel(), pipe_gb.predict(X_train_full), average='micro'))) print('Test F1 Score: {:.3f}'.format( f1_score(y_test_full.values.ravel(), pipe_gb.predict(X_test_full), average='micro'))) # GradientBoost Classifier with Model-based Selection print( '----------------------------With Model-based Selection--------------------------------------' ) pipe_gb_model = Pipeline([('scl', StandardScaler()), ('est', GradientBoostingClassifier(random_state=39))]) pipe_gb_model.fit(X_train_model, y_train_full.values.ravel()) print('Train Accuracy: {:.3f}'.format( accuracy_score(y_train_full.values.ravel(), pipe_gb_model.predict(X_train_model)))) print('Test Accuracy: {:.3f}'.format( accuracy_score(y_test_full.values.ravel(), pipe_gb_model.predict(X_test_model)))) print('Train F1 Score: {:.3f}'.format( f1_score(y_train_full.values.ravel(), pipe_gb_model.predict(X_train_model), average='micro'))) print('Test F1 Score: {:.3f}'.format( f1_score(y_test_full.values.ravel(), pipe_gb_model.predict(X_test_model), average='micro'))) # Recursive Feature Elimination select = RFE(RandomForestClassifier(n_estimators=100, random_state=42), n_features_to_select=15) select.fit(X_train_full, y_train_full.values.ravel()) X_train_rfe = select.transform(X_train_full) X_test_rfe = select.transform(X_test_full) # GradientBoost Classifier print( '--------------------------Without Recursive Feature Elimination-------------------------------------' ) pipe_gb = Pipeline([('scl', StandardScaler()), ('est', GradientBoostingClassifier(random_state=39))]) pipe_gb.fit(X_train_full, y_train_full.values.ravel()) print('Train Accuracy: {:.3f}'.format( accuracy_score(y_train_full.values.ravel(), pipe_gb.predict(X_train_full)))) print('Test Accuracy: {:.3f}'.format( accuracy_score(y_test_full.values.ravel(), pipe_gb.predict(X_test_full)))) print('Train F1 Score: {:.3f}'.format( f1_score(y_train_full.values.ravel(), pipe_gb.predict(X_train_full), average='micro'))) print('Test F1 Score: {:.3f}'.format( f1_score(y_test_full.values.ravel(), pipe_gb.predict(X_test_full), average='micro'))) # GradientBoost Classifier with Recursive Feature Elimination print( '----------------------------With Recursive Feature Elimination--------------------------------------' ) pipe_gb_rfe = Pipeline([('scl', StandardScaler()), ('est', GradientBoostingClassifier(random_state=39))]) pipe_gb_rfe.fit(X_train_rfe, y_train_full.values.ravel()) print('Train Accuracy: {:.3f}'.format( accuracy_score(y_train_full.values.ravel(), pipe_gb_rfe.predict(X_train_rfe)))) print('Test Accuracy: {:.3f}'.format( accuracy_score(y_test_full.values.ravel(), pipe_gb_rfe.predict(X_test_rfe)))) print('Train F1 Score: {:.3f}'.format( f1_score(y_train_full.values.ravel(), pipe_gb_rfe.predict(X_train_rfe), average='micro'))) print('Test F1 Score: {:.3f}'.format( f1_score(y_test_full.values.ravel(), pipe_gb_rfe.predict(X_test_rfe), average='micro'))) cv = cross_val_score(pipe_gb, X_, y_.values.ravel(), cv=StratifiedKFold(n_splits=10, shuffle=True, random_state=39)) print('Cross validation with StratifiedKFold scores: {}'.format(cv)) print('Cross Validation with StatifiedKFold mean: {}'.format(cv.mean())) # GridSearch n_features = len(df.columns) param_grid = { 'learning_rate': [0.01, 0.1, 1, 10], 'n_estimators': [1, 10, 100, 200, 300], 'max_depth': [1, 2, 3, 4, 5] } stratifiedcv = StratifiedKFold(n_splits=10, shuffle=True, random_state=39) X_train, X_test, y_train, y_test = train_test_split(X_, y_, test_size=0.33, random_state=42) grid_search = GridSearchCV(GradientBoostingClassifier(), param_grid, cv=stratifiedcv) grid_search.fit(X_train, y_train.values.ravel()) print('GridSearch Train Accuracy: {:.3f}'.format( accuracy_score(y_train.values.ravel(), grid_search.predict(X_train)))) print('GridSearch Test Accuracy: {:.3f}'.format( accuracy_score(y_test.values.ravel(), grid_search.predict(X_test)))) print('GridSearch Train F1 Score: {:.3f}'.format( f1_score(y_train.values.ravel(), grid_search.predict(X_train), average='micro'))) print('GridSearch Test F1 Score: {:.3f}'.format( f1_score(y_test.values.ravel(), grid_search.predict(X_test), average='micro'))) # GridSearch results print("Best params:\n{}".format(grid_search.best_params_)) print("Best cross-validation score: {:.2f}".format( grid_search.best_score_)) results = pd.DataFrame(grid_search.cv_results_) corr_params = results.drop(results.columns[[ 0, 1, 2, 3, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 19, 20 ]], axis=1) corr_params.head() # GridSearch in nested cv_gb = cross_val_score(grid_search, X_, y_.values.ravel(), cv=StratifiedKFold(n_splits=3, shuffle=True, random_state=39)) print('Grid Search with nested cross validation scores: {}'.format(cv_gb)) print('Grid Search with nested cross validation mean: {}'.format( cv_gb.mean()))
def handle_overlap_studies(args, kax, klines_df, close_times, display_count): all_name = "" if args.ABANDS: # ATR BANDS name = 'ABANDS' real = talib.ATR(klines_df["high"], klines_df["low"], klines_df["close"], timeperiod=14) emas = talib.EMA(klines_df["close"], timeperiod=26) kax.plot(close_times, emas[-display_count:], "b--", label=name) #cs = ['y', 'c', 'm', 'k'] for idx, n in enumerate(args.ABANDS): """ if idx >= len(cs): break c = cs[idx] """ c = 'y' cl = c + '--' n = int(n) kax.plot(close_times, (emas + n * real)[-display_count:], cl, label=name + ' upperband') kax.plot(close_times, (emas - n * real)[-display_count:], cl, label=name + ' lowerband') if args.BANDS: # BANDS name = 'BANDS' emas = talib.EMA(klines_df["close"], timeperiod=26) kax.plot(close_times, emas[-display_count:], "b--", label=name) r = args.BANDS kax.plot(close_times, (1 + r) * emas[-display_count:], 'y--', label=name + ' upperband') kax.plot(close_times, (1 - r) * emas[-display_count:], 'y--', label=name + ' lowerband') # talib os_key = 'BBANDS' if args.BBANDS: upperband, middleband, lowerband = talib.BBANDS(klines_df["close"], timeperiod=5, nbdevup=2, nbdevdn=2, matype=0) kax.plot(close_times, upperband[-display_count:], "y", label=os_key + ' upperband') kax.plot(close_times, middleband[-display_count:], "b", label=os_key + ' middleband') kax.plot(close_times, lowerband[-display_count:], "y", label=os_key + ' lowerband') os_key = 'DEMA' if args.DEMA: real = talib.DEMA(klines_df["close"], timeperiod=args.DEMA) kax.plot(close_times, real[-display_count:], "y", label=os_key) if args.EMA: name = 'EMA' all_name += " %s%s" % (name, args.EMA) for idx, e_p in enumerate(args.EMA): if idx >= len(plot_colors): break e_p = int(e_p) emas = talib.EMA(klines_df["close"], timeperiod=e_p) kax.plot(close_times, emas[-display_count:], plot_colors[idx] + '--', label="%sEMA" % (e_p)) os_key = 'HT_TRENDLINE' if args.HT_TRENDLINE: real = talib.HT_TRENDLINE(klines_df["close"]) kax.plot(close_times, real[-display_count:], "y", label=os_key) os_key = 'KAMA' if args.KAMA: real = talib.KAMA(klines_df["close"], timeperiod=args.KAMA) kax.plot(close_times, real[-display_count:], "y", label=os_key) if args.MA: name = 'MA' all_name += " %s%s" % (name, args.MA) for idx, e_p in enumerate(args.MA): if idx >= len(plot_colors): break e_p = int(e_p) emas = talib.MA(klines_df["close"], timeperiod=e_p) kax.plot(close_times, emas[-display_count:], plot_colors[idx], label="%sMA" % (e_p)) os_key = 'MAMA' if args.MAMA: mama, fama = talib.MAMA(klines_df["close"], fastlimit=0, slowlimit=0) kax.plot(close_times, mama[-display_count:], "b", label=os_key) kax.plot(close_times, fama[-display_count:], "c", label=os_key) os_key = 'MIDPOINT' if args.MIDPOINT: real = talib.MIDPOINT(klines_df["close"], timeperiod=args.MIDPOINT) kax.plot(close_times, real[-display_count:], "y", label=os_key) os_key = 'MIDPRICE' if args.MIDPRICE: real = talib.MIDPRICE(klines_df["high"], klines_df["low"], timeperiod=args.MIDPRICE) kax.plot(close_times, real[-display_count:], "y", label=os_key) os_key = 'SAR' if args.SAR: real = talib.SAR(klines_df["high"], klines_df["low"], acceleration=0, maximum=0) kax.plot(close_times, real[-display_count:], "y", label=os_key) os_key = 'SAREXT' if args.SAREXT: real = talib.SAREXT(klines_df["high"], klines_df["low"], startvalue=0, offsetonreverse=0, accelerationinitlong=0, accelerationlong=0, accelerationmaxlong=0, accelerationinitshort=0, accelerationshort=0, accelerationmaxshort=0) kax.plot(close_times, real[-display_count:], "y", label=os_key) os_key = 'SMA' if args.SMA: real = talib.SMA(klines_df["close"], timeperiod=args.SMA) kax.plot(close_times, real[-display_count:], "y", label=os_key) os_key = 'T3' if args.T3: real = talib.T3(klines_df["close"], timeperiod=args.T3, vfactor=0) kax.plot(close_times, real[-display_count:], "y", label=os_key) os_key = 'TEMA' if args.TEMA: real = talib.TEMA(klines_df["close"], timeperiod=args.TEMA) kax.plot(close_times, real[-display_count:], "y", label=os_key) os_key = 'TRIMA' if args.TRIMA: real = talib.TRIMA(klines_df["close"], timeperiod=args.TRIMA) kax.plot(close_times, real[-display_count:], "y", label=os_key) os_key = 'WMA' if args.WMA: real = talib.WMA(klines_df["close"], timeperiod=args.WMA) kax.plot(close_times, real[-display_count:], "y", label=os_key) return all_name
def TALIB_TEMA(close, timeperiod=30): '''00387,2,1''' return talib.TEMA(close, timeperiod)
def talib_TEMA(DataFrame, N=30): res = talib.TEMA(DataFrame.close.values, timeperiod=N) return pd.DataFrame({'TEMA': res}, index=DataFrame.index)
def add_TEMA(self, df, periods=[5, 10, 20, 30, 60, 120]): for i in periods: period = str(i) df['TEMA_' + period] = ta.TEMA(df['close'], timeperiod=i) return df
def tema(dataframe, period, field='close'): import talib.abstract as ta return ta.TEMA(dataframe, timeperiod=period, price=field)
axis=1) BOP = ta.BOP(SS.sopen, SS.high, SS.low, SS.sclose) CCI = ta.CCI(SS.high, SS.low, SS.sclose) CMO = ta.CMO(SS.sclose) DEMA = ta.DEMA(SS.sclose) DX = ta.DX(SS.high, SS.low, SS.sclose) EMA = ta.EMA(SS.sclose) KAMA = ta.KAMA(SS.sclose) MFI = ta.MFI(SS.high, SS.low, SS.sclose, SS.volumn) MOM = ta.MOM(SS.sclose) RSI = ta.RSI(SS.sclose) group2 = pd.concat([BOP, CCI, CMO, DEMA, DX, EMA, KAMA, MFI, MOM, RSI], axis=1) SAR = ta.SAR(SS.high, SS.low) TEMA = ta.TEMA(SS.sclose) TRANGE = ta.TRANGE(SS.high, SS.low, SS.sclose) TRIMA = ta.TRIMA(SS.sclose) TRIX = ta.TRIX(SS.sclose) group3 = pd.concat([SAR, TEMA, TRANGE, TRIMA, TRIX], axis=1) raw_ta = pd.concat([group1, group2, group3], axis=1) ta_index = pd.concat([raw_ta, target], axis=1) ta_index = ta_index.dropna() #38输入 1输出 4类型 train = ta_index[:'2010-01-01'] x = train.values[:, -1]
maximum=0) df['SAREXT'] = ta.SAREXT(np.array(df['High'].shift(1)), np.array(df['Low'].shift(1)), startvalue=0, offsetonreverse=0, accelerationinitlong=0, accelerationlong=0, accelerationmaxlong=0, accelerationinitshort=0, accelerationshort=0, accelerationmaxshort=0) df['SMA'] = ta.SMA(np.array(df['Adj Close'].shift(1)), timeperiod=n) df['T3'] = ta.T3(np.array(df['Adj Close'].shift(1)), timeperiod=n, vfactor=0) df['TEMA'] = ta.TEMA(np.array(df['Adj Close'].shift(1)), timeperiod=n) df['TRIMA'] = ta.TRIMA(np.array(df['Adj Close'].shift(1)), timeperiod=n) df['WMA'] = ta.WMA(np.array(df['Adj Close'].shift(1)), timeperiod=n) df['20d_ma'] = df['Adj Close'].shift(1).rolling(window=20).mean() df['50d_ma'] = df['Adj Close'].shift(1).rolling(window=50).mean() df['Bol_upper'] = df['Adj Close'].shift(1).rolling( window=20).mean() + 2 * df['Adj Close'].shift(1).rolling(window=20).std() df['Bol_lower'] = df['Adj Close'].shift(1).rolling( window=20).mean() - 2 * df['Adj Close'].shift(1).rolling(window=20).std() df['Bol_BW'] = ((df['Bol_upper'] - df['Bol_lower']) / df['20d_ma']) * 100 df['Bol_BW_200MA'] = df['Bol_BW'].shift(1).rolling(window=50).mean() df['Bol_BW_200MA'] = df['Bol_BW_200MA'].fillna(method='backfill') # df['20d_ewma'] = df['Adj Close'].shift(1).ewm(span=20).mean() # df['50d_ewma'] = df['Adj Close'].shift(1).ewm(span=50).mean()