Relative Strength Index in python pandas

前端 未结 12 1454
生来不讨喜
生来不讨喜 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条回答
  •  Happy的楠姐
    2020-12-07 18:08

    My answer is tested on StockCharts sample data.

    [StockChart RSI info][1]http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:relative_strength_index_rsi

    def RSI(series, period):
        delta = series.diff().dropna()
        u = delta * 0
        d = u.copy()
        u[delta > 0] = delta[delta > 0]
        d[delta < 0] = -delta[delta < 0]
        u[u.index[period-1]] = np.mean( u[:period] ) #first value is sum of avg gains
        u = u.drop(u.index[:(period-1)])
        d[d.index[period-1]] = np.mean( d[:period] ) #first value is sum of avg losses
        d = d.drop(d.index[:(period-1)])
        rs = pd.stats.moments.ewma(u, com=period-1, adjust=False) / \
             pd.stats.moments.ewma(d, com=period-1, adjust=False)
        return 100 - 100 / (1 + rs)
    
    
    #sample data from StockCharts
    data = pd.Series( [ 44.34, 44.09, 44.15, 43.61,
                        44.33, 44.83, 45.10, 45.42,
                        45.84, 46.08, 45.89, 46.03,
                        45.61, 46.28, 46.28, 46.00,
                        46.03, 46.41, 46.22, 45.64 ] )
    print RSI( data, 14 )
    
    #output
    14    70.464135
    15    66.249619
    16    66.480942
    17    69.346853
    18    66.294713
    19    57.915021
    

提交回复
热议问题