Pandas 不同 window 大小的滚动平均值 - 不同周期的移动平均值

Pandas groupby rolling mean with different window size - moving average with different period

问题陈述:尝试使用 Pandas groupby 对每个组使用不同的周期来计算简单移动平均线。

示例: 我有 S&P E-mini 的连续合约,试图找到一个简单的移动平均线,但想使用不同的周期。在下面的示例中,我想计算 C1 的 5 天 SMA、C2 的 7 天 SMA、C3 的 10 天 SMA 等。我从配置中获取周期值。

Date          |Contract| Close       | Period| SMA 
3/23/2020     | C1     | 2210.50     | 5     | 2335.58 
3/22/2020     | C1     | 2191.50     | 5     | 2374.73 
3/20/2020     | C1     | 2389.00     | 5     | 2473.21 
3/19/2020     | C1     | 2401.40     | 5     | 2489.19 
3/18/2020     | C1     | 2485.50     | 5     | 2502.69 
3/17/2020     | C1     | 2406.25     | 5     | 2553.65 
3/16/2020     | C1     | 2683.90     | 5     |
3/15/2020     | C1     | 2468.90     | 5     |
3/13/2020     | C1     | 2468.90     | 5     |
3/12/2020     | C1     | 2740.30     | 5     |
…..
3/23/2020     | C2     | 2219.45     | 7     | 2403.69
3/22/2020     | C2     | 2199.30     | 7     | 2440.39
3/20/2020     | C2     | 2396.50     | 7     | 2480.07
3/19/2020     | C2     | 2410.20     | 7     | 2530.51
3/18/2020     | C2     | 2493.90     | 7     |
3/17/2020     | C2     | 2413.90     | 7     |
3/16/2020     | C2     | 2692.60     | 7     |
3/15/2020     | C2     | 2476.35     | 7     |
3/13/2020     | C2     | 2477.05     | 7     |
3/12/2020     | C2     | 2749.55     | 7     |

我试过使用滚动 window,但无法使用 dynamic/custom window 句号。

df['sma'] = df.groupby('Contract')['Close'].rolling(<<period - not able to use>>).mean().reset_index(0,drop=True)

有什么方法可以为window参数使用可配置参数吗?

如果你想保留合同

dict_periods = {"C1": 5, "C2":7, "C3": 10}
period = lambda z: dict_periods[z['Contract'].iloc[0]]
ma = lambda df: df['Close'].rolling(period(df)).mean()
df.groupby('Contract', as_index=False).apply(ma)

否则,回到你的reset_index(0, drop=True)