Python talib.EMA Examples

The following are 30 code examples of talib.EMA(). 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: features.py    From trading-server with GNU General Public License v3.0 10 votes vote down vote up
def MACD(self, name,  bars: list):
        """
        Return MACD for given time series. Bars list must be 26 bars
        in length (last 26 bars for period).

        MACD = EMA(12) - EMA(26)

        Note we only use the MACD, not signal or histogram.
        """

        self.check_bars_type(bars)

        macd, signal, hist = ta.MACD(
            bars['close'], fastperiod=12, slowperiod=26, signalperiod=9)

        return macd 
Example #2
Source File: features.py    From trading-server with GNU General Public License v3.0 7 votes vote down vote up
def EMA(self, period: int, bars: list):
        """
        Exponential moving average of previous n bars close price.

        EMA = price(t) * k + EMA(y) * ( 1 − k )

        where:
            t = today (current bar for any period)
            y = yesterday (previous bar close price)
            N = number of bars (period)
            k = 2 / (N + 1) (weight factor)
        """

        self.check_bars_type(bars)

        ema = ta.EMA(bars['close'], timeperiod=period)

        return ema 
Example #3
Source File: IndicatorSubsystem.py    From cbpro-trader with GNU General Public License v3.0 7 votes vote down vote up
def calculate_obv(self, period_name, closing_prices, volumes):
        obv = talib.OBV(closing_prices, volumes)
        obv_ema = talib.EMA(obv, timeperiod=3)

        self.current_indicators[period_name]['obv_ema'] = obv_ema[-1]
        self.current_indicators[period_name]['obv'] = obv[-1] 
Example #4
Source File: DyST_IntraDayT.py    From DevilYuan with MIT License 7 votes vote down vote up
def _getAtrExtreme(cls, highs, lows, closes, atrPeriod=14, slowPeriod=30, fastPeriod=3):
        """
            获取TTI ATR Exterme通道, which is based on 《Volatility-Based Technical Analysis》
            TTI is 'Trading The Invisible'

            @return: fasts, slows
        """
        # talib 的源码,它的 ATR 不是 N 日简单平均,而是类似 EMA 的方法计算的指数平均
        atr = talib.ATR(highs, lows, closes, timeperiod=atrPeriod)

        highsMean = talib.EMA(highs, 5)
        lowsMean = talib.EMA(lows, 5)
        closesMean = talib.EMA(closes, 5)

        atrExtremes = np.where(closes > closesMean,
                               ((highs - highsMean)/closes * 100) * (atr/closes * 100),
                               ((lows - lowsMean)/closes * 100) * (atr/closes * 100)
                               )

        fasts = talib.MA(atrExtremes, fastPeriod)
        slows = talib.EMA(atrExtremes, slowPeriod)

        return fasts, slows, np.std(atrExtremes[-slowPeriod:]) 
Example #5
Source File: ABuNDMa.py    From abu with GNU General Public License v3.0 6 votes vote down vote up
def _calc_ma_from_ta(prices, time_period=10, from_calc=EMACalcType.E_MA_MA):
    """
    使用talib计算ma,即透传talib.MA or talib.EMA计算结果
    :param prices: 收盘价格序列,pd.Series或者np.array
    :param time_period: 移动平均的N值,int
    :param from_calc: EMACalcType enum对象,移动移动平均使用的方法
    """

    import talib
    if isinstance(prices, pd.Series):
        prices = prices.values

    if from_calc == EMACalcType.E_MA_MA:
        ma = talib.MA(prices, timeperiod=time_period)
    else:
        ma = talib.EMA(prices, timeperiod=time_period)
    return ma 
Example #6
Source File: DyST_IntraDayT.py    From DevilYuan with MIT License 6 votes vote down vote up
def _getAtrExtreme(cls, highs, lows, closes, atrPeriod=14, slowPeriod=30, fastPeriod=3):
        """
            获取TTI ATR Exterme通道, which is based on 《Volatility-Based Technical Analysis》
            TTI is 'Trading The Invisible'

            @return: fasts, slows
        """
        # talib 的源码,它的 ATR 不是 N 日简单平均,而是类似 EMA 的方法计算的指数平均
        atr = talib.ATR(highs, lows, closes, timeperiod=atrPeriod)

        highsMean = talib.EMA(highs, 5)
        lowsMean = talib.EMA(lows, 5)
        closesMean = talib.EMA(closes, 5)

        atrExtremes = np.where(closes > closesMean,
                               ((highs - highsMean)/closes * 100) * (atr/closes * 100),
                               ((lows - lowsMean)/closes * 100) * (atr/closes * 100)
                               )

        fasts = talib.MA(atrExtremes, fastPeriod)
        slows = talib.EMA(atrExtremes, slowPeriod)

        return fasts, slows, np.std(atrExtremes[-slowPeriod:]) 
Example #7
Source File: vwmacd.py    From jesse with MIT License 6 votes vote down vote up
def vwmacd(candles: np.ndarray, fastperiod=12, slowperiod=26, signalperiod=9, sequential=False) -> VWMACD:
    """
    VWMACD - Volume Weighted Moving Average Convergence/Divergence

    :param candles: np.ndarray
    :param fastperiod: int - default: 12
    :param slow_period: int - default: 26
    :param signal_period: int - default: 9
    :param sequential: bool - default: False

    :return: VWMACD(macd, signal, hist)
    """
    if not sequential and len(candles) > 240:
        candles = candles[-240:]

    vwma_slow = talib.SMA(candles[:, 2] * candles[:, 5], slowperiod) / talib.SMA(candles[:, 5], slowperiod)
    vwma_fast = talib.SMA(candles[:, 2] * candles[:, 5], fastperiod) / talib.SMA(candles[:, 5], fastperiod)
    vwmacd = vwma_fast - vwma_slow
    signal = talib.EMA(vwmacd, signalperiod)
    hist = vwmacd - signal

    if sequential:
        return VWMACD(vwmacd, signal, hist)
    else:
        return VWMACD(vwmacd[-1], signal[-1], hist[-1]) 
Example #8
Source File: ema.py    From jesse with MIT License 6 votes vote down vote up
def ema(candles: np.ndarray, period=5, source_type="close", sequential=False) -> Union[float, np.ndarray]:
    """
    EMA - Exponential Moving Average

    :param candles: np.ndarray
    :param period: int - default: 5
    :param source_type: str - default: "close"
    :param sequential: bool - default=False

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

    source = get_candle_source(candles, source_type=source_type)
    res = talib.EMA(source, timeperiod=period)

    return res if sequential else res[-1] 
Example #9
Source File: tsi.py    From jesse with MIT License 6 votes vote down vote up
def tsi(candles: np.ndarray, long_period=25, short_period=13, source_type="close", sequential=False) -> Union[
    float, np.ndarray]:
    """
     True strength index (TSI)

    :param candles: np.ndarray
    :param long_period: int - default: 25
    :param short_period: int - default: 13
    :param source_type: str - default: "close"
    :param sequential: bool - default=False

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

    source = get_candle_source(candles, source_type=source_type)
    r = 100 * (talib.EMA((talib.EMA(talib.MOM(source, 1), long_period)), short_period)) / (
        talib.EMA((talib.EMA(np.absolute(talib.MOM(source, 1)), long_period)), short_period))

    return r if sequential else r[-1] 
Example #10
Source File: indicators.py    From technical with GNU General Public License v3.0 5 votes vote down vote up
def momentum(dataframe, field='close', period=9):
    from pyti.momentum import momentum as m
    return m(dataframe[field], period)


# PLUS_DI              Plus Directional Indicator
# PLUS_DM              Plus Directional Movement
# PPO                  Percentage Price Oscillator
# ROC                  Rate of change : ((price/prevPrice)-1)*100
# ROCP                 Rate of change Percentage: (price-prevPrice)/prevPrice
# ROCR                 Rate of change ratio: (price/prevPrice)
# ROCR100              Rate of change ratio 100 scale: (price/prevPrice)*100
# RSI                  Relative Strength Index
# STOCH                Stochastic
# STOCHF               Stochastic Fast
# STOCHRSI             Stochastic Relative Strength Index
# TRIX                 1-day Rate-Of-Change (ROC) of a Triple Smooth EMA

