如何在 Python 中实现良好的移动平均线

How to implement a good moving average in Python


我正在做一些研究,我正在根据这个数学表达式在 Python 中实现移动平均线:

其中:n = 样本和 W1 = Window

我是这样实现的:

def movingAverage(signal, window):

   sum = 0
   mAver = []
   k = int((window-1)/2)

   for i in np.arange(k, len(signal)-k):
       for ii in np.arange(i-k, i+k):
           sum = sum + signal[ii]
       #end-for
       mAver.append(sum / window)
       sum = 0
   #end-for

   zeros = [0]*k
   mAver = zeros + mAver + zeros

   return mAver

效果很好。但我正在尝试发现一些实现 k 变体的方法,以最大限度地减少开始和结束时丢失的信号(现在我使用的是带零的列表)。


有人可以帮助我吗?

您可以只使用 Pandas 并指定 center=True 作为您的移动平均线。

import numpy as np
import pandas as pd

np.random.seed(0)

s = pd.Series(np.random.randn(7)).round(1)
moving_avg = s.rolling(window=3).mean(center=True)
>>> pd.concat([s, moving_avg.round(2)], axis=1).rename(columns={0: 'signal', 1: 'MA'})
   signal    MA
0     1.8   NaN
1     0.4  1.07  # 1.07 = (1.8 + 0.4 + 1.0) / 3
2     1.0  1.20  # 1.20 = (0.4 + 1.0 + 2.2) / 3
3     2.2  1.70
4     1.9  1.03
5    -1.0  0.63
6     1.0   NaN

当时我找到了下面的代码:

def moving_average(samples, wind_len=1000):
    wind_len = int(wind_len)
    cumsum_samples = np.cumsum(samples)
    cumsum_diff = cumsum_samples[wind_len:] - cumsum_samples[:-wind_len]
    samples_average = cumsum_diff / float(wind_len)
    return samples_average

def my_cumsum(samples):
    for ind in range(1, len(samples)):
       samples[ind] = samples[ind] + samples[ind - 1]

您可以使用全 1 抽头的过滤器

import scipy as sp
import scipy.signal as sig

h = sp.ones(10)/10
y = sig.lfilter(h, 1, x)