Skip to content

Instantly share code, notes, and snippets.

@whittlem
Last active February 25, 2023 00:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save whittlem/915794cfb39c2af760bbee6641b75a23 to your computer and use it in GitHub Desktop.
Save whittlem/915794cfb39c2af760bbee6641b75a23 to your computer and use it in GitHub Desktop.
Trading using Python  - Exponential Moving Average (EMA)
# 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