用 pandas 滚动法计算加权移动平均值 [英] Calculating weighted moving average using pandas Rolling method
问题描述
我计算简单的移动平均线:
I calculate simple moving average:
def sma(data_frame, length=15):
# TODO: Be sure about default values of length.
smas = data_frame.Close.rolling(window=length, center=False).mean()
return smas
使用滚动功能可以计算加权移动平均值吗?当我阅读文档中的 时,我认为我必须传递 win_type 参数.但是我不确定我必须选择哪一个.
Using the rolling function is it possible to calculate weighted moving average? As I read in the documentation, I think that I have to pass win_type parameter. But I'm not sure which one I have to choose.
Here is a definition for weighted moving average.
预先感谢
推荐答案
是的,关于熊猫的那部分确实没有得到很好的记录.我认为,如果您未使用标准窗口类型之一,则可能必须使用rolling.apply().我戳了一下,并使它起作用:
Yeah, that part of pandas really isn't very well documented. I think you might have to use rolling.apply() if you aren't using one of the standard window types. I poked at it and got this to work:
>>> import numpy as np
>>> import pandas as pd
>>> d = pd.DataFrame({'a':range(10), 'b':np.random.random(size=10)})
>>> d.b = d.b.round(2)
>>> d
a b
0 0 0.28
1 1 0.70
2 2 0.28
3 3 0.99
4 4 0.72
5 5 0.43
6 6 0.71
7 7 0.75
8 8 0.61
9 9 0.14
>>> wts = np.array([-1, 2])
>>> def f(w):
def g(x):
return (w*x).mean()
return g
>>> d.rolling(window=2).apply(f(wts))
a b
0 NaN NaN
1 1.0 0.560
2 1.5 -0.070
3 2.0 0.850
4 2.5 0.225
5 3.0 0.070
6 3.5 0.495
7 4.0 0.395
8 4.5 0.235
9 5.0 -0.165
我认为是正确的.之所以关闭,是因为rolling.apply的签名是rolling.apply(func, *args, **kwargs)
,因此,如果直接将权重直接发送给函数,则权重会被拆成元组,除非以1-tuple (wts,)
的形式发送权重,但是太奇怪了.
I think that is correct. The reason for the closure there is that the signature for rolling.apply is rolling.apply(func, *args, **kwargs)
, so the weights get tuple-unpacked if you just send them to the function directly, unless you send them as a 1-tuple (wts,)
, but that's weird.
这篇关于用 pandas 滚动法计算加权移动平均值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!