aboutsummaryrefslogtreecommitdiff
path: root/ema_algo.py
diff options
context:
space:
mode:
Diffstat (limited to 'ema_algo.py')
-rw-r--r--ema_algo.py81
1 files changed, 81 insertions, 0 deletions
diff --git a/ema_algo.py b/ema_algo.py
new file mode 100644
index 0000000..db25c08
--- /dev/null
+++ b/ema_algo.py
@@ -0,0 +1,81 @@
+from algo import Algo
+import plotly.graph_objects as go
+import datetime
+
+class Ema_Algo(Algo):
+ def __init__(self, shortPeriod=5, longPeriod=13):
+ self.shortPeriod = shortPeriod
+ self.longPeriod = longPeriod
+ self.g_data = {
+ "timestamps" : [],
+ "ema_short" : [],
+ "ema_long" : []
+ }
+
+ @property
+ def name(self):
+ return "EMA Algo"
+
+ @property
+ def graph_data(self):
+ return self.g_data
+
+ def export_graph(self, g_data):
+ timestamps = [datetime.datetime.fromtimestamp(t) for t in g_data['timestamps']]
+ ema_5 = g_data['ema_short']
+ ema_13 = g_data['ema_long']
+ exp = [
+ go.Scatter(name='5 day EMA', x=timestamps, y=ema_5, line=dict(color='rgb(0, 255, 0)'), mode='lines'),
+ go.Scatter(name='13 day EMA', x=timestamps, y=ema_13, line=dict(color='rgb(0, 0, 255)'), mode='lines')
+ ]
+ return exp
+
+ def detemine_signal(self, timestamps, prices):
+
+ ema_5 = self.calc_emas(self.shortPeriod, prices)
+ ema_13 = self.calc_emas(self.longPeriod, prices)
+
+ # add to graph data
+ self.graph_data["timestamps"].append(timestamps[-1])
+ self.graph_data["ema_short"].append(ema_5[-1])
+ self.graph_data["ema_long"].append(ema_13[-1])
+
+ # determine the sign from the most recent price
+ sign_signal = ema_5[-1] - ema_13[-1]
+ # current position, (liquid, shares)
+ if sign_signal > 0:
+ return 1.0 # buy max shares
+ if sign_signal < 0:
+ return 0.0 # sell all shares
+
+ return 0.5
+
+ """
+ Calculates the simple moving average of the first period of the data
+ """
+ def calc_first_sma(self, period, prices):
+ prices_sum = 0
+ for i in range(0, period):
+ prices_sum += prices[i] # 0, 1, 2, 3 ("popping" order)
+ # print('prices_sum:\t', prices_sum)
+
+ return prices_sum / period
+
+ """
+ Returns an array off all EMAs, computed according to period
+ """
+ def calc_emas(self, period, prices):
+ weighted_multiplier = 2.0 / (period + 1.0)
+
+ # calculate the first ema
+ first_ema = self.calc_first_sma(period, prices)
+
+ # calculate the rest ema's using that first
+ emas = [first_ema] * period # 0, 1, 2 (for period 3)
+ for i in range(period, len(prices)): # 3, 4, 5, 6, ... , last
+ last_ema = emas[-1]
+ if prices[i] == None or prices[i] == 0:
+ print(i)
+ next_ema = prices[i] * weighted_multiplier + last_ema * (1 - weighted_multiplier)
+ emas.append(next_ema)
+ return emas \ No newline at end of file