# ULTOSC               Ultimate Oscillator 
Example #11
Source File: indicators.py    From technical with GNU General Public License v3.0 5 votes vote down vote up
def ema(dataframe, period, field='close'):
    import talib.abstract as ta
    return ta.EMA(dataframe, timeperiod=period, price=field)


# HT_TRENDLINE         Hilbert Transform - Instantaneous Trendline
# KAMA                 Kaufman Adaptive Moving Average
# MA                   Moving average
# MAMA                 MESA Adaptive Moving Average
# MAVP                 Moving average with variable period
# MIDPOINT             MidPoint over period
# MIDPRICE             Midpoint Price over period
# SAR                  Parabolic SAR
# SAREXT               Parabolic SAR - Extended

# SMA                  Simple Moving Average 
Example #12
Source File: indicators.py    From technical with GNU General Public License v3.0 5 votes vote down vote up
def stc(dataframe, fast=23, slow=50, length=10):

    # First, the 23-period and the 50-period EMA and the MACD values are calculated:
    # EMA1 = EMA (Close, Short Length);
    # EMA2 = EMA (Close, Long Length);
    # MACD = EMA1 – EMA2.
    # Second, the 10-period Stochastic from the MACD values is calculated:
    # %K (MACD) = %KV (MACD, 10);
    # %D (MACD) = %DV (MACD, 10);
    # Schaff = 100 x (MACD – %K (MACD)) / (%D (MACD) – %K (MACD))

    import talib.abstract as ta

    MACD = ta.EMA(dataframe, timeperiod=fast) - ta.EMA(dataframe, timeperiod=slow)
    STOK = ((MACD - MACD.rolling(window=length).min()) / (
            MACD.rolling(window=length).max() - MACD.rolling(window=length).min())) * 100
    STOD = STOK.rolling(window=length).mean()
    dataframe['stc'] = 100 * (MACD - (STOK * MACD)) / ((STOD * MACD) - (STOK * MACD))

    return dataframe['stc'] 
Example #13
Source File: test_reg.py    From finta with GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_ema():
    '''test TA.EMA'''

    ma = TA.EMA(ohlc, 50)
    talib_ma = talib.EMA(ohlc['close'], timeperiod=50)

    assert round(talib_ma[-1], 5) == round(ma.values[-1], 5) 
Example #14
Source File: TinyStrateMACD.py    From futuquant with Apache License 2.0 5 votes vote down vote up
def on_bar_min1(self, tiny_bar):
        """每一分钟触发一次回调"""

        symbol = self.symbol_pools[0]

        now = datetime.datetime.now()
        work_time = now.replace(hour=15, minute=55, second=0)

        if now == work_time:
            quote_ctx = OpenQuoteContext(host='172.24.31.139', port=11111)
            data = tiny_bar
            price = data.open
            start_day = (now - datetime.timedelta(days=100)).strftime('%Y-%m-%d')
            end_day = now.strftime('%Y-%m-%d')
            history_result, history_kline_result = quote_ctx.get_history_kline(symbol, start=start_day, end=end_day)
            result, kline_result = quote_ctx.get_history_kline(symbol, start=start_day, end=end_day, ktype='K_5M')
            if history_result == 0 and result == 0 and history_kline_result.shape[0] >= 25 and kline_result.shape[0] > 0 :
                close_price = kline_result[-1:]
                close_price_array = history_kline_result['close']
                close_price_array.append(close_price)
                df = pd.DataFrame()
                df['EMA12'] = talib.EMA(np.array(close_price_array), timeperiod=6)
                df['EMA26'] = talib.EMA(np.array(close_price_array), timeperiod=12)
                df['MACD'], df['MACDsignal'], df['MACDhist'] = talib.MACD(np.array(close_price_array), fastperiod=6, slowperiod=12, signalperiod=9)
                signal = df['MACDsignal'][-1:].values[0]
                if signal > 0:
                    self.do_trade(symbol, price, "buy")
                elif signal <0:
                    self.do_trade(symbol, price, "sell")
            quote_ctx = OpenQuoteContext(host='172.24.31.139', port=11111) 
