Relative Strength Index in python pandas

前端 未结 12 1470
生来不讨喜
生来不讨喜 2020-12-07 17:29

I am new to pandas. What is the best way to calculate the relative strength part in the RSI indicator in pandas? So far I got the following:

from pylab impor         


        
12条回答
  •  悲&欢浪女
    2020-12-07 18:02

    You can use rolling_apply in combination with a subfunction to make a clean function like this:

    def rsi(price, n=14):
        ''' rsi indicator '''
        gain = (price-price.shift(1)).fillna(0) # calculate price gain with previous day, first row nan is filled with 0
    
        def rsiCalc(p):
            # subfunction for calculating rsi for one lookback period
            avgGain = p[p>0].sum()/n
            avgLoss = -p[p<0].sum()/n 
            rs = avgGain/avgLoss
            return 100 - 100/(1+rs)
    
        # run for all periods with rolling_apply
        return pd.rolling_apply(gain,n,rsiCalc) 
    

提交回复
热议问题