def test_MINUS_DM(self): class MyMINUS_DM(OperatorMINUS_DM): def __init__(self, name, **kwargs): super(MyMINUS_DM, self).__init__(100, name, **kwargs) self.env.add_operator('minus_dm', { 'operator': MyMINUS_DM, }) string = 'minus_dm(14, high, low, close)' gene = self.env.parse_string(string) self.assertRaises(IndexError, gene.eval, self.env, self.dates[98], self.dates[-1]) df = gene.eval(self.env, self.dates[99], self.dates[100]) ser0, ser1 = df.iloc[0], df.iloc[1] h = self.env.get_data_value('high').values l = self.env.get_data_value('low').values res0, res1, res = [], [], [] for i, val in ser0.iteritems(): res0.append( talib.MINUS_DM(h[:100, i], l[:100, i], timeperiod=14)[-1] == val) for i, val in ser1.iteritems(): res0.append( talib.MINUS_DM(h[1:100 + 1, i], l[1:100 + 1, i], timeperiod=14)[-1] == val) res.append( talib.MINUS_DM(h[:100 + 1, i], l[:100 + 1, i], timeperiod=14)[-1] != val) self.assertTrue(all(res0) and all(res1) and any(res))
def calculateMOM(dataset): timeperiod = 14 dataset.loc[:,'mom_adx'] = talib.ADX(dataset['high'].values, dataset['low'].values, dataset['close'].values, timeperiod=timeperiod) dataset.loc[:,'mom_adxr'] = talib.ADXR(dataset['high'].values, dataset['low'].values, dataset['close'].values, timeperiod=timeperiod) dataset.loc[:,'mom_mdi'] = talib.MINUS_DI(dataset['high'].values, dataset['low'].values, dataset['close'].values, timeperiod=timeperiod) dataset.loc[:,'mom_mdm'] = talib.MINUS_DM(dataset['high'].values, dataset['low'].values, timeperiod=timeperiod) dataset.loc[:,'mom_pdi'] = talib.MINUS_DI(dataset['high'].values, dataset['low'].values, dataset['close'].values, timeperiod=timeperiod) dataset.loc[:,'mom_pdm'] = talib.MINUS_DM(dataset['high'].values, dataset['low'].values, timeperiod=timeperiod) return dataset
def test_dm(self): result = pandas_ta.dm(self.high, self.low) self.assertIsInstance(result, DataFrame) self.assertEqual(result.name, "DM_14") try: expected_pos = tal.PLUS_DM(self.high, self.low) expected_neg = tal.MINUS_DM(self.high, self.low) expecteddf = DataFrame({ "DMP_14": expected_pos, "DMN_14": expected_neg }) pdt.assert_frame_equal(result, expecteddf) except AssertionError as ae: try: dmp = pandas_ta.utils.df_error_analysis(result.iloc[:, 0], expecteddf.iloc[:, 0], col=CORRELATION) self.assertGreater(dmp, CORRELATION_THRESHOLD) except Exception as ex: error_analysis(result, CORRELATION, ex) try: dmn = pandas_ta.utils.df_error_analysis(result.iloc[:, 1], expecteddf.iloc[:, 1], col=CORRELATION) self.assertGreater(dmn, CORRELATION_THRESHOLD) except Exception as ex: error_analysis(result, CORRELATION, ex)
def compMINUSDM(self): md = talib.MINUS_DM(self.high,self.low,timeperiod=self.lookback) self.removeNullID(md) self.rawFeatures['MINUS_DM'] = md FEATURE_SIZE_DICT['MINUS_DM'] = 1 return
def safezonestop(candles: np.ndarray, period: int = 22, mult: float = 2.5, max_lookback: int = 3, direction: str = "long", sequential: bool = False) -> Union[float, np.ndarray]: """ Safezone Stops :param candles: np.ndarray :param period: int - default=22 :param mult: float - default=2.5 :param max_lookback: int - default=3 :param direction: str - default=long :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:] high = candles[:, 3] low = candles[:, 4] last_high = np_shift(high, 1, fill_value=np.nan) last_low = np_shift(low, 1, fill_value=np.nan) if direction == "long": res = last_low - mult * talib.MINUS_DM(high, low, timeperiod=period) swv = sliding_window_view(res, window_shape=max_lookback) res = np.max(swv, axis=-1) else: res = last_high + mult * talib.PLUS_DM(high, low, timeperiod=period) swv = sliding_window_view(res, window_shape=max_lookback) res = np.min(swv, axis=-1) return np.concatenate((np.full((candles.shape[0] - res.shape[0]), np.nan), res), axis=0) if sequential else res[-1]
def getMomentumIndicators(df): high = df['High'] low = df['Low'] close = df['Close'] open = df['Open'] volume = df['Volume'] df['ADX'] = ta.ADX(high, low, close, timeperiod=14) df['SMA'] = ta.ADXR(high, low, close, timeperiod=14) df['APO'] = ta.APO(close, fastperiod=12, slowperiod=26, matype=0) df['AROONDOWN'], df['AROOONUP'] = ta.AROON(high, low, timeperiod=14) df['AROONOSC'] = ta.AROONOSC(high, low, timeperiod=14) df['BOP'] = ta.BOP(open, high, low, close) df['CCI'] = ta.CCI(high, low, close, timeperiod=14) df['CMO'] = ta.CMO(close, timeperiod=14) df['DX'] = ta.DX(high, low, close, timeperiod=14) df['MACD'], df['MACDSIGNAL'], df['MACDHIST'] = ta.MACD(close, fastperiod=12, slowperiod=26, signalperiod=9) df['MFI'] = ta.MFI(high, low, close, volume, timeperiod=14) df['MINUS_DI'] = ta.MINUS_DI(high, low, close, timeperiod=14) df['MINUS_DM']= ta.MINUS_DM(high, low, timeperiod=14) df['MOM'] = ta.MOM(close, timeperiod=10) df['PLUS_DM'] =ta.PLUS_DM(high, low, timeperiod=14) df['PPO'] = ta.PPO(close, fastperiod=12, slowperiod=26, matype=0) df['ROC'] = ta.ROC(close, timeperiod=10) df['ROCP'] = ta.ROCP(close, timeperiod=10) df['ROCR'] = ta.ROCR(close, timeperiod=10) df['ROCR100'] = ta.ROCR100(close, timeperiod=10) df['RSI'] = ta.RSI(close, timeperiod=14) df['SLOWK'], df['SLOWD'] = ta.STOCH(high, low, close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) df['FASTK'], df['FASTD'] = ta.STOCHF(high, low, close, fastk_period=5, fastd_period=3, fastd_matype=0) df['FASTK2'], df['FASTD2'] = ta.STOCHRSI(close, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0) df['TRIX'] = ta.TRIX(close, timeperiod=30) df['ULTOSC'] = ta.ULTOSC(high, low, close, timeperiod1=7, timeperiod2=14, timeperiod3=28) df['WILLR'] = ta.WILLR(high, low, close, timeperiod=14)
def AverageDirectionalIndex(self, timeperiod=14): ''' Average Direction Movement Index (ADX) ADX is used to determine the stength of a trend. If -DI is above the +DX, down trend If -DI is below the +DX, up trend ADX below 20, price is trendless ADX above 20, price is trending Parameters ---------- timeperiod : TYPE, optional DESCRIPTION. The default is 14. Returns ------- TYPE DESCRIPTION. ''' dmi = pd.DataFrame() # Need to figure out if it should be PLUS_DM, MINUS_DM, MINUS_DI, PLUS_DI, Directional Movement Index or Average Directional Movement Index dmi['+di'] = ta.PLUS_DM(self.data.high, self.data.low, timeperiod) dmi['-di'] = ta.MINUS_DM(self.data.high, self.data.low, timeperiod) dmi['dmi'] = ta.DX(self.data.high, self.data.low, self.data.close, timeperiod) return dmi
def checkOne(code_str): df = base.getOneStockData(code_str) df['MINUS_DM_' + str(adx_timeperiod)] = ta.MINUS_DM( np.array(df['high']), np.array(df['low']), timeperiod=adx_timeperiod) df['PLUS_DM_' + str(adx_timeperiod)] = ta.PLUS_DM( np.array(df['high']), np.array(df['low']), timeperiod=adx_timeperiod) df['TR_' + str(adx_timeperiod)] = ta.TRANGE(np.array(df['high']), np.array(df['low']), np.array(df['close'])) df['MINUS_DI_' + str(adx_timeperiod)] = ta.MINUS_DI( np.array(df['high']), np.array(df['low']), np.array(df['close']), timeperiod=adx_timeperiod) df['PLUS_DI_' + str(adx_timeperiod)] = ta.PLUS_DI( np.array(df['high']), np.array(df['low']), np.array(df['close']), timeperiod=adx_timeperiod) df['ADX_' + str(adx_timeperiod)] = ta.ADX(np.array(df['high']), np.array(df['low']), np.array(df['close']), timeperiod=adx_timeperiod) df['ADXR_' + str(adx_timeperiod)] = ta.ADXR(np.array(df['high']), np.array(df['low']), np.array(df['close']), timeperiod=adx_timeperiod) df.to_csv(ADX_DIR + code_str + '.csv')
def momentum(self): adx = talib.ADX(self.high,self.low,self.close,self.period) adxr = talib.ADXR(self.high,self.low,self.close,self.period) apo = talib.APO(self.high,self.low,self.close,self.period) aroondown, aroonup = talib.AROON(self.high, self.low, period) aroonosc = talib.AROONOSC(self.high,self.low,self.period) bop = talib.BOP(self.opens,self.high,self.low,self.close) cci = talib.CCI(self.high,self.low,self.close,self.period) cmo = talib.CMO(self.close,self.period) dx = talib.DX(self.high,self.low,self.close,self.period) macd, macdsignal, macdhist = talib.MACD(self.close, fastperiod=period, slowperiod=period*5, signalperiod=period*2) macd1, macdsignal1, macdhist1 = talib.MACDEXT(self.close, fastperiod=12, fastmatype=0, slowperiod=26, slowmatype=0, signalperiod=9, signalmatype=0) macd2, macdsignal2, macdhist2 = talib.MACDFIX(self.close, signalperiod=9) mfi = talib.MFI(self.high, self.low, self.close, self.volume, timeperiod=14) minus_di = talib.MINUS_DI(self.high, self.low, self.close, timeperiod=14) minus_dm = talib.MINUS_DM(self.high, self.low, timeperiod=14) mom = talib.MOM(self.close, timeperiod=10) plus_di = talib.PLUS_DI(self.high, self.low, self.close, timeperiod=14) plus_dm = talib.PLUS_DM(self.high, self.low, timeperiod=14) ppo = talib.PPO(self.close, fastperiod=12, slowperiod=26, matype=0) roc = talib.ROC(self.close, timeperiod=10) rocp = talib.ROCP(self.close, timeperiod=10) rocr = talib.ROCR(self.close, timeperiod=10) rocr100 = talib.ROCR100(self.close, timeperiod=10) rsi = talib.RSI(self.close, timeperiod=14) slowk, slowd = talib.STOCH(self.high, self.low, self.close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) fastk, fastd = talib.STOCHF(self.high, self.low, self.close, fastk_period=5, fastd_period=3, fastd_matype=0) fastk1, fastd1 = talib.STOCHRSI(self.close, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0) trix = talib.TRIX(self.close, timeperiod=30) ultosc = talib.ULTOSC(self.high, self.low, self.close, timeperiod1=7, timeperiod2=14, timeperiod3=28) willr = talib.WILLR(self.high, self.low, self.close, timeperiod=14)
def safezonestop(candles: np.ndarray, period: int = 22, mult: float = 2.5, max_lookback: int = 3, direction: str = "long", sequential: bool = False) -> Union[float, np.ndarray]: """ Safezone Stops :param candles: np.ndarray :param period: int - default: 22 :param mult: float - default: 2.5 :param max_lookback: int - default: 3 :param direction: str - default: long :param sequential: bool - default: False :return: float | np.ndarray """ candles = slice_candles(candles, sequential) high = candles[:, 3] low = candles[:, 4] last_high = np_shift(high, 1, fill_value=np.nan) last_low = np_shift(low, 1, fill_value=np.nan) if direction == "long": res = talib.MAX(last_low - mult * talib.MINUS_DM(high, low, timeperiod=period), max_lookback) else: res = talib.MIN(last_high + mult * talib.PLUS_DM(high, low, timeperiod=period), max_lookback) return res if sequential else res[-1]
def adxAlert(self, period): closes = [] highs = [] lows = [] for x in self.lastValues: closes.append(float(x[4])) highs.append(float(x[2])) lows.append(float(x[3])) nparraycloses = np.asarray(closes) nparrayhighs = np.asarray(highs) nparraylows = np.asarray(lows) diminus = talib.MINUS_DM(nparrayhighs, nparraylows, timeperiod=14) diplus = talib.PLUS_DM(nparrayhighs, nparraylows, timeperiod=14) adx = talib.ADX(nparrayhighs, nparraylows, nparraycloses, timeperiod=14) if (adx[-1] > 25) and (diplus[-1] > adx[-1]) and ( diplus[-1] > diminus[-1]) and (self.data['adx' + period] == 0): self.data['adx' + period] = 1 return 1, self.getLastPrice() if (adx[-1] > 25) and (diminus[-1] > adx[-1]) and ( diminus[-1] > diplus[-1]) and (self.data['adx' + period] == 0): self.data['adx' + period] = -1 return -1, self.getLastPrice() if adx[-1] < 25: self.data['adx' + period] = 0 return 0, 0
def AverageTrueRangeStopLoss(self, timeperiod=14, multiplier=2): """ Average True Range Is a lagging indicator, used to provide insights into volatility. Parameters ---------- timeperiod : Integer, optional DESCRIPTION. The default is 14. Returns ------- TYPE DESCRIPTION. """ stopLoss = ta.ATR(self.data.high, self.data.low, self.data.close, timeperiod) plus_dm = ta.PLUS_DM(self.data.high, self.data.low, timeperiod) minus_dm = ta.MINUS_DM(self.data.high, self.data.low, timeperiod) if plus_dm > minus_dm: stopLoss = self.data.close - multiplier * stopLoss else: stopLoss = self.data.close + multiplier * stopLoss stopLoss.dropna(inplace=True) return stopLoss
def minus_dm(client, symbol, timeframe="6m", highcol="high", lowcol="low", period=14): """This will return a dataframe of Minus Directional Movement for the given symbol across the given timeframe Args: client (pyEX.Client): Client symbol (string): Ticker timeframe (string): timeframe to use, for pyEX.chart highcol (string): column to use to calculate lowcol (string): column to use to calculate period (int): period to calculate across Returns: DataFrame: result """ df = client.chartDF(symbol, timeframe) x = t.MINUS_DM(df[highcol].values.astype(float), df[lowcol].values.astype(float), period) return pd.DataFrame({ highcol: df[highcol].values, lowcol: df[lowcol].values, "minus_dm": x })
def generate_feature(data): high = data.High.values low = data.Low.values close = data.Close.values feature_df = pd.DataFrame(index=data.index) feature_df["ADX"] = ADX = talib.ADX(high, low, close, timeperiod=14) feature_df["ADXR"] = ADXR = talib.ADXR(high, low, close, timeperiod=14) feature_df["APO"] = APO = talib.APO(close, fastperiod=12, slowperiod=26, matype=0) feature_df["AROONOSC"] = AROONOSC = talib.AROONOSC(high, low, timeperiod=14) feature_df["CCI"] = CCI = talib.CCI(high, low, close, timeperiod=14) feature_df["CMO"] = CMO = talib.CMO(close, timeperiod=14) feature_df["DX"] = DX = talib.DX(high, low, close, timeperiod=14) feature_df["MINUS_DI"] = MINUS_DI = talib.MINUS_DI(high, low, close, timeperiod=14) feature_df["MINUS_DM"] = MINUS_DM = talib.MINUS_DM(high, low, timeperiod=14) feature_df["MOM"] = MOM = talib.MOM(close, timeperiod=10) feature_df["PLUS_DI"] = PLUS_DI = talib.PLUS_DI(high, low, close, timeperiod=14) feature_df["PLUS_DM"] = PLUS_DM = talib.PLUS_DM(high, low, timeperiod=14) feature_df["PPO"] = PPO = talib.PPO(close, fastperiod=12, slowperiod=26, matype=0) feature_df["ROC"] = ROC = talib.ROC(close, timeperiod=10) feature_df["ROCP"] = ROCP = talib.ROCP(close, timeperiod=10) feature_df["ROCR100"] = ROCR100 = talib.ROCR100(close, timeperiod=10) feature_df["RSI"] = RSI = talib.RSI(close, timeperiod=14) feature_df["ULTOSC"] = ULTOSC = talib.ULTOSC(high, low, close, timeperiod1=7, timeperiod2=14, timeperiod3=28) feature_df["WILLR"] = WILLR = talib.WILLR(high, low, close, timeperiod=14) feature_df = feature_df.fillna(0.0) matrix = np.stack(( ADX, ADXR, APO, AROONOSC, CCI, CMO, DX, MINUS_DI, ROCR100, ROC, MINUS_DM, MOM, PLUS_DI, PLUS_DM, PPO, ROCP, WILLR, ULTOSC, RSI)) matrix = np.nan_to_num(matrix) matrix = matrix.transpose() return feature_df, matrix
def minus_dm(self, sym, frequency, *args, **kwargs): if not self.kbars_ready(sym, frequency): return [] highs = self.high(sym, frequency) lows = self.low(sym, frequency) return ta.MINUS_DM(highs, lows, *args, **kwargs)
def MINUS_DM(self, timeperiod=14): real_data = np.array([self.df.high, self.df.low], dtype='f8') minus_dm = talib.MINUS_DM(real_data[0], real_data[1], timeperiod=timeperiod) # return go.Scatter( # x=self.df.index, # y=minus_dm, # name='MINUS_DM' # ) return minus_dm
def minus_dm(self, n, array=False): """ MINUS_DM. """ result = talib.MINUS_DM(self.high, self.low, n) if array: return result return result[-1]
def minus_dm(self, n: int, array: bool = False) -> Union[float, np.ndarray]: """ MINUS_DM. """ result = talib.MINUS_DM(self.high, self.low, n) if array: return result return result[-1]
def generate_feature(data): high = data.High.values low = data.Low.values close = data.Close.values # feature_df = pd.DataFrame(index=data.index) feature_df = data.copy() feature_df["ADX"] = ADX = talib.ADX(high, low, close, timeperiod=14) feature_df["ADXR"] = ADXR = talib.ADXR(high, low, close, timeperiod=14) feature_df["APO"] = APO = talib.APO(close, fastperiod=12, slowperiod=26, matype=0) feature_df["AROONOSC"] = AROONOSC = talib.AROONOSC(high, low, timeperiod=14) feature_df["CCI"] = CCI = talib.CCI(high, low, close, timeperiod=14) feature_df["CMO"] = CMO = talib.CMO(close, timeperiod=14) feature_df["DX"] = DX = talib.DX(high, low, close, timeperiod=14) feature_df["MINUS_DI"] = MINUS_DI = talib.MINUS_DI(high, low, close, timeperiod=14) feature_df["MINUS_DM"] = MINUS_DM = talib.MINUS_DM(high, low, timeperiod=14) feature_df["MOM"] = MOM = talib.MOM(close, timeperiod=10) feature_df["PLUS_DI"] = PLUS_DI = talib.PLUS_DI(high, low, close, timeperiod=14) feature_df["PLUS_DM"] = PLUS_DM = talib.PLUS_DM(high, low, timeperiod=14) feature_df["PPO"] = PPO = talib.PPO(close, fastperiod=12, slowperiod=26, matype=0) feature_df["ROC"] = ROC = talib.ROC(close, timeperiod=10) feature_df["ROCP"] = ROCP = talib.ROCP(close, timeperiod=10) feature_df["ROCR100"] = ROCR100 = talib.ROCR100(close, timeperiod=10) feature_df["RSI"] = RSI = talib.RSI(close, timeperiod=14) feature_df["ULTOSC"] = ULTOSC = talib.ULTOSC(high, low, close, timeperiod1=7, timeperiod2=14, timeperiod3=28) feature_df["WILLR"] = WILLR = talib.WILLR(high, low, close, timeperiod=14) feature_df = feature_df.fillna(0.0) # Exclude columns you don't want feature_df = feature_df[feature_df.columns[ ~feature_df.columns.isin(['Open', 'High', 'Low', 'Close'])]] matrix = feature_df.values return feature_df, matrix
def MINUS_DM(high, low, timeperiod=14): ''' Minus Directional Movement 上升动向值 分组: Momentum Indicator 动量指标 简介: 通过分析股票价格在涨跌过程中买卖双方力量均衡点的变化情况, 即多空双方的力量的变化受价格波动的影响而发生由均衡到失衡的循环过程, 从而提供对趋势判断依据的一种技术指标。 real = MINUS_DM(high, low, timeperiod=14) ''' return talib.MINUS_DM(high, low, timeperiod)
def get_momentum_studies(open, low, high, close, volume, df): # Momentum studies # https://mrjbq7.github.io/ta-lib/func_groups/momentum_indicators.html df['MACD'], df['MACD_SIGN'], df['MACD_HIST'] = talib.MACD( close, fastperiod=12, slowperiod=26, signalperiod=9) df['STOCH-SLOW-K'], df['STOCH-SLOW-D'] = talib.STOCH(high, low, close, fastk_period=5, slowk_period=3, slowk_matype=0, slowd_period=3, slowd_matype=0) df['STOCH-FAST-K'], df['STOCH-FAST-D'] = talib.STOCHF(high, low, close, fastk_period=5, fastd_period=3, fastd_matype=0) df['STOCH-RSI-K'], df['STOCH-RSI-D'] = talib.STOCHRSI(close, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0) df['AROON-DOWN'], df['AROON-UP'] = talib.AROON(high, low, timeperiod=14) df["MINUS_DI"] = talib.MINUS_DI(high, low, close, timeperiod=14) df["MINUS_DM"] = talib.MINUS_DM(high, low, timeperiod=14) df["PLUS_DI"] = talib.PLUS_DI(high, low, close, timeperiod=14) df["PLUS_DM"] = talib.PLUS_DM(high, low, timeperiod=14) df["MOM"] = talib.MOM(close, timeperiod=10) df["MFI"] = talib.MFI(high, low, close, volume, timeperiod=14) 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["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["CMO"] = talib.CMO(close, timeperiod=14) df["DX"] = talib.DX(high, low, close, timeperiod=14) df["PPO"] = talib.PPO(close, fastperiod=12, slowperiod=26, matype=0) df["ROC"] = talib.ROC(close, timeperiod=10) df["RSI"] = talib.RSI(close, timeperiod=14) df["TRIX"] = talib.TRIX(close, timeperiod=30) df["ULT"] = talib.ULTOSC(high, low, close, timeperiod1=7, timeperiod2=14, timeperiod3=28) df["WILLR"] = talib.WILLR(high, low, close, timeperiod=14)
def adx(df): df["adx"] = talib.ADX(df["high"], df["low"], df["close"]) df["dm+"] = talib.PLUS_DM(df["high"], df["low"]) df["dm-"] = talib.MINUS_DM(df["high"], df["low"]) df["dmcut"] = (df["dm+"] > df["dm-"]) != (df["dm+"] > df["dm-"]).shift(1) conditions = [ ((df["dmcut"] == True) & (df["adx"] > 25) & (df["dm+"] > df["dm-"])), ((df["dmcut"] == True) & (df["adx"] > 25) & (df["dm+"] < df["dm-"])) ] df["adx"] = np.select(conditions, [1, -1], default=0) df = df.drop(["dm+", "dm-", "dmcut"], axis=1) return df
def add_MINUS_DM(self, timeperiod=14, type="line", color="decreasing", **kwargs): """Minus Directional Movement.""" if not (self.has_high and self.has_low): raise Exception() utils.kwargs_check(kwargs, VALID_TA_KWARGS) if "kind" in kwargs: type = kwargs["kind"] name = "MINUS_DM({})".format(str(timeperiod)) self.sec[name] = dict(type=type, color=color) self.ind[name] = talib.MINUS_DM( self.df[self.hi].values, self.df[self.lo].values, timeperiod )
def anaryze_data(self): dataframe = self.data pl_dm = talib.MINUS_DM(dataframe.high, dataframe.low, timeperiod=7) mi_dm = talib.PLUS_DM(dataframe.high, dataframe.low, timeperiod=7) dataframe["dmi_sig"] = (pl_dm - mi_dm) >= 0 macd, macdsignal, macdhist = talib.MACD(dataframe.close, fastperiod=9, slowperiod=26, signalperiod=9) dataframe["macd"] = (macd - macdsignal) >= 0 sma5 = talib.SMA(dataframe.close, timeperiod=45) sma15 = talib.SMA(dataframe.close, timeperiod=75) dataframe["sma_sig"] = (dataframe.close - sma15) >= 0 dataframe.dropna()
def filterAdx(self): """ filter by adx and dmi; others, HV, adx>25/30 from another(Greg Weitzman) for reference: 20-40 tendding, >40 exhaustion https://www.youtube.com/watch?v=7r8tRz2xPc0 :return: boolean """ close = self.df.Close[-28:].as_matrix( ) # Adj close is more accurate, factored high = self.df.High[-28:].as_matrix() low = self.df.Low[-28:].as_matrix() adx = talib.ADX(high, low, close, 14) # high, low, close, timeperiod=14 last_adx = adx[-1] if last_adx < 25: return False last_dm_pluse = talib.PLUS_DM(high, low)[-1] last_dm_minus = talib.MINUS_DM(high, low)[-1] if last_dm_pluse < last_dm_minus: return False """ 50 days hv>40% 6 days HV/100 days HV < 50%, it tend to have explosive movement. doubt this will filter recent plat stocks """ hv50 = util.historical_volatility(self.df.Close, 50) if hv50 < 0.4: return False hv6 = util.historical_volatility(self.df.Close, 6) hv100 = util.historical_volatility(self.df.Close, 100) if hv6 / hv100 > 0.5: return False return True
def dm(candles: np.ndarray, period: int = 14, sequential: bool = False) -> DM: """ DM - Directional Movement :param candles: np.ndarray :param period: int - default=14 :param sequential: bool - default=False :return: DM(plus, minus) """ candles = slice_candles(candles, sequential) MINUS_DI = talib.MINUS_DM(candles[:, 3], candles[:, 4], timeperiod=period) PLUS_DI = talib.PLUS_DM(candles[:, 3], candles[:, 4], timeperiod=period) if sequential: return DM(PLUS_DI, MINUS_DI) else: return DM(PLUS_DI[-1], MINUS_DI[-1])
def safezonestop(candles: np.ndarray, period: int = 22, mult: float = 2.5, max_lookback: int = 3, direction: str = "long", sequential: bool = False) -> Union[float, np.ndarray]: """ Safezone Stops :param candles: np.ndarray :param period: int - default=22 :param mult: float - default=2.5 :param max_lookback: int - default=3 :param direction: str - default=long :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:] high = candles[:, 3] low = candles[:, 4] last_high = np_shift(high, 1, fill_value=np.nan) last_low = np_shift(low, 1, fill_value=np.nan) if direction == "long": res = talib.MAX( last_low - mult * talib.MINUS_DM(high, low, timeperiod=period), max_lookback) else: res = talib.MIN( last_high + mult * talib.PLUS_DM(high, low, timeperiod=period), max_lookback) if sequential: return res else: return None if np.isnan(res[-1]) else res[-1]
def dm(candles: np.ndarray, period: int = 14, sequential: bool = False) -> DM: """ DM - Directional Movement :param candles: np.ndarray :param period: int - default=14 :param sequential: bool - default=False :return: DM(plus, minus) """ 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:] MINUS_DI = talib.MINUS_DM(candles[:, 3], candles[:, 4], timeperiod=period) PLUS_DI = talib.PLUS_DM(candles[:, 3], candles[:, 4], timeperiod=period) if sequential: return DM(PLUS_DI, MINUS_DI) else: return DM(PLUS_DI[-1], MINUS_DI[-1])
def test__adx(self): me = ta_adx(DF_TEST, relative=False)[-100:] ta_pdi = talib.PLUS_DI(DF_TEST["High"], DF_TEST["Low"], DF_TEST["Close"])[-100:] ta_mdi = talib.MINUS_DI(DF_TEST["High"], DF_TEST["Low"], DF_TEST["Close"])[-100:] ta_pdm = talib.PLUS_DM(DF_TEST["High"], DF_TEST["Low"])[-100:] ta_mdm = talib.MINUS_DM(DF_TEST["High"], DF_TEST["Low"])[-100:] ta_dx = talib.ADX(DF_TEST["High"], DF_TEST["Low"], DF_TEST["Close"])[-100:] np.testing.assert_array_almost_equal(me["ADX"], ta_dx / 100) np.testing.assert_array_almost_equal(me["+DI"], ta_pdi / 100) np.testing.assert_array_almost_equal(me["-DI"], ta_mdi / 100) # I have absolutely no idea why we are off by a constant factor. but since it is a constant factor we can # neglect it np.testing.assert_array_almost_equal(me["+DM"], ta_pdm * 0.07142861354566638) np.testing.assert_array_almost_equal(me["-DM"], ta_mdm * 0.07142861354566638)
def create_Indicators(data): dfs = data df = dfs.copy() df['ADX'] = talib.ADX(df.high, df.low, df.close, timeperiod=14) df['ADXR'] = talib.ADXR(df.high, df.low, df.close, timeperiod=14) df['APO'] = talib.APO(df.close, fastperiod=12, slowperiod=26, matype=0) df['AROONOSC'] = talib.AROONOSC(df.high, df.low, timeperiod=14) df['BOP'] = talib.BOP( df.open, df.high, df.low, df.close) # (Close price – Open price) / (High price – Low price) df["CCI"] = talib.CCI(df.high, df.low, df.close, timeperiod=14) df["CMO"] = talib.CMO(df.close, timeperiod=14) df["DX"] = talib.DX(df.high, df.low, df.close, timeperiod=14) #df["MFI"] = talib.MFI(df.high, df.low, df.close, df.volume, timeperiod=14).pct_change() df["MINUS_DI"] = talib.MINUS_DI(df.high, df.low, df.close, timeperiod=14) df["MINUS_DM"] = talib.MINUS_DM(df.high, df.low, timeperiod=14) df["MOM"] = talib.MOM(df.close, timeperiod=10) df["PLUS_DI"] = talib.PLUS_DI(df.high, df.low, df.close, timeperiod=14) df["PLUS_DM"] = talib.PLUS_DM(df.high, df.low, timeperiod=14) #X_corr["PPO"] = PPO(df.close, fastperiod=12, sdf.lowperiod=26, matype=0) df["ROC"] = talib.ROC(df.close, timeperiod=10) df["ROCP"] = talib.ROCP(df.close, timeperiod=10) df["ROCR"] = talib.ROCR(df.close, timeperiod=10) df["ROCR100"] = talib.ROCR100(df.close, timeperiod=10) df["RSI"] = talib.RSI(df.close, timeperiod=14) #sdf.lowk, sdf.lowd = STOCH(df.high, df.low, df.close, fastk_period=5, sdf.lowk_period=3, sdf.lowk_matype=0, sdf.lowd_period=3, sdf.lowd_matype=0) df["TRIX"] = talib.TRIX(df.close, timeperiod=30) df["ULTOSC"] = talib.ULTOSC(df.high, df.low, df.close, timeperiod1=7, timeperiod2=14, timeperiod3=28) df["WILLR"] = talib.WILLR(df.high, df.low, df.close, timeperiod=14) return df