Example #15
Source File: TinyStrateMACD.py    From futuquant with Apache License 2.0 5 votes vote down vote up
def ema(self, np_array, n, array=False):
        """移动均线"""
        if n < 2:
            result = np_array
        else:
            result = talib.EMA(np_array, n)
        if array:
            return result
        return result[-1] 
Example #16
Source File: TinyStrateMeanLine.py    From futuquant with Apache License 2.0 5 votes vote down vote up
def get_sma(self, n, symbol):
        quote_ctx = OpenQuoteContext(host='127.0.0.1', port=11111)
        now = datetime.datetime.now()
        end_str = now.strftime('%Y-%m-%d')
        start = now - datetime.timedelta(days=365)
        start_str = start.strftime('%Y-%m-%d')
        temp = quote_ctx.get_history_kline(symbol, start=start_str, end=end_str)
        temp_data = temp[1]['close']
        result = talib.EMA(temp_data, n)
        quote_ctx.close()
        return result.values[-1] 
Example #17
Source File: TinyStrateSouthETF.py    From futuquant with Apache License 2.0 5 votes vote down vote up
def ema(self, np_array, n, array=False):
        """移动均线"""
        if n < 2:
            result = np_array
        else:
            result = talib.EMA(np_array, n)
        if array:
            return result
        return result[-1] 
Example #18
Source File: TinyStrateSample.py    From futuquant with Apache License 2.0 5 votes vote down vote up
def ema(self, np_array, n, array=False):
        """移动均线"""
        if n < 2:
            result = np_array
        else:
            result = talib.EMA(np_array, n)
        if array:
            return result
        return result[-1] 
Example #19
Source File: talib_wrapper.py    From tia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def EMA(series, n=30):
    """exponential moving average"""
    return _series_to_series(series, talib.EMA, n) 
Example #20
Source File: test_indicator_overlap.py    From pandas-ta with MIT License 5 votes vote down vote up
def test_ema(self):
        result = pandas_ta.ema(self.close, presma=False)
        self.assertIsInstance(result, Series)
        self.assertEqual(result.name, 'EMA_10')

        try:
            expected = tal.EMA(self.close, 10)
            pdt.assert_series_equal(result, expected, check_names=False)
        except AssertionError as ae:
            try:
                corr = pandas_ta.utils.df_error_analysis(result, expected, col=CORRELATION)
                self.assertGreater(corr, CORRELATION_THRESHOLD)
            except Exception as ex:
                error_analysis(result, CORRELATION, ex) 
Example #21
Source File: talib_indicators.py    From qtpylib with Apache License 2.0 5 votes vote down vote up
def EMA(data, **kwargs):
    _check_talib_presence()
    prices = _extract_series(data)
    return talib.EMA(prices, **kwargs) 
Example #22
Source File: indicators.py    From technical with GNU General Public License v3.0 5 votes vote down vote up
def bollinger_bands(dataframe, period=21, stdv=2, field='close', colum_prefix="bb") -> DataFrame:
    from pyti.bollinger_bands import lower_bollinger_band, middle_bollinger_band, upper_bollinger_band
    dataframe["{}_lower".format(colum_prefix)] = lower_bollinger_band(dataframe[field], period, stdv)
    dataframe["{}_middle".format(colum_prefix)] = middle_bollinger_band(dataframe[field], period, stdv)
    dataframe["{}_upper".format(colum_prefix)] = upper_bollinger_band(dataframe[field], period, stdv)

    return dataframe


# DEMA                 Double Exponential Moving Average

# EMA                  Exponential Moving Average 
Example #23
Source File: ctaLineBar.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def __recountYB(self):
        """某种趋势线"""

        if not self.inputYb:
            return

        if self.inputYbLen <1:
            return

        if self.inputYbRef < 1:
            self.debugCtaLog(u'参数 self.inputYbRef:{}不能低于1'.format(self.inputYbRef))
            return

        # 1、lineBar满足长度才执行计算
        if len(self.lineBar) < 4 * self.inputYbLen:
            self.debugCtaLog(u'数据未充分,当前Bar数据数量:{0},计算YB 需要:{1}'.
                             format(len(self.lineBar), 4 * self.inputYbLen))
            return

        emaLen = self.inputYbLen
        # 3、获取前InputN周期(不包含当前周期)的K线
        if self.mode == self.TICK_MODE:
            list_mid3 = [x.mid3 for x in self.lineBar[-emaLen*4 - 1:-1]]
        else:
            list_mid3 = [x.mid3 for x in self.lineBar[-emaLen*4:]]
        bar_mid3_ema10 = ta.EMA(np.array(list_mid3, dtype=float), emaLen)[-1]
        bar_mid3_ema10 = round(float(bar_mid3_ema10), self.round_n)

        if len(self.lineYb) > emaLen*4:
            del self.lineYb[0]

        self.lineYb.append(bar_mid3_ema10)

        if len(self.lineYb) < self.inputYbRef + 1:
            return

        if self.lineYb[-1] > self.lineYb[-1 - self.inputYbRef]:
            self.yb_count = self.yb_count + 1 if self.yb_count >= 0 else 1
        else:
            self.yb_count = self.yb_count - 1 if self.yb_count <= 0 else -1 
Example #24
Source File: ctaLineBar.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def getRuningYb(self):
        """
        获取未完结的bar计算出来的YB值
        :return: None,空值;float,计算值
        """
        if not self.inputYb :
            return None
        if self.inputYbLen < 1:
            return None
        if self.inputYbRef < 1:
            self.debugCtaLog(u'参数 self.inputYbRef:{}不能低于1'.format(self.inputYbRef))
            return None

        # 1、lineBar满足长度才执行计算
        if len(self.lineBar) < 4 * self.inputYbLen:
            self.debugCtaLog(u'数据未充分,当前Bar数据数量:{0},计算YB 需要:{1}'.
                             format(len(self.lineBar), 4 * self.inputYbLen))
            return None

        emaLen = self.inputYbLen
        # 3、获取前InputN周期(包含当前周期)的K线
        list_mid3 = [x.mid3 for x in self.lineBar[-emaLen*4:-1]]
        last_bar_mid3 = (self.lineBar[-1].close + self.lineBar[-1].high + self.lineBar[-1].low)/3
        list_mid3.append(last_bar_mid3)
        bar_mid3_ema10 = ta.EMA(np.array(list_mid3, dtype=float), emaLen)[-1]
        bar_mid3_ema10 = round(float(bar_mid3_ema10), self.round_n)
        return bar_mid3_ema10
    # ---------------------------------------------------------------------- 
Example #25
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 #26
Source File: talib_series.py    From QUANTAXIS with MIT License 5 votes vote down vote up
def DEMA(Series, timeperiod=30):
    res = talib.DEMA(Series.values, timeperiod)
    return pd.Series(res, index=Series.index)


# def EMA(Series, timeperiod=30):
#     res = talib.EMA(Series.values, timeperiod)
#     return pd.Series(res, index=Series.index) 
Example #27
Source File: ta_indicator_mixin.py    From strategy with Apache License 2.0 5 votes vote down vote up
def ema_close(self, sym, frequency, period=30):
        if not self.kbars_ready(sym, frequency):
            return []

        closes = self.close(sym, frequency)
        ma = ta.EMA(closes, timeperiod=period)

        return ma 
Example #28
Source File: test_pandas_talib.py    From pandas_talib with MIT License 5 votes vote down vote up
def test_indicator_EMA(self):
        n = 3
        price = 'Close'
        result = EMA(df, n)
        isinstance(result, pd.DataFrame)
        expected = talib.EMA(df[price].values, timeperiod=n)
        np.testing.assert_almost_equal(result.values, expected) 
Example #29
Source File: technical_indicator.py    From NowTrade with MIT License 5 votes vote down vote up
def __str__(self):
        return 'EMA(data=%s, period=%s)' %(self.data, self.period) 
Example #30
Source File: technical_indicator.py    From NowTrade with MIT License 5 votes vote down vote up
def results(self, data_frame):
        try:
            data_frame[self.value] = talib.EMA(data_frame[self.data].values, self.period)
        except KeyError:
            data_frame[self.value] = np.nan