使用Pandas计算Kaufman在Python中的效率比率?

时间:2016-05-02 10:28:27

标签: python pandas

我试图用Pandas在Python中实现Kaufman效率比(ER)。

在Pandas DataFrame中,我有两列:

  1. 日期
  2. 收盘价格(德国DAX指数,^ GDAXI,在本例中):
  3.     Date        Close
        2016-01-05  10310.10
        2016-01-06  10214.02
        2016-01-07   9979.85
        2016-01-08   9849.34
        2016-01-11   9825.07     
        2016-01-12   9985.43     
        2016-01-13   9960.96     
        2016-01-14   9794.20
    

    我需要的是第三列,包括给定时期的ER。

    ER的定义:

    ER = Direction / Volatility
    

    其中:

    Direction = ABS (Close – Close[n])
    Volatility = n * ∑ (ABS(Close – Close[1]))
    n = The efficiency ratio period.
    

    以下是n = 3期间ER(取自http://etfhq.com/blog/2011/02/07/kaufmans-efficiency-ratio/)的示例:

    ER-Calculation

    我和Pandas在Python中如何做到这一点? 最后,根据上面的计算,我的数据框应如下所示:

    Date        Adj Close   ER(3)
    2016-01-04  10283.44    
    2016-01-05  10310.10    
    2016-01-06  10214.02    
    2016-01-07  9979.85     0.9
    2016-01-08  9849.34     1.0
    2016-01-11  9825.07     1.0
    2016-01-12  9985.43     0.0
    2016-01-13  9960.96     0.5
    2016-01-14  9794.20     0.1
    

    如何让Pandas回顾之前的n行以进行ER所需的计算?

    非常感谢任何帮助! 先感谢您。 德克

1 个答案:

答案 0 :(得分:3)

无需编写滚动功能,只需使用diffrolling_sum

df['direction'] = df['Close'].diff(3).abs()
df['volatility'] = pd.rolling_sum(df['Close'].diff().abs(), 3)

我认为代码几乎是不言自明的。如果您想要解释,请告诉我。

In [11]: df['direction'] / df['volatility']
Out[11]: 
0         NaN
1         NaN
2         NaN
3    1.000000
4    1.000000
5    0.017706
6    0.533812
7    0.087801
dtype: float64

这看起来就像你要找的那样。