从pandas数据帧计算RSI

时间:2016-09-26 11:54:28

标签: python pandas dataframe division

我从外汇市场获得了一个有价值的df,我试图在数据框中为df中的每一行输入RSI,相对强弱指数(10)。

df.head()
Out[3]: 
        Date      Time     Open     High      Low    Close  Volume  OpenInt
0 2016-09-16  00:05:00  0.75183  0.75186  0.75160  0.75161       0        0
1 2016-09-16  00:10:00  0.75156  0.75156  0.75145  0.75149       0        0
2 2016-09-16  00:15:00  0.75156  0.75166  0.75152  0.75165       0        0
3 2016-09-16  00:20:00  0.75164  0.75165  0.75150  0.75156       0        0
4 2016-09-16  00:25:00  0.75156  0.75174  0.75153  0.75156       0        0

RSI是一个指示器,可以告诉您何时产品超卖或超买; RSI = 100-100 /(1 + RS)其中RS是给定时间帧中上行周期的平均增益/给定时间帧中下行周期的平均损失。就我而言,时间范围是10。

df.change = df.Open - df.Close # find out if there is a gain or a loss

df.gain = df.change [df.change > 0] #column of gain

df.loss = df.change [df.change < 0]# column of loss

df.again = df.gain.rolling(center=False,window=10) #find the average gain in the last 10 periods 

df.aloss = df.loss.rolling(center=False,window=10) #find the average loss in the last 10 periods

现在是麻烦开始的地方;我需要获得RS:

df.rs = df.again/df.aloss

TypeErrorTraceback (most recent call last)
<ipython-input-13-2886bcd78f42> in <module>()
----> 1 df.rs = df.again/df.aloss

TypeError: unsupported operand type(s) for /: 'Rolling' and 'Rolling'

谢谢你的帮助, 克罗诺斯

修改

df.gain.head(6)
Out[31]: 
0    0.00022
1    0.00007
3    0.00008
5    0.00002
7    0.00003
8    0.00002

df.loss.head(6)
Out[32]: 
2    -0.00009
6    -0.00019
9    -0.00013
14   -0.00002
15   -0.00011
20   -0.00008
dtype: float64

2 个答案:

答案 0 :(得分:2)

import $ from 'jquery';

答案 1 :(得分:0)

对于平均损益,开盘价无关紧要。 它必须始终以收盘价与先前烛棒的收盘价进行比较来计算。

def rsiFunc(prices, n=14):
deltas = np.diff(prices)
seed = deltas[:n+1]
up = seed[seed>=0].sum()/n
down = -seed[seed<0].sum()/n
rs = up/down
rsi = np.zeros_like(prices)
rsi[:n] = 100. - 100./(1.+rs)

for i in range(n, len(prices)):
    delta = deltas[i-1] # cause the diff is 1 shorter

    if delta>0:
        upval = delta
        downval = 0.
    else:
        upval = 0.
        downval = -delta

    up = (up*(n-1) + upval)/n
    down = (down*(n-1) + downval)/n

    rs = up/down
    rsi[i] = 100. - 100./(1.+rs)

return rsi

我从https://github.com/mtamer/python-rsi/blob/master/Stock%20Screener/rsi.py拿走