I've some {open|high|low|close}
market data. I want to compute a Simple Moving Average from the close
value of each row.
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. 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. 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. These are replaced by using the Rolling, Expanding and 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 . 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!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.