[英]Is this an efficient way to compute a moving average?
I've some {open|high|low|close}
market data. 我有一些
{open|high|low|close}
市场数据。 I want to compute a Simple Moving Average from the close
value of each row. 我想根据每一行的
close
价来计算简单移动平均线。
I've had a look around and couldn't find a simple way to do this. 我四处张望,找不到一种简单的方法来做到这一点。 I've computed it via the below method.
我已经通过以下方法进行了计算。 I want to know if there is a better way:
我想知道是否有更好的方法:
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)
Pandas provides all the tools you'll need for this kind of thing. Pandas提供了您需要的所有工具。 Assuming you have your data indexed by time:
假设您已按时间对数据进行索引:
data['SMA10'] = data['<close>'].rolling(window=10).mean()
Voila. 瞧
Edit: I suppose just note the newer api usage. 编辑:我想只是注意较新的api用法。 Quoting from the Pandas docs :
引用熊猫文档 :
Warning Prior to version 0.18.0, pd.rolling_ , pd.expanding_ , and pd.ewm* were module level functions and are now deprecated.
警告在版本0.18.0之前,pd.rolling_ ,pd.expanding_和pd.ewm *是模块级功能,现已弃用。 These are replaced by using the Rolling, Expanding and EWM.
可以使用滚动,扩展和EWM来替换它们。 objects and a corresponding method call.
对象和相应的方法调用。
data['SMA10'] = pd.rolling_mean(data['<CLOSE>'][:], 10)
Was my original found solution, however you get a warning saying it's deprecated 是我最初找到的解决方案,但是您收到警告说它已过时
Therefore: 因此:
data['SMA10'] = data['<CLOSE>'][:].rolling(window=10, center=False).mean()
You can use np.convolve
as suggested in this answer . 您可以按照此答案中的建议使用
np.convolve
。 So something like this should work: 所以这样的事情应该工作:
data.loc[ma-1:, "SMA10"] = np.convolve(data["<CLOSE>"], np.ones((ma,))/ma, mode="valid")
PS: I just saw your own answer, which is actually a much nicer solution! PS:我刚刚看到了您自己的答案,这实际上是一个更好的解决方案!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.