Python talib.RSI Examples

The following are 30 code examples of talib.RSI(). 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: new_strategy.py    From pyfx with MIT License 6 votes vote down vote up
def annotate_data(self, feed, timeframe):
        # Get SMAs
        for k, v in six.iteritems(self.sma_intervals):
            feed[k] = talib.SMA(feed['closeMid'].values, v)

        # Get MACD
        # NOTE: talib.MACD() returns (macd, signal, hist)
        feed['macd'], _, feed['macd_hist'] = talib.MACD(
            feed['closeMid'].values,
            fastperiod=12,
            slowperiod=26,
            signalperiod=9
        )

        # Get RSI
        feed['rsi'] = talib.RSI(feed['closeMid'].values)
        return feed 
Example #3
Source File: talib_simple.py    From catalyst with Apache License 2.0 6 votes vote down vote up
def isSell(context, analysis):
    # Bearish SMA Crossover
    if (getLast(analysis, 'sma_test') == 0):
        # Bearish MACD
        if (getLast(analysis, 'macd_test') == 0):
            return True

    # # Bearish Stochastics
    # if(getLast(analysis, 'stoch_over_bought') == 0):
    #     return True

    # # Bearish RSI
    # if(getLast(analysis, 'rsi_over_bought') == 0):
    #     return True

    return False 
Example #4
Source File: strategyAtrRsi.py    From InplusTrader_Linux with MIT License 6 votes vote down vote up
def onInit(self):
        """初始化策略(必须由用户继承实现)"""
        self.writeCtaLog(u'%s策略初始化' %self.name)
    
        # 初始化RSI入场阈值
        self.rsiBuy = 50 + self.rsiEntry
        self.rsiSell = 50 - self.rsiEntry

        # 载入历史数据,并采用回放计算的方式初始化策略数值
        initData = self.loadBar(self.initDays)
        for bar in initData:
            self.onBar(bar)

        self.putEvent()

    #---------------------------------------------------------------------- 
Example #5
Source File: rsi.py    From InplusTrader_Linux with MIT License 5 votes vote down vote up
def handle_bar(context, bar_dict):
    # 开始编写你的主要的算法逻辑

    # bar_dict[order_book_id] 可以拿到某个证券的bar信息
    # context.portfolio 可以拿到现在的投资组合状态信息

    # 使用order_shares(id_or_ins, amount)方法进行落单

    # TODO: 开始编写你的算法吧!

    # 对我们选中的股票集合进行loop,运算每一只股票的RSI数值
    for stock in context.stocks:
        # 读取历史数据
        prices = history_bars(stock, context.TIME_PERIOD+1, '1d', 'close')

        # 用Talib计算RSI值
        rsi_data = talib.RSI(prices, timeperiod=context.TIME_PERIOD)[-1]

        cur_position = context.portfolio.positions[stock].quantity
        # 用剩余现金的30%来购买新的股票
        target_available_cash = context.portfolio.cash * context.ORDER_PERCENT

        # 当RSI大于设置的上限阀值,清仓该股票
        if rsi_data > context.HIGH_RSI and cur_position > 0:
            order_target_value(stock, 0)

        # 当RSI小于设置的下限阀值,用剩余cash的一定比例补仓该股
        if rsi_data < context.LOW_RSI:
            logger.info("target available cash caled: " + str(target_available_cash))
            # 如果剩余的现金不够一手 - 100shares,那么会被ricequant 的order management system reject掉
            order_value(stock, target_available_cash) 
Example #6
Source File: strategy_rsi.py    From archon with MIT License 5 votes vote down vote up
def backtest_market(data, buy_barrier, short_barrier):		
	COL_TIME = 0
	COL_CLOSE = 4
	COL_VOLUME = 5
	closes = [x[COL_CLOSE] for x in data]
	dates  = [x[COL_TIME] for x in data]
	volumes = [x[COL_VOLUME] for x in data]

	candle_data = {'close': closes, 'volume': volumes}
	bars = pd.DataFrame(candle_data, index=dates, columns = ['close','volume'])
	#print (bars.describe())
	
	bars['Pct Change'] = bars['close'].astype('float').pct_change()
	bars['RSI'] = talib.RSI(bars['close'])
	bars['volumeROC'] = talib.ROC(bars['volume'])
	
	symbol = market	
	rfs = RSIStrategy('close', bars, buy_barrier, short_barrier)
	signals = rfs.generate_signals()
	#print ("signal summary \n",signals.describe())	

	backtest = MarketOnOpenPortfolio(symbol, bars, signals)
	pf = backtest.backtest_portfolio()	
	lastindex = pf['Strategy'][-1]
	total_return = lastindex/100 -1
	print ("total return ",total_return)

	plot_portfolio(pf) 
Example #7
Source File: talib_simple.py    From catalyst with Apache License 2.0 5 votes vote down vote up
def isBuy(context, analysis):
    # Bullish SMA Crossover
    if (getLast(analysis, 'sma_test') == 1):
        # Bullish MACD
        if (getLast(analysis, 'macd_test') == 1):
            return True

    # # Bullish Stochastics
    # if(getLast(analysis, 'stoch_over_sold') == 1):
    #     return True

    # # Bullish RSI
    # if(getLast(analysis, 'rsi_over_sold') == 1):
    #     return True

    return False 
Example #8
Source File: simple_loop.py    From catalyst with Apache License 2.0 5 votes vote down vote up
def handle_data(context, data):
    log.info('handling bar: {}'.format(data.current_dt))

    price = data.current(context.asset, 'close')
    log.info('got price {price}'.format(price=price))

    prices = data.history(
        context.asset,
        fields='price',
        bar_count=20,
        frequency='30T'
    )
    last_traded = prices.index[-1]
    log.info('last candle date: {}'.format(last_traded))

    rsi = talib.RSI(prices.values, timeperiod=14)[-1]
    log.info('got rsi: {}'.format(rsi))

    # If base_price is not set, we use the current value. This is the
    # price at the first bar which we reference to calculate price_change.
    if context.base_price is None:
        context.base_price = price

    price_change = (price - context.base_price) / context.base_price
    cash = context.portfolio.cash

    # Now that we've collected all current data for this frame, we use
    # the record() method to save it. This data will be available as
    # a parameter of the analyze() function for further analysis.
    record(
        price=price,
        price_change=price_change,
        cash=cash
    ) 
Example #9
Source File: ta_lib.py    From ctpbee with MIT License 5 votes vote down vote up
def rsi(self, n, array=False):
        """
        Relative Strenght Index (RSI).
        """
        result = talib.RSI(self.close, n)
        if array:
            return result
        return result[-1] 
Example #10
Source File: rsi.py    From InplusTrader_Linux with MIT License 5 votes vote down vote up
def handle_bar(context, bar_dict):
    # 开始编写你的主要的算法逻辑

    # bar_dict[order_book_id] 可以拿到某个证券的bar信息
    # context.portfolio 可以拿到现在的投资组合状态信息

    # 使用order_shares(id_or_ins, amount)方法进行落单

    # TODO: 开始编写你的算法吧!

    # 对我们选中的股票集合进行loop,运算每一只股票的RSI数值
    for stock in context.stocks:
        # 读取历史数据
        prices = history_bars(stock, context.TIME_PERIOD+1, '1d', 'close')

        # 用Talib计算RSI值
        rsi_data = talib.RSI(prices, timeperiod=context.TIME_PERIOD)[-1]

        cur_position = context.portfolio.positions[stock].quantity
        # 用剩余现金的30%来购买新的股票
        target_available_cash = context.portfolio.cash * context.ORDER_PERCENT

        # 当RSI大于设置的上限阀值,清仓该股票
        if rsi_data > context.HIGH_RSI and cur_position > 0:
            order_target_value(stock, 0)

        # 当RSI小于设置的下限阀值,用剩余cash的一定比例补仓该股
        if rsi_data < context.LOW_RSI:
            logger.info("target available cash caled: " + str(target_available_cash))
            # 如果剩余的现金不够一手 - 100shares,那么会被ricequant 的order management system reject掉
            order_value(stock, target_available_cash) 
Example #11
Source File: rsi.py    From InplusTrader_Linux with MIT License 5 votes vote down vote up
def handle_bar(context, bar_dict):
    # 开始编写你的主要的算法逻辑

    # bar_dict[order_book_id] 可以拿到某个证券的bar信息
    # context.portfolio 可以拿到现在的投资组合状态信息

    # 使用order_shares(id_or_ins, amount)方法进行落单

    # TODO: 开始编写你的算法吧!

    # 对我们选中的股票集合进行loop,运算每一只股票的RSI数值
    for stock in context.stocks:
        # 读取历史数据
        prices = history_bars(stock, context.TIME_PERIOD+1, '1d', 'close')

        # 用Talib计算RSI值
        rsi_data = talib.RSI(prices, timeperiod=context.TIME_PERIOD)[-1]

        cur_position = context.portfolio.positions[stock].quantity
        # 用剩余现金的30%来购买新的股票
        target_available_cash = context.portfolio.cash * context.ORDER_PERCENT

        # 当RSI大于设置的上限阀值,清仓该股票
        if rsi_data > context.HIGH_RSI and cur_position > 0:
            order_target_value(stock, 0)

        # 当RSI小于设置的下限阀值,用剩余cash的一定比例补仓该股
        if rsi_data < context.LOW_RSI:
            logger.info("target available cash caled: " + str(target_available_cash))
            # 如果剩余的现金不够一手 - 100shares,那么会被ricequant 的order management system reject掉
            order_value(stock, target_available_cash) 
Example #12
Source File: strategy_rsi.py    From archon with MIT License 5 votes vote down vote up
def barrier_check_rsi(self, bar):
		""" check signal for every bar. indicators are pre-computed """
		rsi_value = bar['RSI']
		if rsi_value < self.buy_barrier:
			return 1
		elif rsi_value > self.short_barrier: 
			return -1
		else:
			return 0 
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_rsi():
    '''test TA.RSI'''

    rsi = TA.RSI(ohlc, 9)
    talib_rsi = talib.RSI(ohlc['close'], 9)

    assert int(talib_rsi[-1]) == int(rsi.values[-1]) 
Example #14
Source File: TinyQuantBase.py    From futuquant with Apache License 2.0 5 votes vote down vote up
def rsi(self, n, array=False):
        """RSI指标"""
        result = talib.RSI(self.close, n)
        if array:
            return result
        return result[-1]

    # ---------------------------------------------------------------------- 
Example #15
Source File: rsi.py    From Rqalpha-myquant-learning with Apache License 2.0 5 votes vote down vote up
def handle_bar(context, bar_dict):
    # 开始编写你的主要的算法逻辑

    # bar_dict[order_book_id] 可以拿到某个证券的bar信息
    # context.portfolio 可以拿到现在的投资组合状态信息

    # 使用order_shares(id_or_ins, amount)方法进行落单

    # TODO: 开始编写你的算法吧!

    # 对我们选中的股票集合进行loop,运算每一只股票的RSI数值
    for stock in context.stocks:
        # 读取历史数据
        prices = history_bars(stock, context.TIME_PERIOD+1, '1d', 'close')

        # 用Talib计算RSI值
        rsi_data = talib.RSI(prices, timeperiod=context.TIME_PERIOD)[-1]

        cur_position = context.portfolio.positions[stock].quantity
        # 用剩余现金的30%来购买新的股票
        target_available_cash = context.portfolio.cash * context.ORDER_PERCENT

        # 当RSI大于设置的上限阀值,清仓该股票
        if rsi_data > context.HIGH_RSI and cur_position > 0:
            order_target_value(stock, 0)

        # 当RSI小于设置的下限阀值,用剩余cash的一定比例补仓该股
        if rsi_data < context.LOW_RSI:
            logger.info("target available cash caled: " + str(target_available_cash))
            # 如果剩余的现金不够一手 - 100shares,那么会被ricequant 的order management system reject掉
            order_value(stock, target_available_cash) 
Example #16
Source File: talib_wrapper.py    From tia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def RSI(series, n=14):
    return _series_to_series(series, talib.RSI, n) 
Example #17
Source File: test_indicator_momentum.py    From pandas-ta with MIT License 5 votes vote down vote up
def test_rsi(self):
        result = pandas_ta.rsi(self.close)
        self.assertIsInstance(result, Series)
        self.assertEqual(result.name, 'RSI_14')

        try:
            expected = tal.RSI(self.close)
            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 #18
Source File: talib_indicators.py    From qtpylib with Apache License 2.0 5 votes vote down vote up
def RSI(data, **kwargs):
    _check_talib_presence()
    prices = _extract_series(data)
    return talib.RSI(prices, **kwargs) 
Example #19
Source File: ABuNDRsi.py    From abu with GNU General Public License v3.0 5 votes vote down vote up
def _calc_rsi_from_ta(prices, time_period=14):
    """
    使用talib计算rsi, 即透传talib.RSI计算结果
    :param prices: 收盘价格序列,pd.Series或者np.array
    :param time_period: rsi的N日参数, 默认14
    """

    import talib
    if isinstance(prices, pd.Series):
        prices = prices.values
    rsi = talib.RSI(prices, timeperiod=time_period)
    return rsi


# noinspection PyTypeChecker 
Example #20
Source File: features.py    From trading-server with GNU General Public License v3.0 5 votes vote down vote up
def RSI(self, bars, timeperiod: int = 14):
        """
        Return RSI for given time series.
        """

        self.check_bars_type(bars)

        rsi = ta.RSI(bars['close'], timeperiod)

        return rsi 
Example #21
Source File: srsi.py    From jesse with MIT License 5 votes vote down vote up
def srsi(candles: np.ndarray, period=14, period_stoch=14, k=3, d=3, source_type="close", sequential=False) -> StochasticRSI:
    """
    Stochastic RSI

    :param candles: np.ndarray
    :param period: int - default: 14 - RSI Length
    :param period_stoch: int - default: 14 - Stochastic Length
    :param k: int - default: 3
    :param d: int - default: 3
    :param source_type: str - default: "close"
    :param sequential: bool - default=False

    :return: StochasticRSI(k, d)
    """
    if not sequential and len(candles) > 240:
        candles = candles[-240:]

    source = get_candle_source(candles, source_type=source_type)
    rsi_np = talib.RSI(source, timeperiod=period)
    rsi_np = rsi_np[np.logical_not(np.isnan(rsi_np))]
    fast_k, fast_d = ti.stoch(rsi_np, rsi_np, rsi_np, period_stoch, k, d)

    if sequential:
        fast_k = np.concatenate((np.full((candles.shape[0] - fast_k.shape[0]), np.nan), fast_k), axis=0)
        fast_d = np.concatenate((np.full((candles.shape[0] - fast_d.shape[0]), np.nan), fast_d), axis=0)
        return StochasticRSI(fast_k, fast_d)
    else:
        return StochasticRSI(fast_k[-1], fast_d[-1]) 
Example #22
Source File: strategyAtrRsi.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def onInit(self):
        """初始化策略(必须由用户继承实现)"""
        self.writeCtaLog(u'%s策略初始化' %self.name)
    
        # 初始化RSI入场阈值
        self.rsiBuy = 50 + self.rsiEntry
        self.rsiSell = 50 - self.rsiEntry

        # 载入历史数据,并采用回放计算的方式初始化策略数值
        initData = self.loadBar(self.initDays)
        for bar in initData:
            self.onBar(bar)

        self.putEvent()

    #---------------------------------------------------------------------- 
Example #23
Source File: talib_numpy.py    From QUANTAXIS with MIT License 5 votes vote down vote up
def TA_MACD(prices:np.ndarray, 
            fastperiod:int=12, 
            slowperiod:int=26, 
            signalperiod:int=9) -> np.ndarray:
    '''
    参数设置:
        fastperiod = 12
        slowperiod = 26
        signalperiod = 9

    返回: macd - dif, signal - dea, hist * 2 - bar, delta
    '''
    macd, signal, hist = talib.MACD(prices, 
                                    fastperiod=fastperiod, 
                                    slowperiod=slowperiod, 
                                    signalperiod=signalperiod)
    hist = (macd - signal) * 2
    delta = np.r_[np.nan, np.diff(hist)]
    return np.c_[macd, signal, hist, delta]


# 定义RSI函数 
Example #24
Source File: talib_numpy.py    From QUANTAXIS with MIT License 5 votes vote down vote up
def TA_RSI(prices:np.ndarray, 
           timeperiod:int=12) -> np.ndarray:
    '''
    参数设置:
        timeperiod = 12

    返回: ma
    '''
    rsi = talib.RSI(prices, timeperiod=timeperiod)
    delta = np.r_[np.nan, np.diff(rsi)]
    return np.c_[rsi, delta]


# 定义RSI函数 
Example #25
Source File: ta_indicator_mixin.py    From strategy with Apache License 2.0 5 votes vote down vote up
def rsi(self, sym, frequency, *args, **kwargs):
        if not self.kbars_ready(sym, frequency):
            return []

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

        avg_prices = (highs + lows + closes) / 3.0

        return ta.RSI(avg_prices, *args, **kwargs) 
Example #26
Source File: technical_indicator.py    From NowTrade with MIT License 5 votes vote down vote up
def __str__(self):
        return 'RSI(data=%s, period=%s)' %(self.data, self.period) 
Example #27
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.RSI(data_frame[self.data].values, timeperiod=self.period)
        except KeyError:
            data_frame[self.value] = np.nan 
Example #28
Source File: ta.py    From dash-technical-charting with MIT License 5 votes vote down vote up
def add_RSI(self, timeperiod=14,
            type='line', color='secondary', **kwargs):
    """Relative Strength Index."""

    if not self.has_close:
        raise Exception()

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

    name = 'RSI({})'.format(str(timeperiod))
    self.sec[name] = dict(type=type, color=color)
    self.ind[name] = talib.RSI(self.df[self.cl].values,
                               timeperiod) 
Example #29
Source File: technical_indicators.py    From 51bitqunt with MIT License 5 votes vote down vote up
def calculate_cmi_indicator(df):  # RSI

    cmi_period = 30
    cmi_ma_period = 10
    roc = df['close'].diff(cmi_period)
    h1 = ta.MAX(df['high'], cmi_period) - ta.MIN(df['low'], cmi_period)
    cmi = abs(roc / h1) * 100
    cmi_ma = ta.MA(cmi, cmi_ma_period)  # rolling.
    return cmi_ma 
Example #30
Source File: array_manager.py    From 51bitqunt with MIT License 5 votes vote down vote up
def rsi(self, n, array=False):
        """
        Relative Strenght Index (RSI).
        """
        result = talib.RSI(self.close, n)
        if array:
            return result
        return result[-1]