Last active
November 17, 2020 13:21
-
-
Save whittlem/ba1adbc08860e3754b320723df4bd710 to your computer and use it in GitHub Desktop.
Trading using Python - Moving Average Convergence Divergence (MACD)
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
# data: dictionary { 'dd/mm/yyy': price, 'dd/mm/yyyy': price, ... } | |
def movingAverageConvergenceDivergence(data): | |
if not isinstance(data, dict): | |
raise Exception('Dictionary input expected') | |
if (26 > len(data)): | |
raise Exception('Insufficient data for calculation') | |
ema12_data = exponentialMovingAverage(data, 12) | |
ema26_data = exponentialMovingAverage(data, 26) | |
macd_data = {} | |
data_keys = list(data.keys()) | |
for key in data_keys: | |
ema12 = 0 | |
if key in ema12_data: | |
ema12 = ema12_data[key] | |
ema26 = 0 | |
if key in ema26_data: | |
ema26 = ema26_data[key] | |
if (ema12 > 0) and (ema26 == 0): | |
macd_data[key] = 0 | |
else: | |
macd_data[key] = ema12 - ema26 | |
signal_data = exponentialMovingAverage(macd_data, 9) | |
result = {} | |
for key in data_keys: | |
price = 0 | |
if key in data: | |
price = data[key] | |
ema12 = 0 | |
if key in ema12_data: | |
ema12 = ema12_data[key] | |
ema26 = 0 | |
if key in ema26_data: | |
ema26 = ema26_data[key] | |
macd = 0 | |
if key in macd_data: | |
macd = macd_data[key] | |
signal = 0 | |
if key in signal_data: | |
signal = signal_data[key] | |
result[key] = { | |
'price': price, | |
'ema12': ema12, | |
'ema26': ema26, | |
'macd': macd, | |
'signal': signal | |
} | |
return result | |
data = cbpGetHistoricRates('BTC-GBP', 86400) | |
macd = movingAverageConvergenceDivergence(data) | |
print (macd) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment