如何使用NumPy计算移动平均线? [英] How to calculate moving average using NumPy?

查看:168
本文介绍了如何使用NumPy计算移动平均线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎没有函数可以简单地计算numpy/scipy上的移动平均值,从而导致

There seems to be no function that simply calculates the moving average on numpy/scipy, leading to convoluted solutions.

我的问题有两个:

推荐答案

如果您只想要直接的非加权移动平均值,则可以使用np.cumsum轻松实现,可能是 比基于FFT的方法快:

If you just want a straightforward non-weighted moving average, you can easily implement it with np.cumsum, which may be is faster than FFT based methods:

编辑更正了Bean在代码中发现的错误的一对一错误索引. 编辑

EDIT Corrected an off-by-one wrong indexing spotted by Bean in the code. EDIT

def moving_average(a, n=3) :
    ret = np.cumsum(a, dtype=float)
    ret[n:] = ret[n:] - ret[:-n]
    return ret[n - 1:] / n

>>> a = np.arange(20)
>>> moving_average(a)
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.,  11.,
        12.,  13.,  14.,  15.,  16.,  17.,  18.])
>>> moving_average(a, n=4)
array([  1.5,   2.5,   3.5,   4.5,   5.5,   6.5,   7.5,   8.5,   9.5,
        10.5,  11.5,  12.5,  13.5,  14.5,  15.5,  16.5,  17.5])

所以我想答案是:它真的很容易实现,也许numpy的专用功能已经有点肿了.

So I guess the answer is: it is really easy to implement, and maybe numpy is already a little bloated with specialized functionality.

这篇关于如何使用NumPy计算移动平均线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