Notebook
In [24]:
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import talib
In [25]:
ma_length = 200
In [26]:
# Get some daily pricing to demo.
day_pricing = get_pricing('SPY', start_date='2019-01-18', end_date='2020-01-02')
day_pricing['close_price'][-10:]
Out[26]:
2019-12-18 00:00:00+00:00    318.007
2019-12-19 00:00:00+00:00    319.340
2019-12-20 00:00:00+00:00    321.120
2019-12-23 00:00:00+00:00    321.220
2019-12-24 00:00:00+00:00    321.260
2019-12-26 00:00:00+00:00    322.910
2019-12-27 00:00:00+00:00    322.860
2019-12-30 00:00:00+00:00    321.100
2019-12-31 00:00:00+00:00    321.890
2020-01-02 00:00:00+00:00    324.840
Freq: C, Name: close_price, dtype: float64

Wilder's MA

Wilder EMA formula = price today K + EMA yesterday (1-K)

(where K =1/N and N = the number of periods)

In [27]:
def WildersMA(closes, length):
    wma = np.zeros(len(closes))
    k = 1.0/length
    
    for i in range(0, len(closes)):
        if i < 1:
            wma[i] = closes[i]
        else:
            wma[i] = closes[i]*k + np.roll(wma, 1)[i]*(1-k)

    return wma            
In [28]:
wma = WildersMA(day_pricing['close_price'], ma_length)
wma = pd.Series(wma)
wma.index = day_pricing.index

Plotting

In [29]:
plt.figure(1)                # the first figure
### upper window ###
plt.subplot(311)
day_pricing['close_price'].plot()
wma.plot()
Out[29]:
<matplotlib.axes._subplots.AxesSubplot at 0x7f7496121390>