1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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
|