2013-04-22 55 views
2

我有一個python DataFrame包含一些財務數據,我試圖創建一些技術指標。我想弄清楚如何使用移動窗口函數來加速過程,而不是逐個元素。對於每個索引,我想返回最近30天的最大索引。我已經實現了一個元素的元素的解決方案,但你可以想象它是非常慢。在python中滾動idxmax()?

for s_sym in ls_symbols: 
     for i in range(refresh, len(ldt_timestamps)): 
      #Aroon-Up = ((period - Days Since High)/period) x 100 Aroon-Down = ((period - Days Since Low)/peiod) x 100''' 
      whrmax = df_close[s_sym].ix[ldt_timestamps[i-uplen:i]].idxmax() 
      maxaway = (df_close[s_sym].ix[whrmax : ldt_timestamps[i-1]]).count() 
      aroonup = ((uplen - maxaway)/uplen) * 100 

      whrmin = df_close[s_sym].ix[ldt_timestamps[i-dnlen:i]].idxmin() 
      minaway = df_close[s_sym].ix[whrmin : ldt_timestamps[i-1]].count() 
      aroondn = ((dnlen - minaway)/dnlen) * 100 

如何創建自定義滾動窗口功能?

回答

3

請參閱該文檔在:

http://pandas.pydata.org/pandas-docs/dev/computation.html#moving-rolling-statistics-moments

而在一些很好的例子:

http://pandas.pydata.org/pandas-docs/dev/cookbook.html#grouping

In [18]: df = DataFrame(randn(1000,4),index=pd.date_range('20000101',periods=1000), 
       columns=list('ABCD')) 

In [19]: pandas.stats.moments.rolling_apply(df,30,lambda x: Series(x).idxmax()) 
Out[19]: 
<class 'pandas.core.frame.DataFrame'> 
DatetimeIndex: 1000 entries, 2000-01-01 00:00:00 to 2002-09-26 00:00:00 
Freq: D 
Data columns (total 4 columns): 
A 971 non-null values 
B 971 non-null values 
C 971 non-null values 
D 971 non-null values 
dtypes: float64(4) 

In [47]: pandas.stats.moments.rolling_apply(df,30,lambda x: Series(x).idxmax()).tail(30) 
Out[47]: 
      A B C D 
2002-08-28 24 3 26 21 
2002-08-29 23 2 25 20 
2002-08-30 22 1 24 19 
2002-08-31 21 0 23 18 
2002-09-01 20 6 29 17 
2002-09-02 19 5 28 16 
2002-09-03 18 4 27 15 
2002-09-04 17 3 26 14 
2002-09-05 16 2 25 13 
2002-09-06 15 1 24 12 
2002-09-07 14 0 23 11 
2002-09-08 13 13 22 10 
2002-09-09 12 12 21 9 
2002-09-10 11 11 20 8 
2002-09-11 10 10 19 7 
2002-09-12 9 9 18 6 
2002-09-13 8 8 17 5 
2002-09-14 7 7 16 4 
2002-09-15 6 6 15 3 
2002-09-16 5 5 14 2 
2002-09-17 4 4 13 1 
2002-09-18 3 3 12 0 
2002-09-19 2 2 11 11 
2002-09-20 1 1 10 10 
2002-09-21 0 0 9 9 
2002-09-22 27 25 8 8 
2002-09-23 26 24 7 7 
2002-09-24 25 23 6 6 
2002-09-25 24 22 5 5 
2002-09-26 23 29 4 4 

僅供參考,你可能幾乎肯定是最好只使用rolling_max(df,30)得到在特定範圍內的最大值,這就是我收集到的結果

+0

這個工作完美,我不相信它是如此簡單..我想要索引來計算從高/低的百分比範圍。 – 2013-04-23 01:21:14

+0

這很有幫助。 @Jeff,我正在做類似的事情,idxmax/min以及max/min對於確定止損在利潤目標之前是否有效很有用。 – jxstanford 2015-07-19 23:31:23