1

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)
user3666197
  • 1
  • 6
  • 50
  • 92
cardycakes
  • 431
  • 1
  • 4
  • 12
  • 3
    Are you looking for [`rolling`](http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.rolling.html)? – Ami Tavory Sep 04 '16 at 13:33
  • See this SO [thread](http://stackoverflow.com/questions/13728392/moving-average-or-running-mean) for efficient rolling mean solutions. – Daniel Sep 06 '16 at 09:20

3 Answers3

4

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.

ayhan
  • 70,170
  • 20
  • 182
  • 203
binaryaaron
  • 651
  • 7
  • 14
1
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()
cardycakes
  • 431
  • 1
  • 4
  • 12
0

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!

Community
  • 1
  • 1
jotasi
  • 5,077
  • 2
  • 29
  • 51