November 2019
Beginner
394 pages
10h 31m
English
Let's implement an exponential moving average with 20 days as the number of time periods to compute the average over. We will use a default smoothing factor of 2 / (n + 1) for this implementation. Similar to SMA, EMA also achieves an evening out across normal daily prices. EMA has the advantage of allowing us to weigh recent prices with higher weights than an SMA does, which does uniform weighting.
In the following code, we will see the implementation of the exponential moving average:
num_periods = 20 # number of days over which to averageK = 2 / (num_periods + 1) # smoothing constantema_p = 0ema_values = [] # to hold computed EMA valuesfor close_price in close: if (ema_p == 0): # first observation, ...