title: Calculating Kaufman's Efficiency Ratio in Python with Pandas?
body: <p>I'm trying to implement the Kaufman Efficiency Ratio (ER) in Python with Pandas.</p>
  
  <p>In a Pandas DataFrame, I have two columns:</p>
  
  <ol>
  <li>Date</li>
  <li>Closing Price of a stock (the German DAX index, ^GDAXI, in this example):</li>
  </ol>
  
  <pre>
      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
  </pre>
  
  <p>What I need is a third column that includes the ER for a given period n.</p>
  
  <p>Definition of the ER:</p>
  
  <pre><code>ER = Direction / Volatility
  </code></pre>
  
  <p>Where:</p>
  
  <pre><code>Direction = ABS (Close – Close[n])
  Volatility = n * ∑ (ABS(Close – Close[1]))
  n = The efficiency ratio period.
  </code></pre>
  
  <p>Here is an example of a n=3 period ER (taken from <a href="http://etfhq.com/blog/2011/02/07/kaufmans-efficiency-ratio/" rel="nofollow noreferrer">http://etfhq.com/blog/2011/02/07/kaufmans-efficiency-ratio/</a>):</p>
  
  <p><a href="https://i.stack.imgur.com/Kopgf.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Kopgf.gif" alt="ER-Calculation"></a></p>
  
  <p>What I'm struggeling with is how to do this in Python with Pandas?
  In the end, my dataframe should look like this, according to the calculation above:</p>
  
  <pre>
  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
  </pre>
  
  <p>How do I make Pandas to look back at the previous n rows for the calculation needed for the ER? </p>
  
  <p>Any help is greatly appreciated!
  Thank you in advance.
  Dirk</p>