generated from DeML-Research/Python-Project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
visualizations.py
241 lines (194 loc) · 11 KB
/
visualizations.py
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
"""
# -- --------------------------------------------------------------------------------------------------- -- #
# -- project: A SHORT DESCRIPTION OF THE PROJECT -- #
# -- script: visualizations.py : python script with data visualization functions -- #
# -- author: YOUR GITHUB USER NAME -- #
# -- license: GPL-3.0 License -- #
# -- repository: YOUR REPOSITORY URL -- #
# -- --------------------------------------------------------------------------------------------------- -- #
"""
import numpy as np
import plotly.graph_objects as go
# -- -------------------------------------------------------- PLOT: OHLC Price Chart with Vertical Lines -- #
# -- --------------------------------------------------------------------------------------------------- -- #
def g_ohlc(p_ohlc, p_theme, p_vlines):
"""
Timeseries Candlestick with OHLC prices and figures for trades indicator
Requirements
------------
numpy
pandas
plotly
Parameters
----------
p_ohlc: pd.DataFrame
that contains the following float or int columns: 'timestamp', 'open', 'high', 'low', 'close'
p_theme: dict
with the theme for the visualizations
p_vlines: list
with the dates where to visualize the vertical lines, format = pd.to_datetime('2020-01-01 22:15:00')
Returns
-------
fig_g_ohlc: plotly
objet/dictionary to .show() and plot in the browser
References
----------
https://plotly.com/python/candlestick-charts/
"""
# default value for lables to use in main title, and both x and y axisp_fonts
if p_theme['p_labels'] is not None:
p_labels = p_theme['p_labels']
else:
p_labels = {'title': 'Main title', 'x_title': 'x axis title', 'y_title': 'y axis title'}
# tick values calculation for simetry in y axes
y0_ticks_vals = np.arange(min(p_ohlc['low']), max(p_ohlc['high']),
(max(p_ohlc['high']) - min(p_ohlc['low'])) / 10)
y0_ticks_vals = np.append(y0_ticks_vals, max(p_ohlc['high']))
y0_ticks_vals = np.round(y0_ticks_vals, 4)
# Instantiate a figure object
fig_g_ohlc = go.Figure()
# Add layer for OHLC candlestick chart
fig_g_ohlc.add_trace(go.Candlestick(name='ohlc', x=p_ohlc['timestamp'], open=p_ohlc['open'],
high=p_ohlc['high'], low=p_ohlc['low'], close=p_ohlc['close'],
opacity=0.7))
# Layout for margin, and both x and y axes
fig_g_ohlc.update_layout(margin=go.layout.Margin(l=50, r=50, b=20, t=50, pad=20),
xaxis=dict(title_text=p_labels['x_title']),
yaxis=dict(title_text=p_labels['y_title']))
# Color and font type for text in axes
fig_g_ohlc.update_layout(xaxis=dict(titlefont=dict(color=p_theme['p_colors']['color_1']),
tickfont=dict(color=p_theme['p_colors']['color_1'],
size=p_theme['p_fonts']['font_axis']), showgrid=True),
yaxis=dict(zeroline=False, automargin=True,
titlefont=dict(color=p_theme['p_colors']['color_1']),
tickfont=dict(color=p_theme['p_colors']['color_1'],
size=p_theme['p_fonts']['font_axis']),
showgrid=True, gridcolor='lightgrey', gridwidth=.05))
# If parameter vlines is used
if p_vlines is not None:
# Dynamically add vertical lines according to the provided list of x dates.
shapes_list = list()
for i in p_vlines:
shapes_list.append({'type': 'line', 'fillcolor': p_theme['p_colors']['color_1'],
'line': {'color': p_theme['p_colors']['color_1'],
'dash': 'dashdot', 'width': 3},
'x0': i, 'x1': i, 'xref': 'x',
'y0': min(p_ohlc['low']), 'y1': max(p_ohlc['high']), 'yref': 'y'})
# add v_lines to the layout
fig_g_ohlc.update_layout(shapes=shapes_list)
# Update layout for the background
fig_g_ohlc.update_layout(yaxis=dict(tickfont=dict(color='grey', size=p_theme['p_fonts']['font_axis']),
tickvals=y0_ticks_vals),
xaxis=dict(tickfont=dict(color='grey', size=p_theme['p_fonts']['font_axis'])))
# Update layout for the y axis
fig_g_ohlc.update_xaxes(rangebreaks=[dict(pattern="day of week", bounds=['sat', 'sun'])])
# Update layout for the background
fig_g_ohlc.update_layout(title_font_size=p_theme['p_fonts']['font_title'],
title=dict(x=0.5, text='<b> ' + p_labels['title'] + ' </b>'),
yaxis=dict(title=p_labels['y_title'],
titlefont=dict(size=p_theme['p_fonts']['font_axis'] + 4)),
xaxis=dict(title=p_labels['x_title'], rangeslider=dict(visible=False),
titlefont=dict(size=p_theme['p_fonts']['font_axis'] + 4)))
# Final plot dimensions
fig_g_ohlc.layout.autosize = True
fig_g_ohlc.layout.width = p_theme['p_dims']['width']
fig_g_ohlc.layout.height = p_theme['p_dims']['height']
return fig_g_ohlc
# -- -------------------------------------------- PLOT: OHLC Candlesticks + Colored Classificator Result -- #
# -- --------------------------------------------------------------------------------------------------- -- #
def g_ohlc_class(p_ohlc, p_theme, p_data_class, p_vlines):
# default value for lables to use in main title, and both x and y axisp_fonts
if p_theme['p_labels'] is not None:
p_labels = p_theme['p_labels']
else:
p_labels = {'title': 'Main title', 'x_title': 'x axis title', 'y_title': 'y axis title'}
# tick values calculation for simetry in y axes
y0_ticks_vals = np.arange(min(p_ohlc['low']), max(p_ohlc['high']),
(max(p_ohlc['high']) - min(p_ohlc['low'])) / 5)
y0_ticks_vals = np.append(y0_ticks_vals, max(p_ohlc['high']))
y0_ticks_vals = np.round(y0_ticks_vals, 4)
# reset the index of the input data
p_ohlc.reset_index(inplace=True, drop=True)
# auxiliar lists
train_error = []
test_error = []
test_success = []
train_success = []
# error and success in train
for row in p_data_class['train_y'].index.to_list():
if p_data_class['train_y'][row] != p_data_class['train_y_pred'][row]:
train_error.append(row)
else:
train_success.append(row)
# error and success in test
for row in p_data_class['test_y'].index.to_list():
if p_data_class['test_y'][row] != p_data_class['test_y_pred'][row]:
test_error.append(row)
else:
test_success.append(row)
# train and test errors in a list
train_test_error = train_error + test_error
# train and test success in a list
train_test_success = train_success + test_success
# Instantiate a figure object
fig_g_ohlc = go.Figure()
# Layout for margin, and both x and y axes
fig_g_ohlc.update_layout(margin=go.layout.Margin(l=50, r=50, b=20, t=50, pad=20),
xaxis=dict(title_text=p_labels['x_title']),
yaxis=dict(title_text=p_labels['y_title']))
# Add layer for the error based color of candles in OHLC candlestick chart
fig_g_ohlc.add_trace(go.Candlestick(
x=[p_ohlc['timestamp'].iloc[i] for i in train_test_error],
open=[p_ohlc['open'].iloc[i] for i in train_test_error],
high=[p_ohlc['high'].iloc[i] for i in train_test_error],
low=[p_ohlc['low'].iloc[i] for i in train_test_error],
close=[p_ohlc['close'].iloc[i] for i in train_test_error],
increasing={'line': {'color': 'red'}},
decreasing={'line': {'color': 'red'}},
name='Prediction Error'))
# Add layer for the success based color of candles in OHLC candlestick chart
fig_g_ohlc.add_trace(go.Candlestick(
x=[p_ohlc['timestamp'].iloc[i] for i in train_test_success],
open=[p_ohlc['open'].iloc[i] for i in train_test_success],
high=[p_ohlc['high'].iloc[i] for i in train_test_success],
low=[p_ohlc['low'].iloc[i] for i in train_test_success],
close=[p_ohlc['close'].iloc[i] for i in train_test_success],
increasing={'line': {'color': 'skyblue'}},
decreasing={'line': {'color': 'skyblue'}},
name='Prediction Success'))
# Update layout for the background
fig_g_ohlc.update_layout(yaxis=dict(tickfont=dict(color='grey',
size=p_theme['p_fonts']['font_axis']), tickvals=y0_ticks_vals),
xaxis=dict(tickfont=dict(color='grey',
size=p_theme['p_fonts']['font_axis'])))
# Update layout for the y axis
fig_g_ohlc.update_xaxes(rangebreaks=[dict(pattern="day of week", bounds=['sat', 'sun'])])
# If parameter vlines is used
if p_vlines is not None:
# Dynamically add vertical lines according to the provided list of x dates.
shapes_list = list()
for i in p_vlines:
shapes_list.append({'type': 'line', 'fillcolor': p_theme['p_colors']['color_1'],
'line': {'color': p_theme['p_colors']['color_1'],
'dash': 'dashdot', 'width': 3},
'x0': i, 'x1': i, 'xref': 'x',
'y0': min(p_ohlc['low']), 'y1': max(p_ohlc['high']), 'yref': 'y'})
# add v_lines to the layout
fig_g_ohlc.update_layout(shapes=shapes_list)
# Formato para titulo
fig_g_ohlc.update_layout(legend=go.layout.Legend(x=.35, y=-.3, orientation='h',
bordercolor='dark grey',
borderwidth=1,
font=dict(size=p_theme['p_fonts']['font_axis'])))
# Update layout for the background
fig_g_ohlc.update_layout(title_font_size=p_theme['p_fonts']['font_title'],
title=dict(x=0.5, text='<b> ' + p_labels['title'] + ' </b>'),
yaxis=dict(title=p_labels['y_title'],
titlefont=dict(size=p_theme['p_fonts']['font_axis'] + 4)),
xaxis=dict(title=p_labels['x_title'], rangeslider=dict(visible=False),
titlefont=dict(size=p_theme['p_fonts']['font_axis'] + 4)))
# Final plot dimensions
fig_g_ohlc.layout.autosize = True
fig_g_ohlc.layout.width = p_theme['p_dims']['width']
fig_g_ohlc.layout.height = p_theme['p_dims']['height']
return fig_g_ohlc