Beispiel #1
0
    def test_PLUS_DM(self):
        class MyPLUS_DM(OperatorPLUS_DM):
            def __init__(self, name, **kwargs):
                super(MyPLUS_DM, self).__init__(100, name, **kwargs)

        self.env.add_operator('minus_dm', {
            'operator': MyPLUS_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.PLUS_DM(h[:100, i], l[:100,
                                            i], timeperiod=14)[-1] == val)
        for i, val in ser1.iteritems():
            res0.append(
                talib.PLUS_DM(h[1:100 + 1, i], l[1:100 + 1,
                                                 i], timeperiod=14)[-1] == val)
            res.append(
                talib.PLUS_DM(h[:100 + 1, i], l[:100 + 1,
                                                i], timeperiod=14)[-1] != val)
        self.assertTrue(all(res0) and all(res1) and any(res))
Beispiel #2
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
Beispiel #3
0
def plus_dm(client,
            symbol,
            timeframe="6m",
            highcol="high",
            lowcol="low",
            period=14):
    """This will return a dataframe of
    Plus 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.PLUS_DM(df[highcol].values.astype(float),
                  df[lowcol].values.astype(float), period)
    return pd.DataFrame({
        highcol: df[highcol].values,
        lowcol: df[lowcol].values,
        "plus_dm": x
    })
Beispiel #4
0
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
Beispiel #5
0
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')
Beispiel #6
0
    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
Beispiel #7
0
    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)
Beispiel #8
0
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]
Beispiel #9
0
 def compPLUSDM(self):
     pdm = talib.PLUS_DM(self.high,self.low,timeperiod=self.lookback)
     self.removeNullID(pdm)
     self.rawFeatures['PLUS_DM'] = pdm
     
     FEATURE_SIZE_DICT['PLUS_DM'] = 1
     return
Beispiel #10
0
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)
Beispiel #11
0
    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
Beispiel #12
0
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]
Beispiel #13
0
	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 plus_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.PLUS_DM(highs, lows, *args, **kwargs)
Beispiel #15
0
    def plus_dm(self, n, array=False):
        """
        PLUS_DM.
        """
        result = talib.PLUS_DM(self.high, self.low, n)

        if array:
            return result
        return result[-1]
Beispiel #16
0
    def plus_dm(self, n: int, array: bool = False) -> Union[float, np.ndarray]:
        """
        PLUS_DM.
        """
        result = talib.PLUS_DM(self.high, self.low, n)

        if array:
            return result
        return result[-1]
 def PLUS_DM(self, timeperiod=14):
     real_data = np.array([self.df.high, self.df.low], dtype='f8')
     plus_dm = talib.PLUS_DM(real_data[0], real_data[1], timeperiod=timeperiod)
     # return go.Scatter(
     #     x=self.df.index,
     #     y=plus_dm,
     #     name='PLUS_DM'
     # )
     return plus_dm
Beispiel #18
0
def main(df):
    highs = df['high'].values
    lows = df['low'].values
    closes = df['close'].values

    df["ta_DM"] = talib.PLUS_DM(highs, lows, 28)

    df["ta_sig_ta_PLUS_DM_28"] = df.apply(lambda row: adx_signal(row), axis=1)
    del df["ta_DM"]
    return df
Beispiel #19
0
def PLUS_DM(high, low, timeperiod=14):
    ''' Plus Directional Movement

    分组: Momentum Indicator 动量指标

    简介:

    real = PLUS_DM(high, low, timeperiod=14)
    '''
    return talib.PLUS_DM(high, low, timeperiod)
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
Beispiel #21
0
 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)
Beispiel #22
0
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
Beispiel #23
0
def add_PLUS_DM(self, timeperiod=14, type="line", color="increasing", **kwargs):
    """Plus 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 = "PLUS_DM({})".format(str(timeperiod))
    self.sec[name] = dict(type=type, color=color)
    self.ind[name] = talib.PLUS_DM(
        self.df[self.hi].values, self.df[self.lo].values, timeperiod
    )
Beispiel #24
0
    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
Beispiel #26
0
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])
Beispiel #27
0
def generate_tech_data(stock, open_name, close_name, high_name, low_name):
    open_price = stock[open_name].values
    close_price = stock[close_name].values
    low_price = stock[low_name].values
    high_price = stock[high_name].values
    data = pd.DataFrame(stock)
    data['MOM'] = talib.MOM(close_price)
    data['SMA'] = talib.SMA(close_price)
    data['HT_DCPERIOD'] = talib.HT_DCPERIOD(close_price)
    data['HT_DCPHASE'] = talib.HT_DCPHASE(close_price)
    data['sine'], data['leadsine'] = talib.HT_SINE(close_price)
    data['inphase'], data['quadrature'] = talib.HT_PHASOR(close_price)
    data['HT_TRENDMODE'] = talib.HT_TRENDMODE(close_price)
    data['SAREXT'] = talib.SAREXT(high_price, low_price)
    data['ADX'] = talib.ADX(high_price, low_price, close_price)
    data['ADXR'] = talib.ADX(high_price, low_price, close_price)
    data['APO'] = talib.APO(close_price)
    data['AROON_UP'], data['AROON_DOWN'] = talib.AROON(high_price, low_price)
    data['AROONOSC'] = talib.AROONOSC(high_price, low_price)
    data['BOP'] = talib.BOP(open_price, high_price, low_price, close_price)
    data['CCI'] = talib.CCI(high_price, low_price, close_price)
    data['PLUS_DI'] = talib.PLUS_DI(high_price, low_price, close_price)
    data['PLUS_DM'] = talib.PLUS_DM(high_price, low_price)
    data['PPO'] = talib.PPO(close_price)
    data['macd'], data['macd_sig'], data['macd_hist'] = talib.MACD(close_price)
    data['RSI'] = talib.RSI(close_price)
    data['CMO'] = talib.CMO(close_price)
    data['ROC'] = talib.ROC(close_price)
    data['ROCP'] = talib.ROCP(close_price)
    data['ROCR'] = talib.ROCR(close_price)
    data['slowk'], data['slowd'] = talib.STOCH(high_price, low_price,
                                               close_price)
    data['fastk'], data['fastd'] = talib.STOCHF(high_price, low_price,
                                                close_price)
    data['TRIX'] = talib.TRIX(close_price)
    data['ULTOSC'] = talib.ULTOSC(high_price, low_price, close_price)
    data['WILLR'] = talib.WILLR(high_price, low_price, close_price)
    data['NATR'] = talib.NATR(high_price, low_price, close_price)
    data['TRANGE'] = talib.TRANGE(high_price, low_price, close_price)
    data = data.drop([open_name, close_name, high_name, low_name], axis=1)
    data = data.dropna()
    return data
Beispiel #28
0
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]
Beispiel #29
0
Datei: dm.py Projekt: wcy/jesse
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])
Beispiel #30
0
    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)