Brandon Nova
Brandon Nova

Reputation: 31

Relative Strength Index calculation using pandas

I am trying to calculate relative strength index (RSI) using pandas and can't seem to properly adapt a solution provided here. Why isn't this returning a RSI series?

import pandas_datareader.data as web
import datetime
start = datetime.datetime(2018, 2, 8)
end = datetime.datetime(2019, 2, 8)
stock = 'TNA'
price = web.DataReader(stock,'yahoo', start, end)

n = 14

def RSI(series):    
    delta = series.diff()
    u = delta * 0 
    d = u.copy()
    i_pos = delta > 0
    i_neg = delta < 0
    u[i_pos] = delta[i_pos]
    d[i_neg] = delta[i_neg]
    rs = moments.ewma(u, span=27) / moments.ewma(d, span=27)
    return 100 - 100 / (1 + rs)

print(rsi(price, n))

Upvotes: 0

Views: 4648

Answers (1)

dubbbdan
dubbbdan

Reputation: 2720

Here is a shot in the dark because you did not provide very much context.

pandas.stats.moment.ewma is no longer supported in 0.23.0. Exponentially weighed windows are now achieved using pd.Series.ewm. This returns exponentially-weighted-windows object window object that cannot be used in any sort of equation without providing a method for the rolling window. Here is a list of the available methods:

rs.agg         rs.apply       rs.count       rs.exclusions  rs.max         rs.median      rs.name        rs.skew        r.sum
rs.aggregate   rs.corr        rs.cov         rs.kurt        rs.mean        rs.min         rs.quantile    rs.std         rs.var

I assume you copied the function above from here, which did not even seem to answer the OP. If you wanted to do this analysis with the series price.Close with span n and compute the mean of each exponentially weighted window:

import pandas_datareader.data as web
import datetime
import pandas as pd

ewma = pd.Series.ewm
start = datetime.datetime(2018, 2, 8)
end = datetime.datetime(2019, 2, 8)
stock = 'TNA'
price = web.DataReader(stock,'yahoo', start, end)

n = 14

def RSI(series,n):    
    delta = series.diff()
    u = delta * 0 
    d = u.copy()
    i_pos = delta > 0
    i_neg = delta < 0
    u[i_pos] = delta[i_pos]
    d[i_neg] = delta[i_neg]
    rs = ewma(u, span=n).mean() / ewma(d, span=n).mean()
    return 100 - 100 / (1 + rs)

print(RSI(price.Close,n))

Upvotes: 1

Related Questions