简体   繁体   English

用熊猫计算Python中的考夫曼效率比?

[英]Calculating Kaufman's Efficiency Ratio in Python with Pandas?

I'm trying to implement the Kaufman Efficiency Ratio (ER) in Python with Pandas. 我正在尝试使用Pandas在Python中实现考夫曼效率比(ER)。

In a Pandas DataFrame, I have two columns: 在Pandas DataFrame中,我有两列:

  1. Date 日期
  2. Closing Price of a stock (the German DAX index, ^GDAXI, in this example): 股票的收盘价(在此示例中,德国DAX指数^ GDAXI):
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

What I need is a third column that includes the ER for a given period n. 我需要的第三列是给定时间段n的ER。

Definition of the ER: ER的定义:

ER = Direction / Volatility

Where: 哪里:

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

Here is an example of an=3 period ER (taken from http://etfhq.com/blog/2011/02/07/kaufmans-efficiency-ratio/ ): 这是一个= 3期间ER的示例(摘自http://etfhq.com/blog/2011/02/07/kaufmans-efficiency-ratio/ ):

ER-计算

What I'm struggeling with is how to do this in Python with Pandas? 我正在努力的是如何在Python中使用Pandas做到这一点? In the end, my dataframe should look like this, according to the calculation above: 最后,根据上述计算,我的数据框应如下所示:

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

How do I make Pandas to look back at the previous n rows for the calculation needed for the ER? 如何让熊猫回头看前n行,以了解ER所需的计算?

Any help is greatly appreciated! 任何帮助是极大的赞赏! Thank you in advance. 先感谢您。 Dirk 短剑

No need to write a rolling function, just use diff and rolling_sum : 无需编写滚动功能,只需使用diffrolling_sum

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

I think the code is pretty much self-explanatory. 我认为代码几乎是不言自明的。 Please let me know if you would like explanations. 如果您需要解释,请告诉我。

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

This looks like what you're looking for. 这看起来像您要找的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM