Skip to main content
 首页 » 编程设计

python之从 Pandas 数据帧计算 RSI

2024年10月17日7insus

<分区>

我有一个来自外汇市场的值(value) 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 是给定时间范围内上涨周期的平均 yield /给定时间范围内下跌周期的平均损失。在我的例子中,时间范围是 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