这是计算移动平均线的有效方法吗?

Is this an efficient way to compute a moving average?

我有一些 {open|high|low|close} 市场数据。我想根据每行的 close 值计算简单移动平均线。

我环顾四周,找不到执行此操作的简单方法。我已经通过以下方法计算了它。我想知道有没有更好的方法:

data = get_data_period_symbol('1h', 'EURUSD')

empty_list = np.zeros(len(data))

data['SMA10'] = empty_list
ma = 10

for i in range(ma-1, len(data)):
    vals = data['<CLOSE>'][i-(ma-1):i+1].tolist()
    mean = np.average(vals)
    index = data.index[i]
    data.set_value(index, 'SMA10', mean)
data['SMA10'] = pd.rolling_mean(data['<CLOSE>'][:], 10)

这是我最初找到的解决方案,但是您收到一条警告,说它已被弃用

因此:

data['SMA10'] = data['<CLOSE>'][:].rolling(window=10, center=False).mean()

您可以使用 np.convolve as suggested in this answer。所以这样的事情应该有效:

data.loc[ma-1:, "SMA10"] = np.convolve(data["<CLOSE>"], np.ones((ma,))/ma, mode="valid")

PS: 我刚刚看到你自己的答案,这实际上是一个更好的解决方案!

Pandas 提供了您需要的所有工具。 假设您的数据按时间索引:

data['SMA10'] = data['<close>'].rolling(window=10).mean()

瞧。

编辑: 我想只需注意较新的 api 用法即可。引用自 Pandas docs:

Warning Prior to version 0.18.0, pd.rolling_, pd.expanding_, and pd.ewm* were module level functions and are now deprecated. These are replaced by using the Rolling, Expanding and EWM. objects and a corresponding method call.