0

我正在尝试使用以下公式计算 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 = u.ewm(com=period-1, adjust=False).mean() / \
     d.ewm(com=period-1, adjust=False).mean()
     return 100 - 100 / (1 + rs)


#sample data 
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 ] )
RSI(data,10)

追溯:

TypeError                                 Traceback (most recent call last)
<ipython-input-27-3515374ab7b7> in <module>
     20                     45.61, 46.28, 46.28, 46.00,
     21                     46.03, 46.41, 46.22, 45.64 ] )
---> 22 RSI(data,10)

<ipython-input-27-3515374ab7b7> in RSI(series, period)
      3      u = delta * 0
      4      d = u.copy()
----> 5      u[delta > 0] = delta[delta > 0]
      6      d[delta < 0] = -delta[delta < 0]
      7      u[u.index[period-1]] = np.mean( u[:period] ) #first value is sum of avg gains

TypeError: only size-1 arrays can be converted to Python scalars
4

0 回答 0