Last active
February 25, 2023 00:29
-
-
Save whittlem/915794cfb39c2af760bbee6641b75a23 to your computer and use it in GitHub Desktop.
Trading using Python - Exponential Moving Average (EMA)
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, ... } | |
# num: range in the average calculation, normally 9 to 26 | |
def exponentialMovingAverage(data, num): | |
if not isinstance(data, dict): | |
raise Exception('Dictionary input expected') | |
if not isinstance(num, int): | |
raise Exception('Integer input expected') | |
if num < 9 or num > 26: | |
raise Exception('Unusual numeric input detected') | |
if (num > len(data)): | |
raise Exception('Insufficient data for calculation') | |
data_keys = list(data.keys()) | |
data_list = list(data.values()) | |
last_sma = -1 | |
result = {} | |
for x in range(len(data_list) - num + 1): | |
series = data_list[x:x + num] | |
if (last_sma == -1): | |
result[data_keys[x + num - 1]] = round((sum(series) / num), 2) | |
else: | |
current_price = data[data_keys[x + num - 1]] | |
result[data_keys[x + num - 1]] = round( | |
current_price * 2 / (num + 1) + last_sma * (1 - 2 / (num + 1)), 2) | |
last_sma = result[data_keys[x + num - 1]] | |
return result | |
data = cbpGetHistoricRates('BTC-GBP', 86400) | |
ema12 = exponentialMovingAverage(data, 12) | |
ema26 = exponentialMovingAverage(data, 26) | |
print (ema12) | |
print (ema26) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment