Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Best way to implement RSI without using talib

I have been trying for hours to implement talib.RSI and failing. I have been trying to hack an algorithm that uses

context.stocks = symbols('IWM','RWM')  
...
prices = history(15, '1d', 'price')  
rsi = prices.apply(talib.RSI, timeperiod=14).iloc[-1]  

but I haven't been able to make that work for me, especially while using data.history method instead of just history (which is deprecated).

Does anyone know of any non-talib solutions to calculate RSI?

Thanks!

2 responses

Jim,

talib RSI is working for me

import talib

def initialize(context):  
    context.stock = symbol('SPY')  
    schedule_function(trade, date_rules.every_day(), time_rules.market_close(minutes = 15))  
def trade(context, data):  
    stock=context.stock  
    W = 50  
    UB = 65  
    LB =UB*0.8  
    C = data.history(stock, 'price',W+2, '1d')  
    # L = data.history(stock, 'low',W+2, '1d')  
    # H = data.history(stock, 'high',W+2, '1d')

    rsi_one = talib.RSI(C, timeperiod=W)[-1]  
    rsi_two = talib.RSI(C, timeperiod=W)[-2]

    record(RSI1=rsi_one, RSI2=rsi_two, ub=UB)  

Or use this:

#Relative Strength Index  
def RSI(df, n):  
    i = 0  
    UpI = [0]  
    DoI = [0]  
    while i + 1 <= df.index[-1]:  
        UpMove = df.get_value(i + 1, 'High') - df.get_value(i, 'High')  
        DoMove = df.get_value(i, 'Low') - df.get_value(i + 1, 'Low')  
        if UpMove > DoMove and UpMove > 0:  
            UpD = UpMove  
        else: UpD = 0  
        UpI.append(UpD)  
        if DoMove > UpMove and DoMove > 0:  
            DoD = DoMove  
        else: DoD = 0  
        DoI.append(DoD)  
        i = i + 1  
    UpI = pd.Series(UpI)  
    DoI = pd.Series(DoI)  
    PosDI = pd.Series(pd.ewma(UpI, span = n, min_periods = n - 1))  
    NegDI = pd.Series(pd.ewma(DoI, span = n, min_periods = n - 1))  
    RSI = pd.Series(PosDI / (PosDI + NegDI), name = 'RSI_' + str(n))  
    df = df.join(RSI)  
    return df