pandas 使用熊猫滚动法计算加权移动平均线

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/39742797/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 02:06:03  来源:igfitidea点击:

Calculating weighted moving average using pandas Rolling method

pythonpandasmoving-averageweighted-averagetechnical-indicator

提问by anilca

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

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_typeparameter. But I'm not sure which one I have to choose.

使用滚动函数是否可以计算加权移动平均值?正如我在文档中读到,我认为我必须传递win_type参数。但我不确定我必须选择哪一个。

Here is a definitionfor weighted moving average.

这是加权移动平均线的定义

Thanks in advance,

提前致谢,

回答by Dthal

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:

是的,pandas 的那部分确实没有很好的记录。如果您不使用标准窗口类型之一,我认为您可能必须使用rolling.apply()。我戳了一下它并让它起作用:

>>> 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

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.

我认为这是正确的。关闭的原因是 rolling.apply 的签名是rolling.apply(func, *args, **kwargs),所以如果你直接将它们发送到函数,权重会被元组解包,除非你将它们作为 1-tuple 发送(wts,),但这很奇怪。