Working with time series in Pandas/Python
<p>I have the following data:</p>

<pre><code>            AdjClose     Chg     RM    Target
date                                       
2014-01-16  41.733862  0.002045   0     NaN
2014-01-17  41.695141 -0.000928   1     NaN
2014-01-21  42.144309  0.010773   1     NaN
2014-01-22  41.803561 -0.008085   1     NaN
2014-01-23  41.640931 -0.003890   0     3.0
2014-01-24  41.586721 -0.001302   0     3.0
2014-01-27  41.323416 -0.006331   0     2.0
2014-01-28  41.710630  0.009370   1     2.0
2014-01-29  41.780328  0.001671   0     1.0
2014-01-30  42.701896  0.022057   0     1.0
</code></pre>

<p>I'm sure there is an easy way to do this, but I have yet to figure it out. For each day, I need to see how many times over the previous n days, has there been an up/down or down/up movement.</p>

<p>My ugly solution was to do the following for a 5day Target:</p>

<pre><code>dd['RM']=0
dd['RM'][((dd['Chg']&gt;0) &amp; (dd['Chg'].shift(1)&lt;0))|
         ((dd['Chg']&lt;0) &amp; (dd['Chg'].shift(1)&gt;0))] = 1
dd['Target']=pd.rolling_sum(dd['RM'],window=5)
</code></pre>

<p>and then just do a rolling_sum over the previous n days.</p>

<p>I would love some help with a more elegant solution.  Thank you.</p>

<p>I would do a <code>rolling_sum()</code> exactly as you have done, though I think the up/down and down/up are easily measured as <em>when the sign changes</em>:</p>

<pre><code>dd['RM'] = np.int64(np.sign(dd['Chg']) != np.sign(dd['Chg'].shift(1)))
dd['RM'].values[0] = 0
</code></pre>

python pandas