Python talib.ADX Examples

The following are 20 code examples of talib.ADX(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module talib , or try the search function .
Example #1
Source File: data_preprocessing.py    From StarTrader with MIT License 22 votes vote down vote up
def technical_indicators_df(self, daily_data):
        """
        Assemble a dataframe of technical indicator series for a single stock
        """
        o = daily_data['Open'].values
        c = daily_data['Close'].values
        h = daily_data['High'].values
        l = daily_data['Low'].values
        v = daily_data['Volume'].astype(float).values
        # define the technical analysis matrix

        # Most data series are normalized by their series' mean
        ta = pd.DataFrame()
        ta['MA5'] = tb.MA(c, timeperiod=5) / tb.MA(c, timeperiod=5).mean()
        ta['MA10'] = tb.MA(c, timeperiod=10) / tb.MA(c, timeperiod=10).mean()
        ta['MA20'] = tb.MA(c, timeperiod=20) / tb.MA(c, timeperiod=20).mean()
        ta['MA60'] = tb.MA(c, timeperiod=60) / tb.MA(c, timeperiod=60).mean()
        ta['MA120'] = tb.MA(c, timeperiod=120) / tb.MA(c, timeperiod=120).mean()
        ta['MA5'] = tb.MA(v, timeperiod=5) / tb.MA(v, timeperiod=5).mean()
        ta['MA10'] = tb.MA(v, timeperiod=10) / tb.MA(v, timeperiod=10).mean()
        ta['MA20'] = tb.MA(v, timeperiod=20) / tb.MA(v, timeperiod=20).mean()
        ta['ADX'] = tb.ADX(h, l, c, timeperiod=14) / tb.ADX(h, l, c, timeperiod=14).mean()
        ta['ADXR'] = tb.ADXR(h, l, c, timeperiod=14) / tb.ADXR(h, l, c, timeperiod=14).mean()
        ta['MACD'] = tb.MACD(c, fastperiod=12, slowperiod=26, signalperiod=9)[0] / \
                     tb.MACD(c, fastperiod=12, slowperiod=26, signalperiod=9)[0].mean()
        ta['RSI'] = tb.RSI(c, timeperiod=14) / tb.RSI(c, timeperiod=14).mean()
        ta['BBANDS_U'] = tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[0] / \
                         tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[0].mean()
        ta['BBANDS_M'] = tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[1] / \
                         tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[1].mean()
        ta['BBANDS_L'] = tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[2] / \
                         tb.BBANDS(c, timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)[2].mean()
        ta['AD'] = tb.AD(h, l, c, v) / tb.AD(h, l, c, v).mean()
        ta['ATR'] = tb.ATR(h, l, c, timeperiod=14) / tb.ATR(h, l, c, timeperiod=14).mean()
        ta['HT_DC'] = tb.HT_DCPERIOD(c) / tb.HT_DCPERIOD(c).mean()
        ta["High/Open"] = h / o
        ta["Low/Open"] = l / o
        ta["Close/Open"] = c / o

        self.ta = ta 
Example #2
Source File: technical_indicator.py    From NowTrade with MIT License 7 votes vote down vote up
def results(self, data_frame):
        try:
            adx = talib.ADX(data_frame['%s_High' %self.symbol].values,
                            data_frame['%s_Low' %self.symbol].values,
                            data_frame['%s_Close' %self.symbol].values,
                            timeperiod=self.period)
            plus_di = talib.PLUS_DI(data_frame['%s_High' %self.symbol].values,
                                    data_frame['%s_Low' %self.symbol].values,
                                    data_frame['%s_Close' %self.symbol].values,
                                    timeperiod=self.period)
            minus_di = talib.MINUS_DI(data_frame['%s_High' %self.symbol].values,
                                      data_frame['%s_Low' %self.symbol].values,
                                      data_frame['%s_Close' %self.symbol].values,
                                      timeperiod=self.period)
            data_frame[self.value] = adx
            data_frame[self.plus_di] = plus_di
            data_frame[self.minus_di] = minus_di
        except KeyError:
            data_frame[self.value] = np.nan
            data_frame[self.plus_di] = np.nan
            data_frame[self.minus_di] = np.nan 
Example #3
Source File: talib_numpy.py    From QUANTAXIS with MIT License 6 votes vote down vote up
def ADX_MA(data, period=14, smooth=14, limit=18):
    """
    Moving Average ADX
    ADX Smoothing Trend Color Change on Moving Average and ADX Cross. Use on Hourly Charts - Green UpTrend - Red DownTrend - Black Choppy No Trend

    Source: https://www.tradingview.com/script/owwws7dM-Moving-Average-ADX/
    Translator: 阿财(Rgveda@github)(4910163#qq.com)

    Parameters
    ----------
    data : (N,) array_like
        传入 OHLC Kline 序列。
        The OHLC Kline.
    period : int or None, optional
        DI 统计周期 默认值为 14
        DI Length period. Default value is 10. 
    smooth : int or None, optional
        ADX 平滑周期 默认值为 14
        ADX smoothing length period. Default value is 10.
    limit : int or None, optional
        ADX 限制阈值 默认值为 18
        ADX MA Active limit threshold. Default value is 18.

    Returns
    -------
    adx, ADXm : ndarray
        ADXm 指标和趋势指示方向 (-1, 0, 1) 分别代表 (下跌, 无明显趋势, 上涨)
        ADXm indicator and thread directions sequence. (-1, 0, 1) means for (Neagtive, No Trend, Positive)

    """
    up = data.high.pct_change()
    down = data.low.pct_change() * -1

    trur = TA_HMA(talib.TRANGE(data.high.values, data.low.values, data.close.values) , period)
    plus = 100 * TA_HMA(np.where(((up > down) & (up > 0)), up, 0), period) / trur
    minus = 100 * TA_HMA(np.where(((down > up) & (down > 0)), down, 0), period) / trur

    # 这里是dropna的替代解决办法,因为我觉得nparray的传递方式如果随便drop了可能会跟 data.index
    # 对不上,所以我选择补零替代dropna
    plus = np.r_[np.zeros(period + 2), plus[(period + 2):]]
    minus = np.r_[np.zeros(period + 2), minus[(period + 2):]]
    sum = plus + minus 
    adx = 100 * TA_HMA(abs(plus - minus) / (np.where((sum == 0), 1, sum)), smooth)
    adx = np.r_[np.zeros(smooth + 2), adx[(smooth + 2):]]
    ADXm = np.where(((adx > limit) & (plus > minus)), 1, np.where(((adx > limit) & (plus < minus)), -1, 0))
    return adx, ADXm 
Example #4
Source File: talib_indicators.py    From QUANTAXIS with MIT License 6 votes vote down vote up
def ADX(DataFrame, N=14):
    res = talib.ADX(DataFrame.high.values, DataFrame.low.values, DataFrame.close.values, N)
    return pd.DataFrame({'ADX': res}, index=DataFrame.index) 
Example #5
Source File: ta.py    From dash-technical-charting with MIT License 6 votes vote down vote up
def add_ADX(self, timeperiod=14,
            type='line', color='secondary', **kwargs):
    """Average Directional Movement Index."""

    if not (self.has_high and self.has_low and self.has_close):
        raise Exception()

    utils.kwargs_check(kwargs, VALID_TA_KWARGS)
    if 'kind' in kwargs:
        type = kwargs['kind']

    name = 'ADX({})'.format(str(timeperiod))
    self.sec[name] = dict(type=type, color=color)
    self.ind[name] = talib.ADX(self.df[self.hi].values,
                               self.df[self.lo].values,
                               self.df[self.cl].values,
                               timeperiod) 
Example #6
Source File: adx.py    From jesse with MIT License 6 votes vote down vote up
def adx(candles: np.ndarray, period=14, sequential=False) -> Union[float, np.ndarray]:
    """
    ADX - Average Directional Movement Index

    :param candles: np.ndarray
    :param period: int - default=14
    :param sequential: bool - default=False

    :return: float | np.ndarray
    """
    if not sequential and len(candles) > 240:
        candles = candles[-240:]

    res = talib.ADX(candles[:, 3], candles[:, 4], candles[:, 2], timeperiod=period)

    if sequential:
        return res
    else:
        return None if np.isnan(res[-1]) else res[-1] 
Example #7
Source File: talib_indicators.py    From qtpylib with Apache License 2.0 5 votes vote down vote up
def ADX(data, **kwargs):
    _check_talib_presence()
    _, phigh, plow, pclose, _ = _extract_ohlc(data)
    return talib.ADX(phigh, plow, pclose, **kwargs) 
Example #8
Source File: IndicatorSubsystem.py    From cbpro-trader with GNU General Public License v3.0 5 votes vote down vote up
def calculate_adx(self, period_name, close):
        adx = talib.ADX(self.highs, self.lows, close, timeperiod=14)

        self.current_indicators[period_name]['adx'] = adx[-1] 
Example #9
Source File: test_indicator_trend.py    From pandas-ta with MIT License 5 votes vote down vote up
def test_adx(self):
        result = pandas_ta.adx(self.high, self.low, self.close)
        self.assertIsInstance(result, DataFrame)
        self.assertEqual(result.name, 'ADX_14')

        try:
            expected = tal.ADX(self.high, self.low, self.close)
            pdt.assert_series_equal(result.iloc[:,0], expected)
        except AssertionError as ae:
            try:
                corr = pandas_ta.utils.df_error_analysis(result.iloc[:,0], expected, col=CORRELATION)
                self.assertGreater(corr, CORRELATION_THRESHOLD)
            except Exception as ex:
                error_analysis(result, CORRELATION, ex) 
Example #10
Source File: talib_wrapper.py    From tia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ADX(frame, n=14, high_col='high', low_col='low', close_col='close'):
    return _frame_to_series(frame, [high_col, low_col, close_col], talib.ADX, n) 
Example #11
Source File: TinyQuantBase.py    From futuquant with Apache License 2.0 5 votes vote down vote up
def adx(self, n, array=False):
        """ADX指标"""
        result = talib.ADX(self.high, self.low, self.close, n)
        if array:
            return result
        return result[-1]

    # ---------------------------------------------------------------------- 
Example #12
Source File: test_reg.py    From finta with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_adx():
    '''test TA.ADX'''

    adx = TA.ADX(ohlc, period=12)
    ta_adx = talib.ADX(ohlc["high"], ohlc["low"], ohlc["close"], timeperiod=12)

    assert int(ta_adx[-1]) == int(adx.values[-1]) 
Example #13
Source File: ta_lib.py    From ctpbee with MIT License 5 votes vote down vote up
def adx(self, n, array=False):
        """
        ADX.
        """
        result = talib.ADX(self.high, self.low, self.close, n)
        if array:
            return result
        return result[-1] 
Example #14
Source File: __init__.py    From ebisu with MIT License 5 votes vote down vote up
def adx(high, low, close, period=14):
    return talib.ADX(high, low, close, period) 
Example #15
Source File: array_manager.py    From 51bitqunt with MIT License 5 votes vote down vote up
def adx(self, n, array=False):
        """
        ADX.
        """
        result = talib.ADX(self.high, self.low, self.close, n)
        if array:
            return result
        return result[-1] 
Example #16
Source File: technical_indicator.py    From NowTrade with MIT License 5 votes vote down vote up
def __str__(self):
        return 'ADX(symbol=%s, period=%s)' %(self.symbol, self.period) 
Example #17
Source File: ta_indicator_mixin.py    From strategy with Apache License 2.0 5 votes vote down vote up
def adx(self, sym, frequency, period=14):
        if not self.kbars_ready(sym, frequency):
            return []

        highs = self.high(sym, frequency)
        lows = self.low(sym, frequency)
        closes = self.close(sym, frequency)

        return ta.ADX(highs, lows, closes, timeperiod=period) 
Example #18
Source File: talib_numpy.py    From QUANTAXIS with MIT License 5 votes vote down vote up
def Volume_HMA(klines, period=5):
    """
    交易量加权船型移动平均线 HMA,方向指示性类似于 Moving Average ADX,但它们通过不同的指标实现。
    Hull Moving Average with Volume weighted, diretions similar like ADX_MA

    Source: https://www.tradingview.com/script/XTViDINu-VHMA/
    Translator: 阿财(Rgveda@github)(4910163#qq.com)

    Parameters
    ----------
    klines : (N,) array_like
        传入 OHLC Kline 序列。
        The OHLC Kline.
    period : int or None, optional
        DI 统计周期 默认值为 10
        DI Length period. Default value is 10. 

    Returns
    -------
    vhma, Trend : ndarray
        vhma 指标和 Trend 趋势指示方向 (-1/-2, 0, 1/2) 分别代表 (下跌, 无明显趋势, 上涨)
        the vhma indicator and thread directions sequence. (-1/-2, 0, 1/2) means for (Neagtive, No Trend, Positive)

    """
    src1 = talib.EMA(klines.close * klines.volume, period) / talib.EMA(klines.volume, period)
    vhma = TA_HMA(src1, period)
    vhma_s = pd.Series(vhma)

    lineDirection = np.where((vhma > vhma_s.shift(1).values), 1, -1)
    hu = np.where((vhma > vhma_s.shift(2).values), 1, -1)
    return vhma, lineDirection + hu 
Example #19
Source File: talib_numpy.py    From QUANTAXIS with MIT License 5 votes vote down vote up
def TA_ADXR(high, low, close, timeperiod=14) -> np.ndarray:
    """
    名称:平均趋向指数的趋向指数
    简介:使用ADXR指标,指标判断ADX趋势。
    ADXR - Average Directional Movement Index Rating
    """
    real = talib.ADXR(high, low, close, timeperiod=timeperiod)
    return np.c_[real] 
Example #20
Source File: talib_numpy.py    From QUANTAXIS with MIT License 5 votes vote down vote up
def TA_ADX(high, low, close, timeperiod=14) -> np.ndarray:
    """
    ADX - Average Directional Movement Index
    """
    real = talib.ADX(high, low, close, timeperiod=timeperiod)
    return np.c_[real]