def t3(client, symbol, timeframe="6m", col="close", periods=None, vfactor=0): """This will return a dataframe of tripple 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 vfactor (int); vfactor 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["t3-{}".format(per)] = t.T3(df[col].values.astype(float), per, vfactor=vfactor) return pd.DataFrame(build)
def add_T3(self, df, periods=[5, 10, 20, 30, 60, 120], vfactor=0): for i in periods: period = str(i) df['T3_' + period] = ta.T3(df['close'], timeperiod=i, vfactor=vfactor) return df
def calculations(self): '''calculations''' self.df['rsi'] = ta.RSI(self.df['close'], timeperiod=5) self.df['apo'] = ta.APO(self.df['close'], fastperiod=10, slowperiod=5, matype=0) self.df['upperband'], self.df['middleband'], self.df[ 'lowerband'] = ta.BBANDS(self.df['close'], timeperiod=5, nbdevup=2, nbdevdn=2, matype=0) self.df['ema'] = ta.EMA(self.df['close'], timeperiod=5) self.df['ma'] = ta.MA(self.df['close'], timeperiod=5, matype=0) self.df['sma'] = ta.MA(self.df['close'], timeperiod=5) self.df['t3'] = ta.T3(self.df['close'], timeperiod=5, vfactor=0) self.df['wma'] = ta.WMA(self.df['close'], timeperiod=5) self.df['aroonosc'] = ta.AROONOSC(self.df['high'], self.df['low'], timeperiod=5) self.df['cci'] = ta.CCI(self.df['high'], self.df['low'], self.df['close'], timeperiod=5) self.df['cmo'] = ta.CMO(self.df['close'], timeperiod=14) self.df['macd'], self.df['macdsignal'], self.df[ 'macdhist'] = ta.MACDEXT(self.df['close'], fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0) self.df['slowk'], self.df['slowd'] = ta.STOCH(self.df['high'], self.df['low'], self.df['close'], fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) self.df['fastk'], self.df['fastd'] = ta.STOCHRSI(self.df['close'], timeperiod=5, fastk_period=5, fastd_period=3, fastd_matype=0) self.df['ultosc'] = ta.ULTOSC(self.df['high'], self.df['low'], self.df['close'], timeperiod1=7, timeperiod2=14, timeperiod3=28) self.df['adosc'] = ta.ADOSC(self.df['high'], self.df['low'], self.df['close'], self.df['volume'], fastperiod=3, slowperiod=10) return self.df
def test_t3(self): """ Test T3 Moving Average. """ periods = 200 t3 = qufilab.t3(self.close, periods) t3_talib = talib.T3(self.close, periods) np.testing.assert_allclose(t3, t3_talib, rtol=self.tolerance)
def overlap_process(event): print(event.widget.get()) overlap = 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(overlap, fontproperties="SimHei") if overlap == '布林线': pass elif overlap == '双指数移动平均线': real = ta.DEMA(close, timeperiod=30) axes[1].plot(real, 'r-') elif overlap == '指数移动平均线 ': real = ta.EMA(close, timeperiod=30) axes[1].plot(real, 'r-') elif overlap == '希尔伯特变换——瞬时趋势线': real = ta.HT_TRENDLINE(close) axes[1].plot(real, 'r-') elif overlap == '考夫曼自适应移动平均线': real = ta.KAMA(close, timeperiod=30) axes[1].plot(real, 'r-') elif overlap == '移动平均线': real = ta.MA(close, timeperiod=30, matype=0) axes[1].plot(real, 'r-') elif overlap == 'MESA自适应移动平均': mama, fama = ta.MAMA(close, fastlimit=0, slowlimit=0) axes[1].plot(mama, 'r-') axes[1].plot(fama, 'g-') elif overlap == '变周期移动平均线': real = ta.MAVP(close, periods, minperiod=2, maxperiod=30, matype=0) axes[1].plot(real, 'r-') elif overlap == '简单移动平均线': real = ta.SMA(close, timeperiod=30) axes[1].plot(real, 'r-') elif overlap == '三指数移动平均线(T3)': real = ta.T3(close, timeperiod=5, vfactor=0) axes[1].plot(real, 'r-') elif overlap == '三指数移动平均线': real = ta.TEMA(close, timeperiod=30) axes[1].plot(real, 'r-') elif overlap == '三角形加权法 ': real = ta.TRIMA(close, timeperiod=30) axes[1].plot(real, 'r-') elif overlap == '加权移动平均数': real = ta.WMA(close, timeperiod=30) axes[1].plot(real, 'r-') plt.show()
def queryStock(self, stackCode): # 连接数据库 resultTemp=[] connection=Connection() connect = pymysql.Connect( host=connection.host, port=connection.port, user=connection.user, passwd=connection.passwd, db=connection.db, charset=connection.charset ) # 获取游标 cursor = connect.cursor() # 查询数据 sql = "select * from (SELECT DISTINCT * FROM `"+stackCode+"` where tradestatus=1 and turn is not null order by date desc limit %i) as b order by date asc" data = (self.window+80) cursor.execute(sql % data) fs = cursor.description filelds = [] for field in fs: filelds.append(field[0]) rs = cursor.fetchall() result = pd.DataFrame(list(rs), columns=filelds) # 关闭连接 cursor.close() connect.close() #二维数组 result=result.loc[:,['date','open','high','low','close','volume','turn','tradestatus'] ] #计算三十日均线 result['M30']=talib.SMA(result['close'],30) result['T30']=talib.T3(result['close'],timeperiod=30, vfactor=0) result['tprice']=talib.TYPPRICE(result['high'],result['low'],result['close']) # slowk, slowd = talib.STOCH(result['high'],result['low'],result['close'], fastk_period=9, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) # slowj= list(map(lambda x,y: 3*x-2*y, slowk, slowd)) # result['k']=slowk # result['d']=slowd # result['j']=slowj zsindex=ZSIndex() # 主力线,散户线 zz, ss = zsindex.zsLine(result) mm = zsindex.convertXQH(result) result['z'] = zz result['s'] = ss result['m'] = mm #神仙趋势线 result['h1']=talib.EMA(result['close'],6) result['h2']=talib.EMA(result['h1'],18) result['h3']=talib.EMA(result['close'],108) maxPrice=talib.MAX(result['close'],data)[len(result)-1] print(maxPrice) result.date = range(0, len(result)) # 日期改变成序号 resultTemp.append(result) resultTemp.append(maxPrice) return resultTemp
def T3(close, timeperiod=5, vfactor=0): ''' Triple Exponential Moving Average (T3) 三重指数移动平均线 分组: Overlap Studies 重叠研究 简介: TRIX长线操作时采用本指标的讯号,长时间按照本指标讯号交易, 获利百分比大于损失百分比,利润相当可观。 比如日线MA5指5天内的收盘价除以5 。 分析和应用: http://www.iwencai.com/yike/detail/auid/6c22c15ccbf24e64?rid=80 real = T3(close, timeperiod=5, vfactor=0) ''' return talib.T3(close, timeperiod, vfactor)
def add_T3(self, timeperiod=20, vfactor=0.7, type="line", color="secondary", **kwargs): """T3 Exponential Moving Average.""" if not self.has_close: raise Exception() utils.kwargs_check(kwargs, VALID_TA_KWARGS) if "kind" in kwargs: type = kwargs["kind"] name = "T3({}, {})".format(str(timeperiod), str(vfactor)) self.pri[name] = dict(type=type, color=color) self.ind[name] = talib.T3(self.df[self.cl].values, timeperiod, vfactor)
def t3(close, graph=False, **kwargs): ''' T3 - Triple Exponential Moving Average (T3) ''' result = talib.T3(close, **kwargs) df = pd.concat([pd.DataFrame(close), pd.DataFrame(result)], axis=1) df.columns = ['close', 't3'] if graph: title = 'T3 - Triple Exponential Moving Average (T3)' style = ['r-'] + ['--'] * (len(df.columns) - 1) fname = '14_t3.png' make_graph(title, df, style=style, fname=fname) return df
def test_t3(self): result = self.overlap.t3(self.close) self.assertIsInstance(result, Series) self.assertEqual(result.name, 'T3_10_0.7') try: expected = tal.T3(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 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 test_T3(self): class MyT3(OperatorT3): def __init__(self, name, **kwargs): super(MyT3, self).__init__(100, name, **kwargs) self.env.add_operator('t3', { 'operator': MyT3, }) string = 't3(5, 0.7, 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.T3(o[:100, i], 5, 0.7)[-1] == val) self.assertTrue(all(res))
def t3(candles: np.ndarray, period=5, vfactor=0, sequential=False) -> Union[float, np.ndarray]: """ T3 - Triple Exponential Moving Average (T3) :param candles: np.ndarray :param period: int - default: 5 :param vfactor: float - default: 0 :param sequential: bool - default=False :return: float | np.ndarray """ if not sequential and len(candles) > 240: candles = candles[-240:] res = talib.T3(candles[:, 2], timeperiod=period, vfactor=vfactor) return res if sequential else res[-1]
def handle_data(self, kl): self.kl = kl #.copy() self.data['t'] = kl['t'] if self.indicator == 'ma': #MA_Type: 0=SMA, 1=EMA, 2=WMA, 3=DEMA, 4=TEMA, 5=TRIMA, 6=KAMA, 7=MAMA, 8=T3 (Default=SMA) self.data[col_name] = ta.MA(kl['c'], **self.params) elif self.indicator == 'wma': self.data[col_name] = ta.WMA(kl['c'], **self.params) elif self.indicator == 'sma': self.data[col_name] = ta.SMA(kl['c'], **self.params) elif self.indicator == 'ema': self.data[col_name] = ta.EMA(kl['c'], **self.params) elif self.indicator == 'dema': self.data[col_name] = ta.DEMA(kl['c'], **self.params) elif self.indicator == 'trima': self.data[col_name] = ta.TRIMA(kl['c'], **self.params) elif self.indicator == 'kama': self.data[col_name] = ta.KAMA(kl['c'], **self.params) elif self.indicator == 't3': self.data[col_name] = ta.T3(kl['c'], **self.params) ##, vfactor = 0)
def t3(candles: np.ndarray, period: int = 5, vfactor: float = 0, source_type: str = "close", sequential: bool = False) -> Union[float, np.ndarray]: """ T3 - Triple Exponential Moving Average (T3) :param candles: np.ndarray :param period: int - default: 5 :param vfactor: float - default: 0 :param source_type: str - default: "close" :param sequential: bool - default=False :return: float | np.ndarray """ candles = slice_candles(candles, sequential) source = get_candle_source(candles, source_type=source_type) res = talib.T3(source, timeperiod=period, vfactor=vfactor) return res if sequential else res[-1]
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 t3(candles: np.ndarray, period: int = 5, vfactor: float = 0, source_type: str = "close", sequential: bool = False) -> Union[float, np.ndarray]: """ T3 - Triple Exponential Moving Average (T3) :param candles: np.ndarray :param period: int - default: 5 :param vfactor: float - default: 0 :param source_type: str - default: "close" :param sequential: bool - default=False :return: float | np.ndarray """ warmup_candles_num = get_config('env.data.warmup_candles_num', 240) if not sequential and len(candles) > warmup_candles_num: candles = candles[-warmup_candles_num:] source = get_candle_source(candles, source_type=source_type) res = talib.T3(source, timeperiod=period, vfactor=vfactor) return res if sequential else res[-1]
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 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 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_T3(close, timeperiod=5, vfactor=0.7): '''00386,3,1''' return talib.T3(close, timeperiod, vfactor)
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
acceleration=0, 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()
def talib_T3(DataFrame, N=5, vfactor=0): res = talib.T3(DataFrame.close.values, timeperiod=N, vfactor=vfactor) return pd.DataFrame({'T3': res}, index=DataFrame.index)
def T3(raw_df, timeperiod=5, vfactor=0): # extract necessary data from raw dataframe (close) return ta.T3(raw_df.Close.values, timeperiod, vfactor)
df[col + '_fastd'] = slowd df[col + '_WILLR'] = tl.WILLR(high, low, close) aroondown, aroonup = tl.AROON(high, low) df[col + '_aroondown'] = aroondown df[col + '_aroonup'] = aroonup #miss true strength index df[col + '_SMA'] = tl.SMA(close) df[col + '_EMA'] = tl.EMA(close) macd, macdsignal, macdhist = tl.MACD(close) df[col + '_macd'] = macd df[col + '_macdsignal'] = macdsignal df[col + '_macdhist'] = macdhist df[col + '_ADX'] = tl.ADX(high, low, close) #MACD,ADX are Momentum indicators df[col + '_T3'] = tl.T3(close) df[col + '_OBV'] = tl.OBV(close, volume) df[col + '_MFI'] = tl.MFI(high, low, close, volume) #MFI are Momentum indicators df[col + '_ADOSC'] = tl.ADOSC(high, low, close, volume) upperband, middleband, lowerband = tl.BBANDS(close) df[col + '_upperband'] = upperband df[col + '_middleband'] = middleband df[col + '_lowerband'] = lowerband df[col + '_ATR'] = tl.ATR(high, low, close) window = 3 ret = df[col + '_returns'] df['Y1'] = (ret < 0).replace(True, 1)
closeprice = criptomoeda_close.iloc[-1] cci = talib.CCI(criptomoeda_maxima, criptomoeda_minima, criptomoeda_close, timeperiod=14) atr = talib.ATR(criptomoeda_maxima, criptomoeda_minima, criptomoeda_close, timeperiod=14) midpoint = talib.MIDPOINT(criptomoeda_close, timeperiod=30) sma6 = talib.SMA(criptomoeda_close, timeperiod=6) sma9 = talib.SMA(criptomoeda_close, timeperiod=9) real = talib.T3(criptomoeda_close, timeperiod=14) print('Close Price: $%.2f' % (closeprice)) # Média movel de 14 dias do Fechamento criptomoeda_fechamento_mediamovel = criptomoeda['c'].rolling(30).mean() # Média movel de 30 dias do Fechamento criptomoeda_fechamento_mediamovel100 = criptomoeda['c'].rolling(100).mean() #======== Importar biblioteca SKLEARN import numpy as np from sklearn import linear_model from sklearn.metrics import mean_squared_error, r2_score from matplotlib import rcParams #========= criptomoeda_regressao = criptomoeda_abertura #========= Treinar X criptomoeda_X_train = criptomoeda_abertura criptomoeda_X_test = criptomoeda_abertura
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 showK(self, code, result, isShow, savePath): savePath = savePath.strip() + "\\temp" self.savePath = savePath.rstrip("\\") self.isShow = isShow self.code = code t3Price = talib.T3(result['close'], timeperiod=30, vfactor=0) self.date_tickers = result.date.values result.date = range(0, len(result)) # 日期改变成序号 self.matix = result.values # 转换成绘制蜡烛图需要的数据格式(date, open, close, high, low, volume) xdates = self.matix[:, 0] # X轴数据(这里用的天数索引) if isShow: # 设置外观效果 plt.rc('font', family='Microsoft YaHei') # 用中文字体,防止中文显示不出来 plt.rc('figure', fc='k') # 绘图对象背景图 plt.rc('text', c='#800000') # 文本颜色 plt.rc( 'axes', axisbelow=True, xmargin=0, fc='k', ec='#800000', lw=1.5, labelcolor='#800000', unicode_minus=False) # 坐标轴属性(置底,左边无空隙,背景色,边框色,线宽,文本颜色,中文负号修正) plt.rc('xtick', c='#d43221') # x轴刻度文字颜色 plt.rc('ytick', c='#d43221') # y轴刻度文字颜色 plt.rc('grid', c='#800000', alpha=0.9, ls=':', lw=0.8) # 网格属性(颜色,透明值,线条样式,线宽) plt.rc('lines', lw=0.8) # 全局线宽 fig = plt.figure(figsize=(16, 8)) left, width = 0.05, 0.9 self.ax1 = fig.add_axes([left, 0.5, width, 0.48]) # left, bottom, width, height self.ax2 = fig.add_axes([left, 0.4, width, 0.1], sharex=self.ax1) # 共享ax1轴 self.ax3 = fig.add_axes([left, 0.3, width, 0.09], sharex=self.ax1) # 共享ax1轴 self.ax4 = fig.add_axes([left, 0.2, width, 0.09], sharex=self.ax1) # 共享ax1轴 self.ax5 = fig.add_axes([left, 0.1, width, 0.09], sharex=self.ax1) # 共享ax1轴 plt.setp(self.ax1.get_xticklabels(), visible=True) # 使x轴刻度文本不可见,因为共享,不需要显示 plt.setp(self.ax2.get_xticklabels(), visible=True) # 使x轴刻度文本不可见,因为共享,不需要显示 self.ax1.xaxis.set_major_formatter( ticker.FuncFormatter(self.format_date)) # 设置自定义x轴格式化日期函数 self.ax1.xaxis.set_major_locator( ticker.MultipleLocator(max(int(len(result) / 15), 5))) # 横向最多排15个左右的日期,最少5个,防止日期太拥挤 # # 下面这一段代码,替换了上面注释的这个函数,因为上面的这个函数达不到同花顺的效果 opens, closes, highs, lows = self.matix[:, 1], self.matix[:, 4], self.matix[:, 2], self.matix[:, 3] # 取出ochl值 avg_dist_between_points = (xdates[-1] - xdates[0]) / float( len(xdates)) # 计算每个日期之间的距离 delta = avg_dist_between_points / 4.0 # 用于K线实体(矩形)的偏移坐标计算 barVerts = [((date - delta, open), (date - delta, close), (date + delta, close), (date + delta, open)) for date, open, close in zip(xdates, opens, closes) ] # 生成K线实体(矩形)的4个顶点坐标 rangeSegLow = [ ((date, low), (date, min(open, close))) for date, low, open, close in zip(xdates, lows, opens, closes) ] # 生成下影线顶点列表 rangeSegHigh = [((date, high), (date, max(open, close))) for date, high, open, close in zip( xdates, highs, opens, closes)] # 生成上影线顶点列表 rangeSegments = rangeSegLow + rangeSegHigh # 上下影线顶点列表 cmap = { True: mcolors.to_rgba('#000000', 1.0), False: mcolors.to_rgba('#54fcfc', 1.0) } # K线实体(矩形)中间的背景色(True是上涨颜色,False是下跌颜色) inner_colors = [ cmap[opn < cls] for opn, cls in zip(opens, closes) ] # K线实体(矩形)中间的背景色列表 cmap = { True: mcolors.to_rgba('#ff3232', 1.0), False: mcolors.to_rgba('#54fcfc', 1.0) } # K线实体(矩形)边框线颜色(上下影线和后面的成交量颜色也共用) updown_colors = [ cmap[opn < cls] for opn, cls in zip(opens, closes) ] # K线实体(矩形)边框线颜色(上下影线和后面的成交量颜色也共用)列表 # self.ax1.add_collection( LineCollection(rangeSegments, colors=updown_colors, linewidths=0.5, antialiaseds=False)) # 生成上下影线的顶点数据(颜色,线宽,反锯齿,反锯齿关闭好像没效果) self.ax1.add_collection( PolyCollection(barVerts, facecolors=inner_colors, edgecolors=updown_colors, antialiaseds=False, linewidths=0.5)) # 生成多边形(矩形)顶点数据(背景填充色,边框色,反锯齿,线宽) # 绘制均线 mav_colors = [ '#ffffff', '#d4ff07', '#ff80ff', '#00e600', '#02e2f4', '#ffffb9', '#2a6848' ] # 均线循环颜色 mav_period = [5, 10, 20, 30, 60, 120, 180] # 定义要绘制的均线周期,可增减 n = len(result) for i in range(len(mav_period)): if n >= mav_period[i]: mav_vals = result['close'].rolling( mav_period[i]).mean().values self.ax1.plot(xdates, mav_vals, c=mav_colors[i % len(mav_colors)], label='MA' + str(mav_period[i])) # 线性回归展示 # for item in erChengPrice: # myX=item[0] # myY=item[1] # ax1.plot(myX, myY, color="yellow", linewidth=0.3) self.ax1.plot(xdates, t3Price, label='t3price') self.ax1.set_title(code) # 标题 self.ax1.grid(True) # 画网格 self.ax1.legend(loc='upper left') # 图例放置于右上角 self.ax1.xaxis_date() # 好像要不要效果一样? return