def RSI(data, timeperiod=14): return talib.RSI(data['close'], timeperiod=timeperiod)
def add_ta_features(self): obv = talib.OBV(self.close, self.volume) obv_mv_avg = talib.MA(obv, timeperiod=10) obv_mv_avg[np.isnan(obv_mv_avg)] = obv[np.isnan(obv_mv_avg)] difference = obv - obv_mv_avg self.df['obv'] = obv self.df['obv_signal'] = difference self.df['obv_cheat'] = np.gradient(difference) upper, middle, lower = talib.BBANDS(self.close, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0) self.df['dn'] = lower self.df['mavg'] = middle self.df['up'] = upper self.df['pctB'] = (self.close - self.df.dn) / (self.df.up - self.df.dn) rsi14 = talib.RSI(self.close, 14) self.df['rsi14'] = rsi14 macd, macdsignal, macdhist = talib.MACD(self.close, 12, 26, 9) self.df['macd'] = macd self.df['signal'] = macdsignal ## addtional info self.df['adx'] = talib.ADX(self.high, self.low, self.close, timeperiod=14) self.df['cci'] = talib.CCI(self.high, self.low, self.close, timeperiod=14) ## maximum profit self.df['plus_di'] = talib.PLUS_DI(self.high, self.low, self.close, timeperiod=14) ## lower_bound self.df['lower_bound'] = self.df['open'] - self.df['low'] + 1 ## ATR self.df['atr'] = talib.ATR(self.high, self.low, self.close, timeperiod=14) ## STOCH momentum self.df = ta.stochastic_oscillator_k(self.df) self.df = ta.stochastic_oscillator_d(self.df, n=10) ## TRIX self.df['trix'] = talib.TRIX(self.close, timeperiod=5) self.df['trix_signal'] = ta.moving_average(self.df['trix'], n=3) self.df['trix_hist'] = self.df['trix'] - self.df['trix_signal'] ## MFI self.df['mfi14'] = money_flow_index(self.df, 14)
def get_factors(index, Open, Close, High, Low, Volume, rolling=26, drop=False, normalization=False): 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 rsi(self, n, array=False): """RSI指标""" result = talib.RSI(self.close, n) if array: return result return result[-1]
quandl.ApiConfig.api_key = 'fRsTyQJZaBbXBcKsnahq' stock_price = quandl.get('BSE/BOM500325', start_date='2010-01-01', end_date='2019-12-31') info = stock_price[{'Open','High', 'Close', 'Low', 'WAP'}] info.loc[:,'Volume'] = stock_price.loc[:, 'No. of Trades'] info.loc[:, 'Date'] = pd.to_datetime(info.index, format='%m/%d/%Y') info.loc[:,"daily_returns"] = info.iloc[3:,1] / info.iloc[:-3, 1].values - 1 info.daily_returns = info.daily_returns.shift(periods=-3) #info.loc[:,'SMA3']= talib.SMA() #info.loc[:,'SMA6']= pd.Series(info.Open).rolling(window=6).mean() #info.loc[:,'SMA7']= pd.Series(info.Open).rolling(window=7).mean() #info.loc[:,'SMA15']= pd.Series(info.Open).rolling(window=15).mean() info.loc[:,'RSI3'] = talib.RSI(info.daily_returns,small_period) info.loc[:,'RSI10'] = talib.RSI(info.daily_returns,large_period) info.loc[:,'WillR'] = talib.WILLR(info.High, info.Low, info.Close, timeperiod=large_period) macd, macdsignal, macdhist = talib.MACD(info.Close, 12, 26,9) info.loc[:,'MACD'] = macd info.loc[:,'MACDSIGNAL'] = macdsignal del [macd, macdsignal, macdhist] info.loc[:,'MFI'] = talib.MFI(info.High, info.Low, info.Close, info.Volume, timeperiod=14) info.loc[:,'PLUS_DI'] = talib.PLUS_DI(info.High, info.Low, info.Close, large_period) info.loc[:,'PLUS_DM'] = talib.PLUS_DM(info.High, info.Low, large_period) info.loc[:,'ADX'] = talib.ADX(info.High, info.Low, info.Close, 15) info.loc[:,'TRIX'] = talib.TRIX(info.Close, 15) info.loc[:,'OBV']= talib.OBV(info.Close, info.Volume) info = info.dropna()
import talib #initializations lengthTime=172800 #ema=[0] #ethbtc_price=np.array([]) #avggain and loss persists from other script, gucci while 1: #update every second #ethbtc_price=np.append(ethbtc_price,float(line[21:31]) #np array #ethbtc_price.append(float(line[21:31])) if(len(ethbtc_price)>lengthTime): #del ethbtc_price[0] ethbtc_price=np.delete(ethbtc_price,0) #has to be numpy, talib wants numpy sma=talib.SMA(ethbtc_price,timeperiod=lengthTime) ema=talib.EMA(ethbtc_price,timeperiod=lengthTime) rsi=talib.RSI(ethbtc_price,timeperiod=lengthTime) hMacD,mMacD,lMacD=talib.MACD(ethbtc_price,fastperiod=12, slowperiod=26, signalperiod=9)#default intervals if(len(ethbtc_high)>=1500 and len(ethbtc_low)>=1500): cci=talib.CCI(ethbtc_high,ethbtc_low,ethbtc_close,timeperiod=60) print "asdf",sma time.sleep(1) #datafile=open("/Users/ryan/Desktop/inodawey/ethbtc_price.txt", "r") #while 1: # where = datafile.tell() # line = datafile.readline() # if not line:
def handle_data(context, data): # define the windows for the moving averages short_window = 5 mid_window = 70 long_window = 150 # Skip as many bars as long_window to properly compute the average context.i += 1 if context.i < long_window: return price = data.current(context.asset, 'price') # Compute moving averages calling data.history() for each # moving average with the appropriate parameters. We choose to use # minute bars for this simulation -> freq="1m" # Returns a pandas dataframe. short_data = data.history( context.asset, 'price', bar_count=short_window, frequency="15m", ) short_mavg = short_data.mean() mid_data = data.history( context.asset, 'price', bar_count=mid_window, frequency="15m", ) mid_mavg = mid_data.mean() long_data = data.history( context.asset, 'price', bar_count=long_window, frequency="15m", ) candle_data = data.history( context.asset, fields=['price', 'open', 'high', 'low', 'close'], bar_count=120, frequency="5m", ) long_mavg = long_data.mean() adx_len = 40 adx_thresh = 20 adx = talib.ADX(candle_data.high.as_matrix(), candle_data.low.as_matrix(), candle_data.close.as_matrix(), timeperiod=adx_len)[-1] mDI = talib.MINUS_DI(candle_data.high.as_matrix(), candle_data.low.as_matrix(), candle_data.close.as_matrix(), timeperiod=adx_len)[-1] pDI = talib.PLUS_DI(candle_data.high.as_matrix(), candle_data.low.as_matrix(), candle_data.close.as_matrix(), timeperiod=adx_len)[-1] rsi = talib.RSI(candle_data.close.as_matrix(), timeperiod=14)[-1] long_mavg = talib.EMA(long_data, timeperiod=long_window)[-1] prices14 = data.history(context.asset, ['price', 'volume'], 14, "5m") vwap = VWAP(prices14["price"], prices14["volume"]) # Let's keep the price of our asset in a more handy variable # If base_price is not set, we use the current value. This is the # price at the first bar which we reference to calculate price_change. if context.base_price is None: context.base_price = price price_change = (price - context.base_price) / context.base_price # Save values for later inspection record(price=price, cash=context.portfolio.cash, adx=adx, adx_prev=context.adx_prev, mDI=mDI, pDI=pDI, price_change=price_change, short_mavg=short_mavg, mid_mavg=mid_mavg, long_mavg=long_mavg, vwap=vwap) # Since we are using limit orders, some orders may not execute immediately # we wait until all orders are executed before considering more trades. orders = context.blotter.open_orders if len(orders) > 0: return # Exit if we cannot trade if not data.can_trade(context.asset): return # We check what's our position on our portfolio and trade accordingly pos_amount = context.portfolio.positions[context.asset].amount # Trading logic # if short_mavg > long_mavg and pos_amount == 0: # # we buy 100% of our portfolio for this asset # order_target_percent(context.asset, 1) # elif short_mavg < long_mavg and pos_amount > 0: # # we sell all our positions for this asset # order_target_percent(context.asset, 0) if context.trade_price != None: trade_change = (price - context.trade_price) / (context.trade_price) else: trade_change = 0 if ( short_mavg > long_mavg ) and pDI > mDI and price >= long_mavg and pos_amount == 0 and context.adx_sell is True: if context.timer == 0: # we buy 100% of our portfolio for this asset order_target_percent(context.asset, 1) context.trade_price = price context.adx_sell = False elif (pDI < mDI): # we sell all our positions for this asset if pos_amount > 0: pass #order_target_percent(context.asset, 0) #else: context.adx_sell = True if pos_amount > 0 and ((trade_change > 0.01)): order_target_percent(context.asset, 0.5) if pos_amount > 0 and ((trade_change > 0.02 or trade_change < -0.01)): order_target_percent(context.asset, 0) context.timer = 1 if context.timer > context.trade_timer: context.timer = 0 context.adx_sell = True elif context.timer > 0: context.timer += 1 context.last_price = price if context.counter < 5: context.counter += 1 else: context.adx_prev = adx context.counter = 0
def RSI(close, period): return ta.RSI(close, timeperiod=period)
from sklearn import mixture as mix from sklearn.preprocessing import StandardScaler from sklearn.svm import SVC df = web.get_data_yahoo('SPY', start = '2000-01-01', end = '2017-08-08') df = df[['Open', 'High', 'Low', 'Close']] n = 10 t = 0.8 split = int(t * len(df)) df['high'] = df['High'].shift(1) df['Low'] = df['Low'].shift(1) df['Close'] = df['Close'].shift(1) df['RSI'] = ta.RSI(np.array(df['close']), timeperiod = n) df['SMA'] = df['close'].rolling(window = n).mean() df['Corr'] = df['SMA'].rolling(window = n).corr(df['close']) df['SAR'] = ta.SAR(np.array(df['high']), np.array(df['low']), 0.2,0.2) df['ADX'] = ta.ADX(np.array(df['high']), np.array(df['low']), np.array(df['close']), timeperiod = n) df['Return'] = np.log(df['Open'] / df['Open'].shift(1)) print(df.head()) df = df.dropna() ss = StandardScaler() unsup.fit(np.reshape(ss.fit_transform(df[:split]), (-1, df.shape[1]))) regime = unsup.predict(np.reshape(ss.fit_transform(df[split:]), \ (-1, df.shape[1])))
import random random.seed(42) #Importing the dataset dataset = pd.read_csv('RELIANCE.NS.csv') dataset = dataset.dropna() dataset = dataset[['Open', 'High', 'Low', 'Close']] #Preparing the dataset dataset['H-L'] = dataset['High'] - dataset['Low'] dataset['O-C'] = dataset['Close'] - dataset['Open'] dataset['3day MA'] = dataset['Close'].shift(1).rolling(window=3).mean() dataset['10day MA'] = dataset['Close'].shift(1).rolling(window=10).mean() dataset['30day MA'] = dataset['Close'].shift(1).rolling(window=30).mean() dataset['Std_dev'] = dataset['Close'].rolling(5).std() dataset['RSI'] = talib.RSI(dataset['Close'].values, timeperiod=9) dataset['Williams %R'] = talib.WILLR(dataset['High'].values, dataset['Low'].values, dataset['Close'].values, 7) dataset['Price_Rise'] = np.where(dataset['Close'].shift(-1) > dataset['Close'], 1, 0) dataset = dataset.dropna() X = dataset.iloc[:, 3:-1] y = dataset.iloc[:, -1] #Splitting the dataset split = int(len(dataset) * 0.8) X_train, X_test, y_train, y_test = X[:split], X[split:], y[:split], y[split:]
def creat_ta_data(): target = [] pct = SS.sclose.pct_change().dropna() v = pct.values for i in v: if i > 0.015: target.append(4) elif i < -0.015: target.append(0) elif i > 0.005: target.append(3) elif i < -0.005: target.append(1) else: target.append(2) target = pd.DataFrame(data=target, index=pct.index, columns=['target']) MA = pd.DataFrame() #计算10-90日均线 for i in range(10, 90, 10): local_MA = ta.MA(SS.sclose, timeperiod=i) local_MA.name = 'MA' + str(i) MA = pd.concat([MA, local_MA], axis=1) MACD1, MACD2, XX = ta.MACD(SS.sclose) MACD = pd.concat([MACD1, MACD2], axis=1) ADX = ta.ADX(SS.high, SS.low, SS.sclose) ADXR = ta.ADXR(SS.high, SS.low, SS.sclose) aroondown, aroonup = ta.AROON(SS.high, SS.low) ATR = ta.ATR(SS.high, SS.low, SS.sclose) Bupper, Bmiddle, Blower = ta.BBANDS(SS.sclose) group1 = pd.concat([ SS, MA, MACD, ADX, ADXR, aroondown, aroonup, ATR, Bupper, Bmiddle, Blower ], 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类型 return ta_index
import tushare as ts import pandas as pd import matplotlib.pyplot as plt import numpy as np import talib df=ts.get_hist_data('601328',start='2015-01-01',end='2015-12-31') df=df.sort_index() df.index=pd.to_datetime(df.index,format='%Y-%m-%d') close = df.close # 6日的强度指标、24日的强度指标 df['RSI_6'] = talib.RSI(np.array(close), timeperiod=6) df['RSI_24'] = talib.RSI(np.array(close), timeperiod=24) #买卖信号 #6日的超买和超卖 sig1=[] for i in df.RSI_6: if i>80: sig1.append(1) elif i<20: sig1.append(-1) else: sig1.append(0) df['sig1']=sig1 df.RSI_6[7] #交易信号2:黄金交叉与死亡交叉 sig2=pd.Series(0,index=df.index) lagrsi6=df.RSI_6.shift(1) lagrsi24=df.RSI_24.shift(1)
def transform(self, X): now = datetime.datetime.now() # print('[{}] : Starting new Transformer optimizing 67 Technical Indicator parameters'.format(now.strftime("%Y-%m-%d %H:%M:%S"))) """ @param X: Training set @type X: numpy array of shape [n_samples, n_features] @return: Transformed array. @rtype: X_newnumpy array of shape [n_samples, n_features_new] """ X = self._validate_input(X) X = X.copy() # Simple Moving Average (SMA) ''' Description: iloc is primarily integer position based (from 0 to length-1 of the axis), but may also be used with a boolean array. ''' X['SMA_Close'] = talib.SMA(X["Close"], timeperiod=self.sma_close_timeperiod) # Stochastic Oscillator (SO) StochasticOscillator = ta.momentum.StochasticOscillator( high=X["High"], low=X["Low"], close=X["Close"], n=self.so_n, d_n=self.so_d_n, fillna=False) X['SO'] = StochasticOscillator.stoch() # Momentum (M) X['Momentum'] = talib.MOM(X["Close"], timeperiod=self.momentum_period) # Price Rate Of Change (ROC) ''' Description: is a pure momentum oscillator that measures the percent change in price from one period to the next The ROC calculation compares the current price with the price “n” periods ago ''' RateOfChange = ta.momentum.ROCIndicator(close=X["Close"], n=self.roc_period, fillna=False) X['ROC'] = RateOfChange.roc() # Williams %R ''' Description: Williams %R reflects the level of the close relative to the highest high for the look-back period Williams %R oscillates from 0 to -100. Readings from 0 to -20 are considered overbought. Readings from -80 to -100 are considered oversold. ''' WilliamsR = ta.momentum.WilliamsRIndicator(high=X["High"], low=X["Low"], close=X["Close"], lbp=self.wr_lookback_period, fillna=False) X['WR'] = WilliamsR.wr() # Weighted Closing Price (WCP) X['WCP'] = talib.WCLPRICE(X["High"], X["Low"], X["Close"]) # Williams Accumulation Distribution Line # AKA Accumulation/Distribution Index (ADI)???? ''' Description: a volume-based indicator designed to measure the cumulative flow of money into and out of a security The Accumulation Distribution Line rises when the multiplier is positive and falls when the multiplier is negative. ''' if self.useVolume: ADI = ta.volume.AccDistIndexIndicator(high=X["High"], low=X["Low"], close=X["Close"], volume=X["Volume"], fillna=False) X['ADI'] = ADI.acc_dist_index() # Moving Average Convergence Divergence (MACD) ''' Description: Is a trend-following momentum indicator that shows the relationship between two moving averages of prices. ''' MACD = ta.trend.MACD(close=X["Close"], n_slow=self.macd_period_longterm, n_fast=self.macd_period_shortterm, n_sign=self.macd_period_to_signal, fillna=False) X['MACD'] = MACD.macd() # Bollinger Bands (BB) ''' Description: CCI measures the difference between a security’s price change and its average price change. High positive readings indicate that prices are well above their average, which is a show of strength. Low negative readings indicate that prices are well below their average, which is a show of weakness. ''' indicator_bb = ta.volatility.BollingerBands( close=X["Close"], n=self.bb_periods, ndev=self.bb_n_factor_standard_dev, fillna=False) # Add Bollinger Bands features # X['bb_bbm'] = indicator_bb.bollinger_mavg() X['BB_H'] = indicator_bb.bollinger_hband() X['BB_L'] = indicator_bb.bollinger_lband() # Add Bollinger Band high indicator X['bb_bbhi'] = indicator_bb.bollinger_hband_indicator() # Add Bollinger Band low indicator X['bb_bbli'] = indicator_bb.bollinger_lband_indicator() # Add width size Bollinger Bands X['bb_bbw'] = indicator_bb.bollinger_wband() # Mean Open & Close (M_O, M_C) period = 3 X['MEAN_O_C'] = ( talib.SMA(X["Open"], timeperiod=self.mean_o_c_period) / 2) + (talib.SMA(X["Close"], timeperiod=self.mean_o_c_period) / 2) # Variance Open & Close X["VAR_Close"] = talib.VAR(X["Close"], timeperiod=self.var_close_period, nbdev=self.var_close_nbdev) X["VAR_Open"] = talib.VAR(X["Open"], timeperiod=self.var_open_period, nbdev=self.var_open_nbdev) # High Price Average ''' Description: Simple moving average over the high ''' X['SMA_High'] = talib.SMA(X["High"], timeperiod=self.sma_high_period) # Low Price Average ''' Description: Simple moving average over the low ''' X['SMA_Low'] = talib.SMA(X["Low"], timeperiod=self.sma_low_period) # High, Low Average ''' Description: Simple moving average over the sum of high and low ''' X['SMA_H+L'] = talib.SMA(X["High"] + X["Low"], timeperiod=self.sma_handl_period) # Trading Day Price Average ''' Description: Simple moving average over the sum of the open, high, low and close ''' X['SMA_H+L+C+O'] = talib.SMA(X["High"] + X["Low"] + X["Open"] + X["Close"], timeperiod=self.sma_h_l_c_o_period) # From here on adding random indicators according to the ta-lib library # ######################## OVERLAP STUDIES ############################ # Double Exponential Moving Average X['DEMA'] = talib.DEMA(X["Close"], timeperiod=self.dema_period) # Exponential Moving Average X['EMA'] = talib.EMA(X["Close"], timeperiod=self.ema_period) # HT_TRENDLINE - Hilbert Transform - Instantaneous Trendline X['HT_TRENDLINE'] = talib.HT_TRENDLINE(X["Close"]) # KAMA - Kaufman Adaptive Moving Average X['KAMA'] = talib.KAMA(X["Close"], timeperiod=self.kama_period) # MA - Moving average X['MA'] = talib.MA(X["Close"], timeperiod=self.ma_period, matype=0) # MIDPOINT - MidPoint over period X['MIDPOINT'] = talib.MIDPOINT(X["Close"], timeperiod=self.midpoint_period) # MIDPRICE - Midpoint Price over period X['MIDPRICE'] = talib.MIDPRICE(X["High"], X["Low"], timeperiod=self.midprice_period) # SAR - Parabolic SAR X['SAR'] = talib.SAR(X["High"], X["Low"], acceleration=self.sar_acceleration, maximum=self.sar_maximum) # SAREXT - Parabolic SAR - Extended X['SAREXT'] = talib.SAREXT( X["High"], X["Low"], startvalue=self.sarext_startvalue, offsetonreverse=self.sarext_offsetonreverse, accelerationinitlong=self.sarext_accelerationinitlong, accelerationlong=self.sarext_accelerationlong, accelerationmaxlong=self.sarext_accelerationmaxlong, accelerationinitshort=self.sarext_accelerationinitshort, accelerationshort=self.sarext_accelerationshort, accelerationmaxshort=self.sarext_accelerationmaxshort) # T3 - Triple Exponential Moving Average (T3) X['T3'] = talib.T3(X["Close"], timeperiod=self.t3_period, vfactor=self.t3_vfactor) # TEMA - Triple Exponential Moving Average X['TEMA'] = talib.TEMA(X["Close"], timeperiod=self.tema_period) # TRIMA - Triangular Moving Average X['TRIMA'] = talib.TRIMA(X["Close"], timeperiod=self.trima_period) # WMA - Weighted Moving Average X['WMA'] = talib.WMA(X["Close"], timeperiod=self.wma_period) # ######################## Momentum Indicators ############################ # ADX - Average Directional Movement Index X['ADX'] = talib.ADX(X["High"], X["Low"], X["Close"], timeperiod=self.adx_period) # ADXR - Average Directional Movement Index Rating X['ADXR'] = talib.ADXR(X["High"], X["Low"], X["Close"], timeperiod=self.adxr_period) # APO - Absolute Price Oscillator X['APO'] = talib.APO(X["Close"], fastperiod=self.apo_fastperiod, slowperiod=self.apo_slowperiod, matype=self.apo_matype) # AROON - Aroon X['aroondown'], X['aroonup'] = talib.AROON( X["High"], X["Low"], timeperiod=self.aroon_period) # AROONOSC - Aroon Oscillator X['AROONOSC'] = talib.AROONOSC(X["High"], X["Low"], timeperiod=self.aroonosc_period) # BOP - Balance Of Power X['BOP'] = talib.BOP(X["Open"], X["High"], X["Low"], X["Close"]) # CMO - Chande Momentum Oscillator X['CMO'] = talib.CMO(X["Close"], timeperiod=self.cmo_period) # DX - Directional Movement Index X['DX'] = talib.DX(X["High"], X["Low"], X["Close"], timeperiod=self.dx_period) if self.useVolume: # MFI - Money Flow Index X['MFI'] = talib.MFI(X["High"], X["Low"], X["Close"], X["Volume"], timeperiod=self.mfi_period) # MINUS_DI - Minus Directional Indicator X['MINUS_DI'] = talib.MINUS_DI(X["High"], X["Low"], X["Close"], timeperiod=self.minus_di_period) # MINUS_DM - Minus Directional Movement X['MINUS_DM'] = talib.MINUS_DM(X["High"], X["Low"], timeperiod=self.minus_dm_period) # PLUS_DI - Plus Directional Indicator X['PLUS_DI'] = talib.PLUS_DI(X["High"], X["Low"], X["Close"], timeperiod=self.plus_di_period) # PLUS_DM - Plus Directional Movement X['PLUS_DM'] = talib.PLUS_DM(X["High"], X["Low"], timeperiod=self.plus_dm_period) # PPO - Percentage Price Oscillator X['PPO'] = talib.PPO(X["Close"], fastperiod=self.ppo_fastperiod, slowperiod=self.ppo_slowperiod, matype=self.ppo_matype) # ROCP - Rate of change Percentage: (price-prevPrice)/prevPrice X['ROCP'] = talib.ROCP(X["Close"], timeperiod=self.rocp_period) # ROCR - Rate of change ratio: (price/prevPrice) X['ROCR'] = talib.ROCR(X["Close"], timeperiod=self.rocr_period) # ROCR100 - Rate of change ratio 100 scale: (price/prevPrice)*100 X['ROCR100'] = talib.ROCR100(X["Close"], timeperiod=self.rocr100_period) # RSI - Relative Strength Index X['RSI'] = talib.RSI(X["Close"], timeperiod=self.rsi_period) # TRIX - 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA X['TRIX'] = talib.TRIX(X["Close"], timeperiod=self.trix_period) # ULTOSC - Ultimate Oscillator X['ULTOSC'] = talib.ULTOSC(X["High"], X["Low"], X["Close"], timeperiod1=self.ultosc_period1, timeperiod2=self.ultosc_period1, timeperiod3=self.ultosc_period3) if self.useVolume: # ######################## Volume Indicators ############################ # AD - Chaikin A/D Line X['AD'] = talib.AD(X["High"], X["Low"], X["Close"], X["Volume"]) # ADOSC - Chaikin A/D Oscillator X['ADOSC'] = talib.ADOSC(X["High"], X["Low"], X["Close"], X["Volume"], fastperiod=self.adosc_fastperiod, slowperiod=self.adosc_slowperiod) # OBV - On Balance Volume X['OBV'] = talib.OBV(X["Close"], X["Volume"]) # ######################## Cycle Indicators ############################ # HT_DCPERIOD - Hilbert Transform - Dominant Cycle Period X['HT_DCPERIOD'] = talib.HT_DCPERIOD(X["Close"]) # HT_DCPHASE - Hilbert Transform - Dominant Cycle Phase #X['HT_DCPHASE'] = talib.HT_DCPHASE(X["Close"]) # HT_TRENDMODE - Hilbert Transform - Trend vs Cycle Mode #X['HT_TRENDMODE'] = talib.HT_TRENDMODE(X["Close"]) # ######################## Price transform functions ############################ # AVGPRICE - Average Price X['AVGPRICE'] = talib.AVGPRICE(X["Open"], X["High"], X["Low"], X["Close"]) # MEDPRICE - Median Price X['MEDPRICE'] = talib.MEDPRICE(X["High"], X["Low"]) # TYPPRICE - Typical Price X['TYPPRICE'] = talib.TYPPRICE(X["High"], X["Low"], X["Close"]) # WCLPRICE - Weighted Close Price X['WCLPRICE'] = talib.WCLPRICE(X["High"], X["Low"], X["Close"]) # ################################ END OF TECHINCAL INDICATORS ######################### # Delete columns that contains only NaN values ''' cols = X.columns[X.isna().all()] X = X.drop(cols, axis=1) # Delete rows that contain at least one NaN X = X.dropna() ''' return X
def calc_technical_indicators(df, column_name: str, id: int, all: bool, verbose: bool): """ Calculates a set of selecteed technical indicators based on the close price of the given stock :param df: pandas data frame :param column_name: MUST refer to the close price of the stock :return: Void - modifies the frame in place """ close = np.asarray(df[column_name]) # This is for experimenting to generate a wide range of technical indicators # requires subsequent feature ranking full_range = [ 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 25, 26, 27, 28, 29 ] short_range = [3, 5, 7, 10, 15, 20, 25] long_range = [50, 60, 70, 80, 100, 150, 200, 250] range = full_range + long_range if (id == 1 or all): # Bollinger bands df['UP_BB'], df['MID_BB'], df['LOW_BB'] = talib.BBANDS( close, timeperiod=20, nbdevup=2, nbdevdn=2, matype=0) if (verbose): print("ID: " + str(id)) print("Bollinger bands") print(df.corr()) if (id == 2 or all): # Create Simple Moving Average # Time range adjusted based on feature ranking for S&P500 periods = range # [2, 3, 4, 5, 7] for period in periods: df['SMA-' + str(period)] = talib.SMA(close, timeperiod=period) if (verbose): print("ID: " + str(id)) print("Simple Moving Average") print(df.corr()) if (id == 3 or all): # Create Exponential moving average # correlation drops at 30 and beyond # time range adjusted based on feature ranking for S&P500 periods = range # [6,7,9,12] for period in periods: df['EMA-' + str(period)] = talib.EMA(close, timeperiod=period) if (verbose): print("ID: " + str(id)) print("Exponential Moving Average") print(df.corr()) if (id == 4 or all): # Create Momentum # no strong correlation for the MOM indicators was found, thus disabled. # only MOM-300 yields about ~ -30% Corr. periods = range for period in periods: df['MOM-' + str(period)] = talib.MOM(close, timeperiod=period) if (verbose): print("ID: " + str(id)) print("Momentum") print(df.corr()) if (id == 5 or all): # Create RSI # Time range adjusted based on feature ranking for S&P500 periods = range # [10, 11, 12, 13, 14, 15, 21, 22] for period in periods: df['RSI-' + str(period)] = talib.RSI(close, timeperiod=period) if (verbose): print("ID: " + str(id)) print("RSI") print(df.corr()) if (id == 6 or all): # Create TRIX # Time range adjusted based on feature ranking for S&P500 # For a smaller sample size, only Trix-30 shows higehst correlation to close price. # Add full range to re-test and look how Trix-30 performs periods = range # [3, 4] # range for period in periods: df['TRIX-' + str(period)] = talib.TRIX(close, timeperiod=period) if (verbose): print("ID: " + str(id)) print("Trix") print(df.corr()) if (id == 7 or all): # Cycle Indicator Functions # https://mrjbq7.github.io/ta-lib/func_groups/cycle_indicators.html df["HT_DCPERIOD"] = talib.HT_DCPERIOD(close) df["HT_DCPHASE"] = talib.HT_DCPHASE(close) df["HT_TRENDMODE"] = talib.HT_TRENDMODE(close) if (verbose): print("ID: " + str(id)) print("Cycle Indicator Functions") print(df.corr())
import numpy import talib from numpy import genfromtxt my_data = genfromtxt('15minutes.csv', delimiter=',') print(my_data) close = my_data[:,4] print(close) # moving_average = talib.SMA(close, timeperiod=10) # print(moving_average) rsi = talib.RSI(close) print(rsi)
def rsi(self, period): df = pd.DataFrame(index=self.index) close = self.data.close rsi = talib.RSI(close, timeperiod=14) df[f'rsi_{period}'] = rsi return df
def GetRSI(self,tp=14): return talib.RSI(self.Close, timeperiod=tp)
def test_TA_rsi(): talib.RSI(close_np, timeperiod=14)
df['Skew'] = round(df[['Open', 'High', 'Low', 'Adj Close']].skew(axis=1), 4) df.head() df['Kurt'] = round(df[['Open', 'High', 'Low', 'Adj Close']].kurt(axis=1), 4) df.head() # Standard error of the mean df['Error'] = df[['Open', 'High', 'Low', 'Adj Close']].sem(axis=1) df.head() import talib as ta # Creating Indicators n = 5 df['RSI'] = ta.RSI(np.array(df['Adj Close'].shift(1)), timeperiod=n) df['SMA'] = pd.rolling_mean(df['Adj Close'].shift(1), window=n) df['Corr'] = pd.rolling_corr(df['SMA'], df['Adj Close'].shift(1), window=n) df['SAR'] = ta.SAR(np.array(df['High'].shift(1)), np.array(df['Low'].shift(1)), 0.2, 0.2) # Momemtum Indicator Functions df['ADX'] = ta.ADX(np.array(df['High'].shift(1)), np.array(df['Low'].shift(1)), np.array(df['Open'].shift(1)), timeperiod=n) df['ADXR'] = ta.ADXR(np.array(df['High'].shift(1)), np.array(df['Low'].shift(1)), np.array(df['Adj Close']), timeperiod=n) # df['APO']=ta.APO(np.array(df['Adj Close'].shift(1), fastperiod=12, slowperiod=26, matype=0))
def on_message(ws, message): global closes, in_position, bought json_message = json.loads(message) candle = json_message['k'] is_candle_closed = candle['x'] close = float(candle['c']) if is_candle_closed: print("candle closed at {}".format(close)) closes.append(close) if len(closes) > RSI_PERIOD: np_closes = numpy.array(closes) rsi = talib.RSI(np_closes, RSI_PERIOD) rsi = clear_array(rsi) if len(closes) > MACD_START: macd, macdsignal, macdhist = talib.MACD( np_closes, MACD_FAST, MACD_SLOW, MACD_SIGNALPEDIOD) macd = clear_array(macd) macdsignal = clear_array(macdsignal) macdhist = clear_array(macdhist) else: macd, macdsignal, macdhist = (10, 0, 10) last_rsi = rsi[-1] last_macdhist = macdhist[-1] print("the current RSI is {}, MACD is {}".format( last_rsi, last_macdhist)) if last_rsi >= RSI_OVERBOUGHT and (-1.5 <= last_macdhist <= 1.5): if in_position: gain = calc_gain(close, bought) if gain >= MINIMUM_GAIN: print("Overbought! Sell! Sell! Sell!") order_succeeded = order("SELL", TRADE_QUANTITY, TRADE_SYMBOL, close, gain) if order_succeeded: bought = 0 in_position = False else: print("Overbought! But not profitable, nothing to do.") else: print( "It is overbought, but we don't own any. Nothing to do." ) if last_rsi <= RSI_OVERSOLD and (-1.5 <= last_macdhist <= 1.5): if in_position: print( "It is oversold, but you already own it, nothing to do." ) else: print("Oversold! Buy! Buy! Buy!") order_succeeded = order("BUY", TRADE_QUANTITY, TRADE_SYMBOL, close) if order_succeeded: bought = close in_position = True
def backtesting(settingFile, kLineCycle=30, vt_symbol='rb1801', vt_symbol2=None, mode='B', startDate=None, days=1, historyDays=0, optimization=False): # 创建回测引擎 engine = BacktestingEnginePatch() # 设置回测用的数据起始日期 if startDate: startDate = startDate endDate = datetime.strptime(startDate, '%Y%m%d') + timedelta(days) else: startDate = date.today() - timedelta(days + historyDays) endDate = date.today() engine.set_parameters( vt_symbol=vt_symbol, interval="1m", start=startDate, end=endDate, rate=1 / 10000, slippage=1, size=10, pricetick=1, capital=1_000_000, ) setting = {} setting['vt_symbol'] = vt_symbol setting['kLineCycle'] = kLineCycle setting['settingFile'] = settingFile engine.add_strategy(MultiStrategy, setting) engine.load_data() engine.run_backtesting() df = engine.calculate_result() engine.calculate_statistics() #engine.show_chart() # 显示回测结果 resultList = engine.showBacktestingResult() # try: # engine.showDailyResult() # except: # print ('-' * 20) # print ('Failed to showDailyResult') # #traceback.print_exc() # pass try: # 显示定单信息 import pandas as pd orders = pd.DataFrame([i.__dict__ for i in resultList['resultList']]) try: orders['holdTime'] = (orders.exitDt - orders.entryDt).astype('timedelta64[m]') except: pass pd.options.display.max_rows = 100 pd.options.display.width = 300 pd.options.display.precision = 2 engine.output('-' * 50) engine.output(str(orders)) except: print('-' * 20) print('Failed to print result') #traceback.print_exc() try: # 显示详细信息 import pandas as pd from utils import plot_candles, plot_candles1 import talib import numpy as np # analysis #engine.loadHistoryData() orders = pd.DataFrame([i.__dict__ for i in resultList['resultList']]) pricing = pd.DataFrame([i.__dict__ for i in engine.history_data]) #VPIN analysis # from .VPINAnalysis import VPINAnalysis # if len(pricing.index) > 1000: # VPINAnalysis(pricing) atr = talib.ATR(pricing.high_price.values, pricing.low_price.values, pricing.close_price.values, 25) atr_ma = pd.DataFrame(atr).rolling(25).mean()[0].values technicals = { 'rsi': talib.RSI(pricing.close_price.values, 4), 'atr': atr, 'atr-ma': atr_ma } technicals = {} plot_candles1(pricing, volume_bars=True, orders=orders, technicals=technicals) except: print('-' * 20) print('Failed to plot candles') traceback.print_exc()
def get_rsi(self, data): self.get_price_history(data) self.rsi.append(talib.RSI(self.price_history)[-1]) if (len(self.rsi) == 2): self.rsi.pop(0) pass
oil=oil.rename(columns={"Value":'value'}) gold_value=pd.DataFrame((gold['Bid Average']+gold['Ask Average'])/2).rename(columns={0:'value'}) silver_value=pd.DataFrame((silver['Bid Average']+silver['Ask Average'])/2).rename(columns={0:'value_silver'}) ruth_value=pd.DataFrame(ruthenium['New York 9:30']).rename(columns={'New York 9:30':'value_ruth'}) irid_value=pd.DataFrame(iridium['New York 9:30']).rename(columns={'New York 9:30':'value_irid'}) rhod_value=pd.DataFrame(rhodium['New York 9:30']).rename(columns={'New York 9:30':'value_rhod'}) pall_value=pd.DataFrame(palladium['New York 9:30']).rename(columns={'New York 9:30':'value_pall'}) plat_value=pd.DataFrame(platinum['New York 9:30']).rename(columns={'New York 9:30':'value_plat'}) hard=gold_value.join(oil,how='outer',lsuffix='_gold',rsuffix='_oil').join(silver_value,how='outer').join(ruth_value,how='outer').join(irid_value,how='outer').join(pall_value,how='outer').join(rhod_value,how='outer').join(plat_value,how='outer').dropna() hard_tech=pd.DataFrame() cols=hard.columns for x in cols: hard_tech['macd'+x[x.find('_'):]]=talib.MACD(hard[x])[0] hard_tech['rsi'+x[x.find('_'):]]=talib.RSI(hard[x]) hard_tech_pct=pd.DataFrame() cols=hard.columns for x in cols: hard_tech_pct['ppo'+x[x.find('_'):]]=talib.PPO(hard[x])[0] hard_tech_pct['rsi'+x[x.find('_'):]]=talib.RSI(hard[x]) hard_tech=hard_tech.dropna() hard_pct=pd.DataFrame() cols=hard.columns for x in cols: hard_pct['pct'+x[x.find('_'):]]=hard[x].pct_change() hard_pct=hard_pct.replace([np.inf, -np.inf,np.nan], 0)
def extract_by_type(self, feature_type, open_prices=None, close_prices=None, high_prices=None, low_prices=None, volumes=None): if feature_type == 'ROCP': rocp = talib.ROCP(close_prices, timeperiod=1) self.feature.append(rocp) if feature_type == 'OROCP': orocp = talib.ROCP(open_prices, timeperiod=1) self.feature.append(orocp) if feature_type == 'HROCP': hrocp = talib.ROCP(high_prices, timeperiod=1) self.feature.append(hrocp) if feature_type == 'LROCP': lrocp = talib.ROCP(low_prices, timeperiod=1) self.feature.append(lrocp) if feature_type == 'MACD': macd, signal, hist = talib.MACD(close_prices, fastperiod=12, slowperiod=26, signalperiod=9) norm_macd = numpy.nan_to_num(macd) / math.sqrt( numpy.var(numpy.nan_to_num(macd))) norm_signal = numpy.nan_to_num(signal) / math.sqrt( numpy.var(numpy.nan_to_num(signal))) norm_hist = numpy.nan_to_num(hist) / math.sqrt( numpy.var(numpy.nan_to_num(hist))) macdrocp = talib.ROCP(norm_macd + numpy.max(norm_macd) - numpy.min(norm_macd), timeperiod=1) signalrocp = talib.ROCP(norm_signal + numpy.max(norm_signal) - numpy.min(norm_signal), timeperiod=1) histrocp = talib.ROCP(norm_hist + numpy.max(norm_hist) - numpy.min(norm_hist), timeperiod=1) # self.feature.append(macd / 100.0) # self.feature.append(signal / 100.0) # self.feature.append(hist / 100.0) self.feature.append(norm_macd) self.feature.append(norm_signal) self.feature.append(norm_hist) self.feature.append(macdrocp) self.feature.append(signalrocp) self.feature.append(histrocp) if feature_type == 'RSI': rsi6 = talib.RSI(close_prices, timeperiod=6) rsi12 = talib.RSI(close_prices, timeperiod=12) rsi24 = talib.RSI(close_prices, timeperiod=24) rsi6rocp = talib.ROCP(rsi6 + 100., timeperiod=1) rsi12rocp = talib.ROCP(rsi12 + 100., timeperiod=1) rsi24rocp = talib.ROCP(rsi24 + 100., timeperiod=1) self.feature.append(rsi6 / 100.0 - 0.5) self.feature.append(rsi12 / 100.0 - 0.5) self.feature.append(rsi24 / 100.0 - 0.5) # self.feature.append(numpy.maximum(rsi6 / 100.0 - 0.8, 0)) # self.feature.append(numpy.maximum(rsi12 / 100.0 - 0.8, 0)) # self.feature.append(numpy.maximum(rsi24 / 100.0 - 0.8, 0)) # self.feature.append(numpy.minimum(rsi6 / 100.0 - 0.2, 0)) # self.feature.append(numpy.minimum(rsi6 / 100.0 - 0.2, 0)) # self.feature.append(numpy.minimum(rsi6 / 100.0 - 0.2, 0)) # self.feature.append(numpy.maximum(numpy.minimum(rsi6 / 100.0 - 0.5, 0.3), -0.3)) # self.feature.append(numpy.maximum(numpy.minimum(rsi6 / 100.0 - 0.5, 0.3), -0.3)) # self.feature.append(numpy.maximum(numpy.minimum(rsi6 / 100.0 - 0.5, 0.3), -0.3)) self.feature.append(rsi6rocp) self.feature.append(rsi12rocp) self.feature.append(rsi24rocp) if feature_type == 'VROCP': # vrocp = talib.ROCP(volumes, timeperiod=1) norm_volumes = (volumes - numpy.mean(volumes)) / math.sqrt( numpy.var(volumes)) vrocp = talib.ROCP(norm_volumes + numpy.max(norm_volumes) - numpy.min(norm_volumes), timeperiod=1) # self.feature.append(norm_volumes) self.feature.append(vrocp) if feature_type == 'BOLL': upperband, middleband, lowerband = talib.BBANDS(close_prices, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0) self.feature.append((upperband - close_prices) / close_prices) self.feature.append((middleband - close_prices) / close_prices) self.feature.append((lowerband - close_prices) / close_prices) if feature_type == 'MA': ma5 = talib.MA(close_prices, timeperiod=5) ma10 = talib.MA(close_prices, timeperiod=10) ma20 = talib.MA(close_prices, timeperiod=20) ma30 = talib.MA(close_prices, timeperiod=30) ma60 = talib.MA(close_prices, timeperiod=60) ma90 = talib.MA(close_prices, timeperiod=90) ma120 = talib.MA(close_prices, timeperiod=120) ma180 = talib.MA(close_prices, timeperiod=180) ma360 = talib.MA(close_prices, timeperiod=360) ma720 = talib.MA(close_prices, timeperiod=720) ma5rocp = talib.ROCP(ma5, timeperiod=1) ma10rocp = talib.ROCP(ma10, timeperiod=1) ma20rocp = talib.ROCP(ma20, timeperiod=1) ma30rocp = talib.ROCP(ma30, timeperiod=1) ma60rocp = talib.ROCP(ma60, timeperiod=1) ma90rocp = talib.ROCP(ma90, timeperiod=1) ma120rocp = talib.ROCP(ma120, timeperiod=1) ma180rocp = talib.ROCP(ma180, timeperiod=1) ma360rocp = talib.ROCP(ma360, timeperiod=1) ma720rocp = talib.ROCP(ma720, timeperiod=1) self.feature.append(ma5rocp) self.feature.append(ma10rocp) self.feature.append(ma20rocp) self.feature.append(ma30rocp) self.feature.append(ma60rocp) self.feature.append(ma90rocp) self.feature.append(ma120rocp) self.feature.append(ma180rocp) self.feature.append(ma360rocp) self.feature.append(ma720rocp) self.feature.append((ma5 - close_prices) / close_prices) self.feature.append((ma10 - close_prices) / close_prices) self.feature.append((ma20 - close_prices) / close_prices) self.feature.append((ma30 - close_prices) / close_prices) self.feature.append((ma60 - close_prices) / close_prices) self.feature.append((ma90 - close_prices) / close_prices) self.feature.append((ma120 - close_prices) / close_prices) self.feature.append((ma180 - close_prices) / close_prices) self.feature.append((ma360 - close_prices) / close_prices) self.feature.append((ma720 - close_prices) / close_prices) if feature_type == 'VMA': ma5 = talib.MA(volumes, timeperiod=5) ma10 = talib.MA(volumes, timeperiod=10) ma20 = talib.MA(volumes, timeperiod=20) ma30 = talib.MA(volumes, timeperiod=30) ma60 = talib.MA(volumes, timeperiod=60) ma90 = talib.MA(volumes, timeperiod=90) ma120 = talib.MA(volumes, timeperiod=120) ma180 = talib.MA(volumes, timeperiod=180) ma360 = talib.MA(volumes, timeperiod=360) ma720 = talib.MA(volumes, timeperiod=720) ma5rocp = talib.ROCP(ma5, timeperiod=1) ma10rocp = talib.ROCP(ma10, timeperiod=1) ma20rocp = talib.ROCP(ma20, timeperiod=1) ma30rocp = talib.ROCP(ma30, timeperiod=1) ma60rocp = talib.ROCP(ma60, timeperiod=1) ma90rocp = talib.ROCP(ma90, timeperiod=1) ma120rocp = talib.ROCP(ma120, timeperiod=1) ma180rocp = talib.ROCP(ma180, timeperiod=1) ma360rocp = talib.ROCP(ma360, timeperiod=1) ma720rocp = talib.ROCP(ma720, timeperiod=1) self.feature.append(ma5rocp) self.feature.append(ma10rocp) self.feature.append(ma20rocp) self.feature.append(ma30rocp) self.feature.append(ma60rocp) self.feature.append(ma90rocp) self.feature.append(ma120rocp) self.feature.append(ma180rocp) self.feature.append(ma360rocp) self.feature.append(ma720rocp) self.feature.append((ma5 - volumes) / (volumes + 1)) self.feature.append((ma10 - volumes) / (volumes + 1)) self.feature.append((ma20 - volumes) / (volumes + 1)) self.feature.append((ma30 - volumes) / (volumes + 1)) self.feature.append((ma60 - volumes) / (volumes + 1)) self.feature.append((ma90 - volumes) / (volumes + 1)) self.feature.append((ma120 - volumes) / (volumes + 1)) self.feature.append((ma180 - volumes) / (volumes + 1)) self.feature.append((ma360 - volumes) / (volumes + 1)) self.feature.append((ma720 - volumes) / (volumes + 1)) if feature_type == 'PRICE_VOLUME': rocp = talib.ROCP(close_prices, timeperiod=1) norm_volumes = (volumes - numpy.mean(volumes)) / math.sqrt( numpy.var(volumes)) vrocp = talib.ROCP(norm_volumes + numpy.max(norm_volumes) - numpy.min(norm_volumes), timeperiod=1) # vrocp = talib.ROCP(volumes, timeperiod=1) pv = rocp * vrocp * 100. self.feature.append(pv)
def GetRSI(self, lst): C = np.array(self.df['收盤'], dtype=float, ndmin=1) for val in lst: self.df['RSI' + str(val)] = talib.RSI(C, timeperiod=val)
def set_indicator(self): """ Calculates the Relative Strength Index from the array passed """ super() self.real = talib.RSI(real=self.np_array, timeperiod=self.timperiod)
def ExecuteTrendFollowing(self, exchange, moneta, tool, risultato): #Attention: static stoploss and dynamic stoploss cannot be activated simultaneously tool.attivazione_stoploss_statico = 0 #with zero not activated, with 1 activated tool.attivazione_stoploss_dinamico = 1 # with zero not activated, with 1 activated tool.profitto = 0.4 #minimum percentage of profit tool.stoploss_1 = 0.8 #percentage of stoploss tool.stoploss_2 = 2.0 #second level stoploss percentage (not active for now) tool.commissioni = 0.25 #percentage of fees in buy and sell tool.nrtransizioni = 2000 #do not use tool.stoploss_dinamico_moltiplicatore = 0.997 #multiplier of the trailing stop tool.stoploss_dinamico_formula = "row.close * tool.stoploss_dinamico_moltiplicatore" #formula per il calcolo dello stoploss dinamico (trailing stop) tool.attivazione_stoploss_dinamico_limiti = 1 #with zero not activated, with 1 activated. It works if dynamic stoploss is activated tool.stoploss_dinamico_min_profitto = 0.30 #minimum profit compared to lastbuy if activated stoploss_dinamico_limiti tool.stoploss_dinamico_max_perdita = 2 #max loss in percentage compared to lastbuy if activated stoploss_dinamico_limiti tool.hours = 36 #timedelta from now tool.periodo = '5m' #candlestick timeframe self.nome = " Test Strategy Trend Following " candle = candlestick.Candlestick() self.df1 = candle.getCandle(exchange, moneta, tool.hours, tool.periodo) moneta = moneta exchange = exchange self.df1 = self.df1.apply(pd.to_numeric) #-------------Indicators and oscillators self.df1['rsi'] = ta.RSI(self.df1.close.values, timeperiod=14) self.df1['adx'] = ta.ADX(self.df1['high'].values, self.df1['low'].values, self.df1['close'].values, timeperiod=14) # Bollinger bands with qtpylib-------------------------------------- """ bollinger = qt.bollinger_bands(qt.typical_price(self.df1), window=20, stds=2) self.df1['lower'] = bollinger['lower'] self.df1['middle'] = bollinger['mid'] self.df1['upper'] = bollinger['upper'] """ #------------------------------------------------------------------ # Bollinger bands with TA library self.df1['upper'], self.df1['middle'], self.df1['lower'] = ta.BBANDS( self.df1['close'].values, timeperiod=5,nbdevup=1,nbdevdn=1, matype=1) self.df1['upper2'], self.df1['middle2'], self.df1[ 'lower2'] = ta.BBANDS(self.df1['close'].values, timeperiod=5,nbdevup=1.6,nbdevdn=1.6, matype=1) self.df1['upper3'], self.df1['middle3'], self.df1[ 'lower3'] = ta.BBANDS(self.df1['close'].values, timeperiod=5,nbdevup=2,nbdevdn=2, matype=1) #------------------------------------------------------------------ self.df1['PrezzoMed'] = self.df1['close'].mean() self.df1['STDDEV'] = ta.STDDEV(self.df1['close'].values, timeperiod=15, nbdev=1) self.df1['macd'], self.df1['macdsignal'], self.df1[ 'macdhist'] = ta.MACD(self.df1.close.values, fastperiod=12, slowperiod=26, signalperiod=9) self.df1['minus_di'] = ta.MINUS_DI(self.df1['high'].values, self.df1['low'].values, self.df1['close'].values, timeperiod=25) self.df1['plus_di'] = ta.PLUS_DI(self.df1['high'].values, self.df1['low'].values, self.df1['close'].values, timeperiod=25) self.df1['sar'] = ta.SAR(self.df1['high'].values, self.df1['low'].values, acceleration=0, maximum=0) self.df1['mom'] = ta.MOM(self.df1['close'].values, timeperiod=14) self.df1['atr'] = ta.ATR(self.df1['high'].values, self.df1['low'].values, self.df1['close'].values, timeperiod=14) self.df1['ema'] = ta.EMA(self.df1['close'].values, timeperiod=20) self.df1['ema1'] = ta.EMA(self.df1['close'].values, timeperiod=28) self.df1['ema2'] = ta.EMA(self.df1['close'].values, timeperiod=35) self.df1['ema3'] = ta.EMA(self.df1['close'].values, timeperiod=48) self.df1['ema50'] = ta.EMA(self.df1['close'].values, timeperiod=50) self.df1['dema20']= ta.DEMA(self.df1['close'].values, timeperiod=20) self.df1['dema50']= ta.DEMA(self.df1['close'].values, timeperiod=50) self.df1['tema20']= ta.TEMA(self.df1['close'].values, timeperiod=5) self.df1['tema50']= ta.TEMA(self.df1['close'].values, timeperiod=20) self.df1['cci'] = ta.CCI(self.df1['high'].values, self.df1['low'].values, self.df1['close'].values, timeperiod=14) #ta lib moving average self.df1['shortma']= ta.SMA(self.df1['close'].values, timeperiod=10) self.df1['longma']= ta.SMA(self.df1['close'].values, timeperiod=20) # MFI self.df1['mfi'] = ta.MFI(self.df1['high'].values,self.df1['low'].values, self.df1['close'].values, self.df1['volume'].values, timeperiod=14) # Stoch self.df1['slowk'],self.df1['slowd'] = ta.STOCH(self.df1['high'].values,self.df1['low'].values, self.df1['close'].values) # Hammer: values [0, 100] - pattern recognised self.df1['CDLHAMMER'] = ta.CDLHAMMER(self.df1['open'].values,self.df1['high'].values,self.df1['low'].values, self.df1['close'].values) # Inverted Hammer: values self.df1['CDLINVERTEDHAMMER'] = ta.CDLINVERTEDHAMMER(self.df1['open'].values,self.df1['high'].values,self.df1['low'].values, self.df1['close'].values) # Engulfing self.df1['CDLENGULFING'] = ta.CDLENGULFING(self.df1['open'].values,self.df1['high'].values,self.df1['low'].values, self.df1['close'].values) # Hiddake self.df1['CDLHIKKAKE'] = ta.CDLHIKKAKE(self.df1['open'].values,self.df1['high'].values,self.df1['low'].values, self.df1['close'].values) # Doji self.df1['CDLDOJI'] = ta.CDLDOJI(self.df1['open'].values,self.df1['high'].values,self.df1['low'].values, self.df1['close'].values) # DojiStar self.df1['CDLDOJISTAR'] = ta.CDLDOJISTAR(self.df1['open'].values,self.df1['high'].values,self.df1['low'].values, self.df1['close'].values) # Stoch fast self.df1['fastk'], self.df1['fastd'] = ta.STOCHF(self.df1.high.values, self.df1.low.values, self.df1.close.values) # Inverse Fisher transform on RSI, values [-1.0, 1.0] (https://goo.gl/2JGGoy) rsi = 0.1 * (self.df1['rsi'] - 50) self.df1['fisher_rsi'] =(np.exp(2 * rsi) - 1) / (np.exp(2 * rsi) + 1) # EMA - Exponential Moving Average self.df1['ema5'] = ta.EMA(self.df1.close.values, timeperiod=5) self.df1['ema10'] = ta.EMA(self.df1.close.values, timeperiod=10) self.df1['ema50'] = ta.EMA(self.df1.close.values, timeperiod=50) self.df1['ema100'] = ta.EMA(self.df1.close.values, timeperiod=100) # SMA - Simple Moving Average self.df1['sma'] = ta.SMA(self.df1.close.values, timeperiod=40) #----------------------------------------------------------------------- self.df1['Sellsignal'] = 0 self.df1['Buysignal'] = 0 #---------------------example 1 strategy buy and sell ---------------------------------------- #-------------Buy conditions---------------------------------------------------------- """ self.df1.loc[((( (self.df1['macd'] > self.df1['macdsignal']) & (self.df1['cci'] <= -50.0)))),'BuySignal'] = 1 """ #-------------Sell conditions---------------------------------------------------------- """ self.df1.loc[((( (self.df1['macd'] < self.df1['macdsignal']) & (self.df1['cci'] >= 100.0)))),'SellSignal'] = -1 """ #------------------------example 2 strategy buy and sell--------------------------------------- #-------------Buy conditions---------------------------------------------------------- """ self.df1.loc[((( (self.df1['adx'] > 25) & (self.df1['mom'] < 0) & (self.df1['minus_di'] > 25) & (self.df1['plus_di'] < self.df1['minus_di'])))),'BuySignal'] = 1 """ #-------------Sell conditions---------------------------------------------------------- """ self.df1.loc[((( (self.df1['adx'] > 25) & (self.df1['mom'] > 0) & (self.df1['minus_di'] > 25) & (self.df1['plus_di'] > self.df1['minus_di'])))),'SellSignal'] = -1 """ # -------------------------------------------------------------------------- #example 3 strategy macd and midprice with qtpylib Sell & Buy #-------------Sell conditions---------------------------------------------------------- self.df1.loc[((( self.qt.crossed_below(self.df1['macd'], self.df1['macdsignal'])))), 'Sellsignal'] = -1 #-------------Buy conditions---------------------------------------------------------- self.df1.loc[((( self.qt.crossed_above(self.df1['macd'], self.df1['macdsignal'])) & (self.df1['close'] < self.df1['PrezzoMed']))), 'Buysignal'] = 1 # -------------------------------------------------------------------------- #example 4 strategy Bollinger Bands with rsi #-------------Buy conditions---------------------------------------------------------- """ self.df1.loc[ ((self.df1['close'] < self.df1['lower']) & (self.df1['rsi'] < 30) ),'Buysignal'] = 1 #-------------Sell conditions---------------------------------------------------------- self.df1.loc[ ((self.df1['close']>self.df1['upper']) | (self.df1['rsi'] > 70) ),'Sellsignal'] = -1 """ #--------------------------------------------------------------------------- #example 5 Bollinger Bands with rsi qtpylib library Sell & Buy #-------------Buy conditions---------------------------------------------------------- """ self.df1.loc[ ( (self.df1['rsi'] < 30) & (self.df1['close'] < self.df1['lower']) ), 'Buysignal'] = 1 #------------Sell conditions-------------------------------------------- self.df1.loc[ ( (self.df1['rsi'] > 70) ), 'Sellsignal'] = -1 """ # -------------------------------------------------------------------------- #example 6 strategy longma and shortma with qtpylib Sell & Buy #-------------Sell conditions---------------------------------------------------------- """ self.df1.loc[((( self.qt.crossed_below(self.df1['shortma'], self.df1['longma'])))), 'Sellsignal'] = -1 #-------------Buy and Sell conditions---------------------------------------------------------- self.df1.loc[((( self.qt.crossed_above(self.df1['shortma'], self.df1['longma'])) & (self.df1['close'] < self.df1['PrezzoMed']))), 'Buysignal'] = 1 """ #-------------------------------------------------------------------------- #example 7 strategy with qtpylib and TA-lib Sell & Buy #-------------Buy conditions-------------------------------- """ self.df1.loc[ ( (self.df1['rsi'] < 28) & (self.df1['rsi'] > 0) & (self.df1['close'] < self.df1['sma']) & (self.df1['fisher_rsi'] < -0.94) & (self.df1['mfi'] < 16.0) & ( (self.df1['ema50'] > self.df1['ema100']) | (qt.crossed_above(self.df1['ema5'], self.df1['ema10'])) ) & (self.df1['fastd'] > self.df1['fastk']) & (self.df1['fastd'] > 0) ), 'Buysignal'] = 1 #------------Sell conditions--------------------------------------------- self.df1.loc[ ( (self.df1['sar'] > self.df1['close']) & (self.df1['fisher_rsi'] > 0.3) ), 'Sellsignal'] = -1 """ # ---------------------------------------------------------------------- #example 8 strategy - multiple indicators with pattern indicator HAMMER #------------------Sell conditions-------------------------------------- """ self.df1.loc[ ( (self.df1['rsi'] < 30) & (self.df1['slowk'] < 20) & (self.df1['lower'] > self.df1['close']) & (self.df1['CDLHAMMER'] == 100) ), 'Buysignal'] = 1 #---------------Buy conditions------------------------------------------ self.df1.loc[ ( (self.df1['sar'] > self.df1['close']) & (self.df1['fisher_rsi'] > 0.3) ), 'Sellsignal'] = -1 """ # ---------------------------------------------------------------------- #example 9 strategy pattern strategy ENGULFING strategy Sell and Buy #---------------Sell conditions------------------------------------------ """ print(self.df1['CDLENGULFING'].values) self.df1.loc[ ( (self.df1['CDLENGULFING'].values < -99) ), 'Buysignal'] = 1 #---------------Buy conditions------------------------------------------ self.df1.loc[ ( (self.df1['CDLENGULFING'].values > 99) ), 'Sellsignal'] = -1 """ #--------------------------------------------------------------------------------- #example 10 strategy Bollinger Bands with rsi with technical indicators Sell & Buy """risultati_index_buy = self.df1.index[self.df1['CDLINVERTEDHAMMER'] == 100].tolist() risultato_last_index = self.df1.index[-1] if ((risultati_index_buy == None) or (risultato_last_index == None) or (risultato_last_index == '') or (len(risultati_index_buy) == 0)): print('None Result') else: risultato_last_index = str(risultati_index_buy[-1]) risultato_last_index = risultato_last_index[:-3] risultato_last_index = (str(risultato_last_index))[:-3] #rimozione dei tre caratteri data1 = datetime.fromtimestamp(int(risultato_last_index)) data2 = datetime.fromtimestamp(int(risultato_last_index)) print(data2,data1) print(self.df1) #------------------Buy conditions---------------------------------- self.df1.loc[( self.df1['CDLINVERTEDHAMMER'] == 100 ),'CDLHIKKAKE_CLOSE'] = self.df1['close'] self.df1.loc[ ( (self.df1['close'] < self.df1['lower3']) ) ,'Buysignal'] = 1 #------------------Sell conditions---------------------------------- self.df1.loc[ ( self.qt.crossed_above(self.df1['dema20'], self.df1['dema50']) ),'Sellsignal'] = -1 """ #---------------------------------------------------------------------- #example 11 strategy DOJISTAR strategy Sell and Buy #---------------Buy conditions------------------------------------------ """ self.df1.loc[ ( (self.df1['CDLDOJISTAR'].values == -100) ), 'Buysignal'] = 1 #---------------Sell conditions---------------------------------------- self.df1.loc[ ( (self.df1['CDLHIKKAKE'].values == 200) ), 'Sellsignal'] = -1 """ #----------------------------------------------------------------------- #example 12 strategy DEMA of EMA BuySignal and SellSignal #---------------Buy conditions------------------------------------------ """ self.df1.loc[((( self.qt.crossed_below(self.df1['ema50'], self.df1['dema200'])))), 'BuySignal'] = 1 #---------------Sell conditions------------------------------------------ self.df1.loc[ ( (self.df1['CDLHIKKAKE'].values > 99) ), 'Sellsignal'] = -1 """ #---------------------------trailing stoploss--------------------------- #example 1 #tool.stoploss_dinamico_formula = "row.close * tool.stoploss_dinamico_moltiplicatore" #formula for calculating dynamic stoploss (trailing stop) #example 2 tool.stoploss_dinamico_formula = "row.ema3" x = [] y = [] balance = [] lower_vect = [] lower2_vect = [] upper_vect = [] upper2_vect = [] pattern_vect = [] close_vect = [] buysignal_vect = [] sellsignal_vect = [] prezzmed_vect = [] stdev_vect = [] stoplosssignal_vect = [] stoplossprezzo_vect = [] ema_vect = [] ema_long_vect = [] ema_short_vect = [] date = [] volume_vect = [] macd_vect = [] macd_signal_vect = [] macd_hist_vect = [] atr_vect = [] rsi_vect = [] i = 0 for row in self.df1.itertuples(): a = row.Index / 1000.0 b = datetime.fromtimestamp(a) self.stoploss = self.getStoploss(row, i, tool) logging.info("-----------Loop line processing " + str(i)) logging.info("1) self.stoploss value = " + str(self.stoploss)) if (i > 0): stoplossprezzo_vect.append(self.stoplossprezzo) logging.info( "2) Value of i greater than zero not first loop for i =" + str(i)) logging.info("2.1) Value of self.stoplossprezzo = " + str(self.stoplossprezzo)) else: self.stoplossprezzo = row.close * 0.99 logging.info( "2) Value of i equal to zero first loop for i = " + str(i)) stoplossprezzo_vect.append(self.stoplossprezzo) logging.info("2.1) Value of self.stoplossprezzo = " + str(self.stoplossprezzo)) if (self.stoploss == 1): logging.info( "3) self.stoploss value = 1 after getstoploss method ") x.append(i) y.append(row.close) if (row.Sellsignal == 0 and self.stoploss == 0) or (row.Sellsignal == 1 and self.stoploss == 1): logging.info("4) Value of self.stoploss before If for sell " + str(self.stoploss)) logging.info("4.1) Value of row.Sellsignal " + str(row.Sellsignal)) sellsignal_vect.append(np.nan) stoplosssignal_vect.append(np.nan) else: if (self.stoploss == 1): logging.info("5) self.stoploss value = 1 else before if ") logging.info( "5.1) Indication of sell in presence of self.stoploss = 1" ) if (self.sell == 0) and (self.buy == 1): logging.info( "5.2) Sell with self.stoploss = 1 self.stoploss = " + str(self.stoploss)) logging.info( "5.2.1) Sell with self.stoploss = 1 self.sell = " + str(self.sell)) logging.info( "5.2.2) Sell with self.stoploss = 1 self.buy = " + str(self.buy)) #increases variable by 1 num_of_trades by one self.nr_of_trades = self.nr_of_trades+1 sellsignal_vect.append(row.close) stoplosssignal_vect.append(row.close) percentualecommissioni = ( float(row.close) / 100) * float(tool.commissioni) logging.info( "5.3) Percentage of fees in presence of self.stoploss = 1" + str(percentualecommissioni)) balance.append( [row.close - (percentualecommissioni), 1]) if ((row.close - percentualecommissioni) > self.lastbuy): self.nr_positive_trades = self.nr_positive_trades +1 elif ((row.close - percentualecommissioni) < self.lastbuy): self.nr_negative_trades = self.nr_negative_trades +1 else: print('Non risulta positiva ne negativa') self.totalecommissioni = self.totalecommissioni + percentualecommissioni logging.info( "5.4) Total fees in presence of self.stoploss = 1 " + str(self.totalecommissioni)) self.sell = 1 self.buy = 0 self.stoploss = 0 logging.info( "5.5) Assign value zero to self.stoploss = " + str(self.stoploss)) logging.info("5.6) Assign value 1 to self.sell = " + str(self.sell)) logging.info("5.7) Assign value zero to self.buy = " + str(self.buy)) else: sellsignal_vect.append(np.nan) stoplosssignal_vect.append(np.nan) self.stoploss = 0 else: stoplosssignal_vect.append(np.nan) if ((self.sell == 0) and (self.buy == 1) and (tool.attivazione_stoploss_dinamico == 0)): logging.info( "6.0) Sell normal not in the presence of dynamic stoploss" ) logging.info("6.1) Value of self.sell: " + str(self.sell)) logging.info("6.2) Value of self.buy: " + str(self.buy)) logging.info( "6.3) Dynamic stoploss activation parameter value: " + str(tool.attivazione_stoploss_dinamico)) price1 = float(self.lastbuy) + ( (float(self.lastbuy)) / 100) * float(tool.profitto) logging.info("6.4) Value of self.lastbuy: " + str(self.lastbuy)) logging.info("6.5) Price1 price of sell: " + str(price1)) logging.info("6.6) Profit parameters: " + str(tool.profitto)) if (float(row.close) > float(price1)): logging.info( "6.7) Sell in presence of row.close greater than value of price1" ) logging.info("6.8) Value of row.close: " + str(row.close)) logging.info("6.9) Value of sell price: " + str(price1)) #increases variable by 1 num_of_trades by one self.nr_positive_trades = self.nr_positive_trades +1 sellsignal_vect.append(row.close) percentualecommissioni = (float( row.close) / 100) * float(tool.commissioni) logging.info( "6.9.1) Percentage of fees in presence of self.stoploss = 1 " + str(percentualecommissioni)) balance.append( [row.close - (percentualecommissioni), 1]) self.totalecommissioni = self.totalecommissioni + percentualecommissioni logging.info( "6.9.2) Total of fees in presence of self.stoploss = 1" + str(self.totalecommissioni)) self.sell = 1 self.buy = 0 self.stoploss = 0 logging.info( "6.9.3) Assign value zero to self.stoploss = " + str(self.stoploss)) logging.info( "6.9.4) Assign value 1 to self.sell = " + str(self.sell)) logging.info( "6.9.5) Assign value 0 to self.buy = " + str(self.buy)) else: sellsignal_vect.append(np.nan) else: sellsignal_vect.append(np.nan) if ((row.Buysignal == 0 or row.Buysignal == '0')): logging.info( "7) Value of self.stoploss in if row.BuySignal = 0 " + str(self.stoploss)) logging.info("7.1) Value of row.Buysignal " + str(row.Buysignal)) buysignal_vect.append(np.nan) else: if ((row.Buysignal == 1 or row.Buysignal == '1')): logging.info("8) Value of row.Buysignal " + str(row.Buysignal)) if (self.buy == '0' or self.buy == 0): logging.info( "8.1) Buy in presence of self.stoploss = " + str(self.stoploss)) logging.info("8.2) Value of self.sell = " + str(self.sell)) logging.info("8.3) Value of self.buy = " + str(self.buy)) buysignal_vect.append(row.close) percentualecommissioni = ( float(row.close) / 100) * float(tool.commissioni) logging.info( "8.4) Percentage of fees in presence of self.stoploss = 1 " + str(percentualecommissioni)) self.totalecommissioni = self.totalecommissioni + percentualecommissioni logging.info( "8.5) Total of fees in presence of stoploss = 1" + str(self.totalecommissioni)) balance.append([(-row.close - percentualecommissioni), 0]) self.buy = 1 self.sell = 0 logging.info( "8.5.1) Assign value zero to self.stoploss = " + str(self.stoploss)) logging.info( "8.5.2) Assign value zero to self.sell = " + str(self.sell)) logging.info("8.5.3) Assign value 1 to self.buy = " + str(self.buy)) if (tool.attivazione_stoploss_dinamico == 1): logging.info( "8.6) Value of tool.attivazione_stoploss_dinamico equal to : " + str(tool.attivazione_stoploss_dinamico)) self.stoplossprezzo = eval( tool.stoploss_dinamico_formula) logging.info( "8.6.1) Value of self.stoplossprezzo " + str(self.stoplossprezzo)) else: self.stoplossprezzo = (row.close - ( (row.close / 100) * tool.stoploss_1)) logging.info( "8.7) Value of self.stoplossprezzo with tool.attivazione_stoploss_dinamico equal to 1 = " + str(self.stoplossprezzo)) self.lastbuy = row.close logging.info("8.8) Value of self.lastbuy" + str(self.lastbuy)) logging.info("8.9.0) Value of self.stoploss = " + str(self.stoploss)) logging.info("8.9.1) Value of self.sell = " + str(self.sell)) logging.info("8.9.2) Value of self.buy = " + str(self.buy)) logging.info("8.9.3) Value of self.stoplossprezzo = " + str(self.stoplossprezzo)) logging.info("8.9.4) Value of self.lastbuy = " + str(self.lastbuy)) logging.info( "8.9.5) Value of tool.attivazione_stoploss_dinamico = " + str(tool.attivazione_stoploss_dinamico)) logging.info( "8.9.6) Value of tool.attivazione_stoploss_statico = " + str(tool.attivazione_stoploss_statico)) else: buysignal_vect.append(np.nan) else: buysignal_vect.append(np.nan) #add indicators,oscillators and others prezzmed_vect.append(row.PrezzoMed) stdev_vect.append(row.STDDEV) ema_vect.append(row.ema3) date.append(b) rsi_vect.append(row.rsi) #pattern_vect.append(row.CDLHIKKAKE_CLOSE) volume_vect.append(row.volume) lower2_vect.append(row.lower2) upper2_vect.append(row.upper2) ema_long_vect.append(row.tema50) ema_short_vect.append(row.tema20) lower_vect.append(row.lower) upper_vect.append(row.upper) macd_vect.append(row.macd) macd_signal_vect.append(row.macdsignal) macd_hist_vect.append(row.macdhist) atr_vect.append(row.atr) i = i + 1 self.valorestrategia = self.getValoreStrategia(balance) tool.setVisualizzaGrafico(1) if (tool.visualizzagrafico == 1 or tool.visualizzagrafico == '1'): ds = draw.Draw() ds.setNrGrafici(2) ds.draw_graphic(moneta, x, y, self.nr_of_trades, self.nr_positive_trades,self.nr_negative_trades, buysignal_vect, sellsignal_vect, prezzmed_vect, stoplossprezzo_vect, stdev_vect, self.nome, self.valorestrategia, date, ema_vect, rsi_vect,pattern_vect,volume_vect,lower2_vect, upper2_vect,ema_short_vect,ema_long_vect,lower_vect,upper_vect,macd_vect,macd_signal_vect,macd_hist_vect,atr_vect)
def extract_by_type(self, feature_type, open_prices=None, close_prices=None, high_prices=None, low_prices=None): if feature_type == 'ROCP': rocp = talib.ROCP(close_prices, timeperiod=1) self.feature.append(rocp) if feature_type == 'OROCP': orocp = talib.ROCP(open_prices, timeperiod=1) self.feature.append(orocp) if feature_type == 'HROCP': hrocp = talib.ROCP(high_prices, timeperiod=1) self.feature.append(hrocp) if feature_type == 'LROCP': lrocp = talib.ROCP(low_prices, timeperiod=1) self.feature.append(lrocp) if feature_type == 'MACD': macd, signal, hist = talib.MACD(close_prices, fastperiod=12, slowperiod=26, signalperiod=9) norm_macd = numpy.nan_to_num(macd) / math.sqrt( numpy.var(numpy.nan_to_num(macd))) norm_signal = numpy.nan_to_num(signal) / math.sqrt( numpy.var(numpy.nan_to_num(signal))) norm_hist = numpy.nan_to_num(hist) / math.sqrt( numpy.var(numpy.nan_to_num(hist))) macdrocp = talib.ROCP(norm_macd + numpy.max(norm_macd) - numpy.min(norm_macd), timeperiod=1) signalrocp = talib.ROCP(norm_signal + numpy.max(norm_signal) - numpy.min(norm_signal), timeperiod=1) histrocp = talib.ROCP(norm_hist + numpy.max(norm_hist) - numpy.min(norm_hist), timeperiod=1) # self.feature.append(macd / 100.0) # self.feature.append(signal / 100.0) # self.feature.append(hist / 100.0) self.feature.append(norm_macd) self.feature.append(norm_signal) self.feature.append(norm_hist) self.feature.append(macdrocp) self.feature.append(signalrocp) self.feature.append(histrocp) if feature_type == 'RSI': rsi6 = talib.RSI(close_prices, timeperiod=6) rsi12 = talib.RSI(close_prices, timeperiod=12) rsi24 = talib.RSI(close_prices, timeperiod=24) rsi6rocp = talib.ROCP(rsi6 + 100., timeperiod=1) rsi12rocp = talib.ROCP(rsi12 + 100., timeperiod=1) rsi24rocp = talib.ROCP(rsi24 + 100., timeperiod=1) self.feature.append(rsi6 / 100.0 - 0.5) self.feature.append(rsi12 / 100.0 - 0.5) self.feature.append(rsi24 / 100.0 - 0.5) # self.feature.append(numpy.maximum(rsi6 / 100.0 - 0.8, 0)) # self.feature.append(numpy.maximum(rsi12 / 100.0 - 0.8, 0)) # self.feature.append(numpy.maximum(rsi24 / 100.0 - 0.8, 0)) # self.feature.append(numpy.minimum(rsi6 / 100.0 - 0.2, 0)) # self.feature.append(numpy.minimum(rsi6 / 100.0 - 0.2, 0)) # self.feature.append(numpy.minimum(rsi6 / 100.0 - 0.2, 0)) # self.feature.append(numpy.maximum(numpy.minimum(rsi6 / 100.0 - 0.5, 0.3), -0.3)) # self.feature.append(numpy.maximum(numpy.minimum(rsi6 / 100.0 - 0.5, 0.3), -0.3)) # self.feature.append(numpy.maximum(numpy.minimum(rsi6 / 100.0 - 0.5, 0.3), -0.3)) self.feature.append(rsi6rocp) self.feature.append(rsi12rocp) self.feature.append(rsi24rocp) if feature_type == 'UO': ult_osc = talib.ULTOSC(high_prices, low_prices, close_prices, timeperiod1=7, timeperiod2=14, timeperiod3=28) self.feature.append(ult_osc / 100.0 - 0.5) if feature_type == 'BOLL': upperband, middleband, lowerband = talib.BBANDS(close_prices, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0) self.feature.append((upperband - close_prices) / close_prices) self.feature.append((middleband - close_prices) / close_prices) self.feature.append((lowerband - close_prices) / close_prices) if feature_type == 'MA': ma5 = talib.MA(close_prices, timeperiod=5) ma10 = talib.MA(close_prices, timeperiod=10) ma20 = talib.MA(close_prices, timeperiod=20) ma30 = talib.MA(close_prices, timeperiod=30) ma60 = talib.MA(close_prices, timeperiod=60) ma90 = talib.MA(close_prices, timeperiod=90) ma120 = talib.MA(close_prices, timeperiod=120) ma180 = talib.MA(close_prices, timeperiod=180) #ma360 = talib.MA(close_prices, timeperiod=360) #ma720 = talib.MA(close_prices, timeperiod=720) ma5rocp = talib.ROCP(ma5, timeperiod=1) ma10rocp = talib.ROCP(ma10, timeperiod=1) ma20rocp = talib.ROCP(ma20, timeperiod=1) ma30rocp = talib.ROCP(ma30, timeperiod=1) ma60rocp = talib.ROCP(ma60, timeperiod=1) ma90rocp = talib.ROCP(ma90, timeperiod=1) ma120rocp = talib.ROCP(ma120, timeperiod=1) ma180rocp = talib.ROCP(ma180, timeperiod=1) #ma360rocp = talib.ROCP(ma360, timeperiod=1) #ma720rocp = talib.ROCP(ma720, timeperiod=1) self.feature.append(ma5rocp) self.feature.append(ma10rocp) self.feature.append(ma20rocp) self.feature.append(ma30rocp) self.feature.append(ma60rocp) self.feature.append(ma90rocp) self.feature.append(ma120rocp) self.feature.append(ma180rocp) #self.feature.append(ma360rocp) #self.feature.append(ma720rocp) self.feature.append((ma5 - close_prices) / close_prices) self.feature.append((ma10 - close_prices) / close_prices) self.feature.append((ma20 - close_prices) / close_prices) self.feature.append((ma30 - close_prices) / close_prices) self.feature.append((ma60 - close_prices) / close_prices) self.feature.append((ma90 - close_prices) / close_prices) self.feature.append((ma120 - close_prices) / close_prices) self.feature.append((ma180 - close_prices) / close_prices) #self.feature.append((ma360 - close_prices) / close_prices) #self.feature.append((ma720 - close_prices) / close_prices) if feature_type == 'STOCH': slow_stoch_k, slow_stoch_d = talib.STOCH(high_prices, low_prices, close_prices, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) fast_stoch_k, fast_stoch_d = talib.STOCHF(high_prices, low_prices, close_prices, fastk_period=5, fastd_period=3, fastd_matype=0) fast_rsi_k, fast_rsi_d = talib.STOCHRSI(close_prices, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0) self.feature.append(slow_stoch_k / 100.0 - 0.5) self.feature.append(slow_stoch_d / 100.0 - 0.5) self.feature.append(fast_stoch_k / 100.0 - 0.5) self.feature.append(fast_stoch_d / 100.0 - 0.5) self.feature.append(fast_rsi_k / 100.0 - 0.5) self.feature.append(fast_rsi_d / 100.0 - 0.5) if feature_type == 'AO': median_price = (high_prices + low_prices) / 2 ao = talib.SMA(median_price, 5) - talib.SMA(median_price, 34) self.feature.append(ao) return self.feature