Created
January 24, 2021 11:15
-
-
Save timotewb/432317e8dae395f09cf0d9d19b299532 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def weightedMovingAverage(period, data): | |
# --- Weighted Moving Average | |
# data: array, time series data e.g. daily close prices | |
# period: integer, number of periods from time series array to include in calculation | |
import numpy as np | |
# --- get first non nan index | |
for i in range(len(data)): | |
if np.isnan(data[i]) == False: | |
firstNonNan = i | |
break | |
# --- get last non nan index | |
for i in reversed(range(len(data))): | |
if np.isnan(data[i]) == False: | |
lastNonNan = i | |
break | |
# --- based on period value calculate the 'weighting factor' or denominator | |
d = period * (period / 2 + 0.5) | |
# --- generate weights list | |
weights = np.zeros(period) | |
for i in range(period): | |
weights[i] = (i + 1) / d | |
# --- calculate WMA | |
a = np.zeros(period) | |
out = np.zeros(len(data)) | |
for i in range(len(data)): | |
if i < firstNonNan + period - 1: | |
out[i] = np.nan | |
elif i > lastNonNan: | |
out[i] = np.nan | |
else: | |
for m in range(period): | |
a[(period - 1) - m] = data[ | |
i - m, | |
] | |
out[i] = np.sum(a * weights) | |
return out |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment