-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlabquant.py
4168 lines (3784 loc) · 165 KB
/
labquant.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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# LabQuant - A visual tool to support the development of algo-strategies in Quantitative Finance - by fab2112
import re
import os
import sys
import datetime
import tempfile
import traceback
import itertools
import numpy as np
import pandas as pd
import pyqtgraph as pg
import multiprocessing as mp
from scipy import stats
from colorama import Fore
from pyqtgraph.Qt import QtCore
from pyqtgraph import QtWidgets
from typing import Callable, Optional
from multiprocessing.sharedctypes import Value
from sklearn.metrics import accuracy_score, f1_score
from pyqtgraph.Qt.QtGui import QFont, QLinearGradient, QBrush
from pyqtgraph.Qt.QtWidgets import (
QPushButton,
QApplication,
QComboBox,
QLabel,
QCheckBox,
)
from .candlestick import CandlestickItem
from .multlines import MultiColorLines, MultiLines
from .datetimeaxis import DatetimeAxisX2, DatetimeAxisX3
from .simulations import ProcessMonteCarlo, ProcessHypSimulations, ThreadHypSimulations
from .utils import (
apply_tax,
process_df,
process_mc_strategy,
decimal_round,
get_drawdowns,
get_equitycurve,
get_hitrate,
get_riskmetrics,
get_mc_price_paths,
)
BAR_TITLE = "LabQuant v0.1.4"
class LabQuant(QtWidgets.QMainWindow):
"""
This class manages the entire graphical engine of the project based on the PyQtGraph module.
"""
def __init__(self, df_1: pd.DataFrame, seed: int | None = None, show_roi: bool = False):
"""
Initialization method.
args:
df_1 (dataframe): The main dataframe ohlcv processed by strategy.
seed (int | None): Reproductibility of experiments.
show_roi (bool | None): Enable or disable region of interest (see ROI - PyQtGraph).
"""
self.app = QApplication(sys.argv)
super().__init__()
#
self.seed = seed
self.df_1 = df_1
self.exec_loop = True
self.show_roi = show_roi
self.strategy = None
self.str_params = None
# Monte Carlo args
self.mc_mode = None
self.mc_paths_colors = None
self.mc_line_plots = None
self.mc_dist_bins = None
self.mc_price_model = None
self.mc_nsim = None
self.mc_nsteps = None
self.mc_sigma = None
self.mc_s0 = None
self.mc_r = None
self.mc_dt = None
self.mc_lambda_ = None
self.mc_mu_y = None
self.mc_sigma_y = None
# Variables Logic
self.showplt1 = 1 # Performance | Signals
self.showplt2 = 1 # Positions & Signals
self.showplt3 = 1 # Features
self.showplt4 = 1 # Cumulative Amount
self.showplt5 = 1 # Equity Curve Scatter
self.showplt6 = 1 # Monte Carlo Simulation
self.showplt7 = 1 # Distribution
self.showplt8 = 1 # DDrown Monte Carlo
self.showplt9 = 1 # Monte Carlo EquityCurves CDF
self.showplt10 = 1 # Monte Carlo Plot Expander
self.showplt11 = 1 # Strategy Returns
self.showplt12 = 1 # Strategy params simulations
self.showplt13 = 1 # Monte Carlo CDF | PDF
self.cumulative_gain_curve_str = 0
# Object Attributes
self.equity_curve_true = None
self.equity_curve_pred = None
self.initial_pos = None
self.pct_rate = None
self.returns = None
self.strategy_returns_true = None
self.strategy_returns_pred = None
self.cumulative_gain_curve_hold = None
self.market_returns_cum = None
self.strategy_returns_cum = None
self.drawdown = None
self.scatter_long_true = None
self.scatter_short_true = None
self.scatter_long_pred = None
self.scatter_short_pred = None
self.scatter_exit_true_long = None
self.scatter_exit_true_short = None
self.scatter_exit_pred_long = None
self.scatter_exit_pred_short = None
self.scatter_exit_gain_true = None
self.scatter_exit_stop_true = None
self.scatter_exit_gain_pred = None
self.scatter_exit_stop_pred = None
self.scatter_short_pred_plus = None
self.scatter_short_pred_minus = None
self.scatter_long_pred_plus = None
self.scatter_long_pred_minus = None
self.n_trads = None
self.sharpe_ratio = None
self.sortino_ratio = None
self.calmar_ratio = None
self.grad = None
self.brush = None
self.maker_fee = None
self.risk_free = None
self.period = None
self.pos_true = None
self.pos_pred = None
self.frame_plot_2 = None
self.plt_4 = None
self.plt_5 = None
self.plt_6 = None
self.mc_sucess_prob = None
self.var_value = None
self.np_mem_1 = None
self.np_mem_2 = None
self.workProcess = None
self.timer_plot = None
self.mc_average_dd = None
self.x_line_plt1 = None
self.y_line_plt1 = None
self.x_line_plt2 = None
self.y_line_plt2 = None
self.x_line_plt3 = None
self.y_line_plt3 = None
self.proxy = None
self.test_ = False
self.treat_zerodiv_factor = 1e-32
self.df_diff_factor = 0
self.df_main = pd.DataFrame()
self.df_str_params = pd.DataFrame()
# Reset df_1 index
self.df_1 = self.df_1.reset_index(drop=True)
# Set Axis shared var
self.value_var_time_axis = Value("d")
# Parse timestamp
if "time" in self.df_1.columns:
# Convert date object to to epoch timestamp
if pd.api.types.is_object_dtype(self.df_1.time):
# Set time to epoch timestamp
try:
self.df_1["time"] = self.df_1.time.astype(float)
# self.df_1.time = pd.to_datetime(self.df_1.time)
# Convert string unix epoch to float
except Exception as e:
self.df_1.time = pd.to_datetime(self.df_1.time)
self.df_1["time"] = (
self.df_1["time"] - datetime.datetime(1970, 1, 1)
).dt.total_seconds() * 1000 + 10800000.0
# Convert date datetime64[ns] to epoch timestamp
elif pd.api.types.is_datetime64_any_dtype(self.df_1.time):
self.df_1["time"] = (
self.df_1["time"] - datetime.datetime(1970, 1, 1)
).dt.total_seconds() * 1000 + 10800000.0
# Epoch [ms] normalization
if self.df_1.time.values[-1] < 10000000000:
self.df_1.time = self.df_1.time * 1000
# Dateindex column reference - Epoch timestamp or timestamp[ms]
self.df_1["dateindex"] = 0
step_ref = self.df_1.time.values[1] - self.df_1.time.values[0]
time_diff = self.df_1["time"].diff().fillna(step_ref)
self.df_1["dateindex"] = (time_diff / step_ref).cumsum()
self.value_var_time_axis.value = 0
else:
self.df_1["dateindex"] = self.df_1.index.values
self.df_1["time"] = self.df_1.index.values
self.value_var_time_axis.value = 10
# MainWindow 1
self.win_1 = QtWidgets.QMainWindow()
self.win_1.setWindowTitle(BAR_TITLE)
self.win_1.setGeometry(150, 100, 1400, 900)
self.win_1.setStyleSheet("background-color: #282828;")
# Set widgets layouts
self.plot_widget_0 = pg.GraphicsLayoutWidget()
self.plot_widget_0_1 = pg.GraphicsLayoutWidget()
self.plot_widget_1 = pg.GraphicsLayoutWidget()
self.plot_widget_2 = pg.GraphicsLayoutWidget()
self.plot_widget_3 = pg.GraphicsLayoutWidget()
# Fix widget_0 height
self.plot_widget_0.setFixedHeight(40)
# Set widgets bg-color
self.plot_widget_0.setBackground(background="#282828")
self.plot_widget_0_1.setBackground(background="#282828")
self.plot_widget_1.setBackground(background="#282828")
self.plot_widget_2.setBackground(background="#282828")
self.plot_widget_3.setBackground(background="#282828")
# Set QSplitter
self.splitter = QtWidgets.QSplitter(QtCore.Qt.Vertical)
# Add widgets in splitter
self.splitter.addWidget(self.plot_widget_0)
self.splitter.addWidget(self.plot_widget_0_1)
self.splitter.addWidget(self.plot_widget_1)
self.splitter.addWidget(self.plot_widget_2)
self.splitter.addWidget(self.plot_widget_3)
# Splitter settings
self.splitter.setStyleSheet("""
QSplitter::handle {
background-color: black;
height: 1px;
}
""")
# Set Axis shared var
self.value_var_hist_axis = Value("d")
self.value_var_hist_axis.value = 0
self.datetimeaxis_plt2 = DatetimeAxisX2(
orientation="bottom",
data=self.df_1.time,
value_var_hist_axis=self.value_var_hist_axis,
value_var_time_axis=self.value_var_time_axis,
)
self.datetimeaxis_plt3 = DatetimeAxisX3(
orientation="bottom",
data=self.df_1.time,
value_var_hist_axis=self.value_var_hist_axis,
value_var_time_axis=self.value_var_time_axis,
)
self.plt_0 = self.plot_widget_0_1.addPlot()
self.plt_1 = self.plot_widget_1.addPlot()
self.plt_2 = self.plot_widget_2.addPlot(
axisItems={"bottom": self.datetimeaxis_plt2}
)
self.plt_3 = self.plot_widget_3.addPlot(
axisItems={"bottom": self.datetimeaxis_plt3}
)
# Optimizations
factor = 5
self.plt_1.setClipToView(True)
self.plt_2.setClipToView(True)
self.plt_3.setClipToView(True)
self.plt_0.setDownsampling(auto=True, mode="subsample", ds=factor)
self.plt_1.setDownsampling(auto=True, mode="peak", ds=factor)
self.plt_2.setDownsampling(auto=True, mode="peak", ds=factor)
self.plt_3.setDownsampling(auto=True, mode="peak", ds=factor)
# ROI - Region Of Interest
if self.show_roi:
if len(self.df_1) > 100000:
pct_region = 0.02
else:
pct_region = 0.1
self.plot_widget_0_1.setFixedHeight(50)
self.roi = pg.LinearRegionItem([0, (pct_region * len(self.df_1.c))])
self.roi.setBounds([0, len(self.df_1.c) - 1])
self.roi.sigRegionChanged.connect(self._update_plot_by_roi)
self.roi.setHoverBrush(pg.mkBrush((pg.mkColor("#D3D3D340"))))
self.roi.setBrush(pg.mkBrush((pg.mkColor("#D3D3D320"))))
self.plt_0.setFixedHeight(30)
self.plt_0.addItem(self.roi)
self.plt_0.plot(self.df_1.c.values, pen=pg.mkPen("#B0C4DE", width=0.6))
self.plt_0.enableAutoRange(x=True, y=True)
self.plt_0.setMouseEnabled(x=False, y=False)
self.roi_plot_var = 0
for line in self.roi.lines:
line.setPen(pg.mkPen(pg.mkColor("grey"), width=1))
line.setHoverPen(pg.mkPen(pg.mkColor("green"), width=3))
else:
self.plot_widget_0_1.hide()
# Set splitter top margin
self.splitter.setContentsMargins(0, 0, 0, 0)
# Centralize splitter in win_1
self.win_1.setCentralWidget(self.splitter)
# ">" - Performance
self.button_1 = QPushButton(self.plot_widget_0)
self.button_1.clicked.connect(self._show_plot)
self.button_1.setGeometry(10, 10, 20, 20)
self.button_1.setText(">")
self.button_1.show()
self.button_1.setStyleSheet(
"font: bold 11pt; color: white; background-color: #483D8B; "
"border-radius: 1px; border: 1px outset grey;"
)
# "-" - Signals / Positions / Pct-change
self.button_2 = QPushButton(self.plot_widget_0)
self.button_2.clicked.connect(self._show_signals_positions)
self.button_2.setGeometry(40, 10, 20, 20)
self.button_2.setText("-")
self.button_2.setStyleSheet(
"font: bold 11pt; color: white; background-color: #483D8B; "
"border-radius: 1px; border: 1px outset grey;"
)
# "X" - Features
self.button_3 = QPushButton(self.plot_widget_0)
self.button_3.clicked.connect(self._show_features)
self.button_3.setGeometry(70, 10, 20, 20)
self.button_3.setText("X")
self.button_3.setStyleSheet(
"font: bold 11pt; color: white; background-color: #483D8B; "
"border-radius: 1px; border: 1px outset grey;"
)
# "A" - Cumulative Amount
self.button_4 = QPushButton(self.plot_widget_0)
self.button_4.clicked.connect(self._show_cumulative_gains)
self.button_4.setGeometry(100, 10, 20, 20)
self.button_4.setText("A")
self.button_4.setStyleSheet(
"font: bold 11pt; color: white; background-color: #483D8B; "
"border-radius: 1px; border: 1px outset grey;"
)
# "MC" - Monte Carlo Simulation
self.button_5 = QPushButton(self.plot_widget_0)
self.button_5.clicked.connect(self._show_monte_carlo_simulation)
self.button_5.setGeometry(200, 10, 30, 20)
self.button_5.setText("MC")
self.button_5.setEnabled(False)
self.button_5.setStyleSheet(
"""
QPushButton {
font: bold 11pt;
color: white;
background-color: #483D8B;
border-radius: 1px;
border: 1px outset grey;
}
QPushButton:disabled {
color: #8B8B8B;
background-color: #404040;
border: 1px outset #404040;
}
"""
)
# "D" - Price Distribution
self.button_6 = QPushButton(self.plot_widget_0)
self.button_6.clicked.connect(self._show_pricedistribution)
self.button_6.setGeometry(100, 10, 20, 20)
self.button_6.setText("D")
self.button_6.setStyleSheet(
"font: bold 11pt; color: white; background-color: #483D8B; "
"border-radius: 1px; border: 1px outset grey;"
)
# "R" - Returns
self.button_9 = QPushButton(self.plot_widget_0)
self.button_9.clicked.connect(self._show_returns)
self.button_9.setGeometry(40, 10, 20, 20)
self.button_9.setText("R")
self.button_9.setStyleSheet(
"font: bold 11pt; color: white; background-color: #483D8B; "
"border-radius: 1px; border: 1px outset grey;"
)
# "S" - Simulation
self.button_10 = QPushButton(self.plot_widget_0)
self.button_10.clicked.connect(self._show_hypparams_simulation)
self.button_10.setGeometry(160, 10, 30, 20)
self.button_10.setText("SM")
self.button_10.setEnabled(False)
self.button_10.setStyleSheet(
"""
QPushButton {
font: bold 11pt;
color: white;
background-color: #483D8B;
border-radius: 1px;
border: 1px outset grey;
}
QPushButton:disabled {
color: #8B8B8B;
background-color: #404040;
border: 1px outset #404040;
}
"""
)
# Set Font
self.font = QFont("TypeWriter")
self.font.setPixelSize(13)
# MC combobox
self.combobox_mc = QComboBox(self.plot_widget_0)
self.combobox_mc.setGeometry(245, 9, 305, 22)
self.combobox_mc.setFont(self.font)
self.combobox_mc.currentIndexChanged.connect(self._update_mc_mode)
self.combobox_mc.addItems(
[
"RANDOM PRICES PRICE BASE",
"RANDOM PRICES BLACK SCHOLES",
"RANDOM PRICES MERTON JUMP DIFFUSION",
"RANDOM RETURNS",
"RANDOM RETURNS WITH REPLACEMENT",
"RANDOM POSITIONS",
"RANDOM STARTINGS POSITIONS",
"RANDOM ENDINGS POSITIONS",
]
)
self.combobox_mc.setStyleSheet("""
QComboBox {
background-color: #2E2E2E; /* Cor de fundo do ComboBox */
color: #B0C4DE; /* Cor do texto */
border: 1px solid gray; /* Cor da borda */
selection-color: black;
selection-background-color: #B0C4DE;
}
QComboBox QAbstractItemView {
background-color: #2E2E2E; /* Cor de fundo das opções */
color: grey; /* Cor do texto das opções */
}
QComboBox:disabled {
background-color: #424242; /* Fundo intermediário */
color: #9A9A9A; /* Texto cinza médio */
border: 1px solid #606060; /* Borda cinza escuro */
}
""")
self.combobox_mc.setEnabled(False)
# Checkbox
self.checkbox_scatter = QCheckBox("SCATTERS", self.plot_widget_0)
self.checkbox_scatter.stateChanged.connect(self._showhide_scatters)
self.checkbox_scatter.setGeometry(565, 9, 100, 22)
self.checkbox_scatter.setFont(self.font)
self.checkbox_scatter.setChecked(True)
self.checkbox_scatter.setStyleSheet(
"color: #B0C4DE; background-color: #2E2E2E; "
"border-radius: 1px; border: 1px solid grey"
)
# Scaling limit
self.plt_1.getViewBox().setLimits(
xMin=-10000000000000,
xMax=10000000000000,
yMin=-10000000000000,
yMax=10000000000000,
)
self.plt_2.getViewBox().setLimits(
xMin=-1000000000000,
xMax=10000000000000,
yMin=-10000000000000,
yMax=10000000000000,
)
self.plt_3.getViewBox().setLimits(
xMin=-10000000000000,
xMax=10000000000000,
yMin=-10000000000000,
yMax=10000000000000,
)
# Risk Metrics
self.risk_metrics_textitem = pg.TextItem(color="#5EF38C")
self.risk_metrics_textitem.setParentItem(self.plt_3)
self.risk_metrics_textitem.setPos(10, 5)
self.risk_metrics_textitem.setFont(self.font)
# Profit and Losses
self.pnl_textitem = pg.TextItem(color="#5EF38C")
self.pnl_textitem.setParentItem(self.plt_2)
self.pnl_textitem.setPos(10, 5)
self.pnl_textitem.setFont(self.font)
# Returns
self.returns_textitem = pg.TextItem(color="#5EF38C")
self.returns_textitem.setParentItem(self.plt_2)
self.returns_textitem.setPos(10, 5)
self.returns_textitem.setFont(self.font)
# Hit-Rate and n-Hits | n-Losses
self.hit_trads_textitem = pg.TextItem(color="#90EE90")
self.hit_trads_textitem.setParentItem(self.plt_2)
self.hit_trads_textitem.setPos(10, 5)
self.hit_trads_textitem.setFont(self.font)
# Distribution
self.dist_textitem = pg.TextItem(color="#99CCFF")
self.dist_textitem.setParentItem(self.plt_2)
self.dist_textitem.setPos(10, 5)
self.dist_textitem.setFont(self.font)
# Monte Carlo Status
self.mc_label = QLabel(self.plot_widget_0)
self.mc_label.setStyleSheet("color: #B0C4DE;")
self.mc_label.setGeometry(685, 10, 450, 20)
self.mc_label.setFont(self.font)
self.mc_label.hide()
# Simulation Status
self.sim_label = QLabel(self.plot_widget_0)
self.sim_label.setStyleSheet("color: #B0C4DE;")
self.sim_label.setGeometry(685, 10, 450, 20)
self.sim_label.setFont(self.font)
self.sim_label.hide()
# Initializing status
self.init_label = QLabel(self.plot_widget_0)
self.init_label.setStyleSheet("color: yellow;")
self.init_label.setGeometry(685, 10, 400, 20)
self.init_label.setFont(self.font)
self.init_label.show()
self.init_label.setText("STARTING...")
# Hit-Rate and n-Hits | n-Losses
self.scores_textitem = pg.TextItem(color="#90EE90")
self.scores_textitem.setParentItem(self.plt_1)
self.scores_textitem.setPos(10, 5)
self.scores_textitem.setFont(self.font)
self.scores_textitem.hide()
# Drawndown
self.drawdown_textitem = pg.TextItem(color="#ff3562")
self.drawdown_textitem.setParentItem(self.plt_1)
self.drawdown_textitem.setPos(10, 5)
self.drawdown_textitem.setFont(self.font)
# Plot Configs
self.font_axis = QFont("Arial")
self.font_axis.setPixelSize(13)
self.font_axis.setWeight(40)
# Font Tick
self.plt_0.getAxis("right").setTickFont(self.font_axis)
self.plt_1.getAxis("right").setTickFont(self.font_axis)
self.plt_2.getAxis("right").setTickFont(self.font_axis)
self.plt_3.getAxis("right").setTickFont(self.font_axis)
self.plt_3.getAxis("bottom").setTickFont(self.font_axis)
# Color Tick
self.plt_0.getAxis("right").setTextPen("#C0C0C0")
self.plt_1.getAxis("right").setTextPen("#C0C0C0")
self.plt_2.getAxis("right").setTextPen("#C0C0C0")
self.plt_3.getAxis("right").setTextPen("#C0C0C0")
self.plt_3.getAxis("bottom").setTextPen("#C0C0C0")
# Config Grid
self.plt_0.showGrid(x=True, y=True, alpha=0.2)
self.plt_1.showGrid(x=True, y=True, alpha=0.2)
self.plt_2.showGrid(x=True, y=True, alpha=0.2)
self.plt_3.showGrid(x=True, y=True, alpha=0.2)
# Config Axis
self.plt_0.showAxis("right")
self.plt_0.showAxis("left")
self.plt_0.showAxis("top")
self.plt_0.getAxis("left").setStyle(showValues=False)
self.plt_0.getAxis("top").setStyle(showValues=False)
self.plt_0.getAxis("bottom").setStyle(showValues=False)
self.plt_0.getAxis("right").setStyle(showValues=False)
self.plt_0.getAxis("right").setWidth(int(65))
#
self.plt_1.showAxis("right")
self.plt_1.showAxis("left")
self.plt_1.showAxis("top")
self.plt_1.getAxis("left").setStyle(showValues=False)
self.plt_1.getAxis("top").setStyle(showValues=False)
self.plt_1.getAxis("bottom").setStyle(showValues=False)
self.plt_1.getAxis("right").setWidth(int(65))
#
self.plt_2.showAxis("right")
self.plt_2.showAxis("left")
self.plt_2.showAxis("top")
self.plt_2.getAxis("left").setStyle(showValues=False)
self.plt_2.getAxis("top").setStyle(showValues=False)
self.plt_2.getAxis("bottom").setStyle(showValues=False)
self.plt_2.getAxis("right").setWidth(int(65))
#
self.plt_3.showAxis("right")
self.plt_3.showAxis("left")
self.plt_3.showAxis("top")
self.plt_3.getAxis("left").setStyle(showValues=False)
self.plt_3.getAxis("top").setStyle(showValues=False)
self.plt_3.getAxis("right").setWidth(int(65))
# Config Frame
self.plt_0.getAxis("bottom").setPen(pg.mkPen(color="#505050", width=1))
self.plt_0.getAxis("right").setPen(pg.mkPen(color="#505050", width=1))
self.plt_0.getAxis("top").setPen(pg.mkPen(color="#505050", width=1))
self.plt_0.getAxis("left").setPen(pg.mkPen(color="#505050", width=1))
#
self.plt_1.getAxis("bottom").setPen(pg.mkPen(color="#606060", width=1))
self.plt_1.getAxis("right").setPen(pg.mkPen(color="#606060", width=1))
self.plt_1.getAxis("top").setPen(pg.mkPen(color="#606060", width=1))
self.plt_1.getAxis("left").setPen(pg.mkPen(color="#606060", width=1))
#
self.plt_2.getAxis("bottom").setPen(pg.mkPen(color="#606060", width=1))
self.plt_2.getAxis("right").setPen(pg.mkPen(color="#606060", width=1))
self.plt_2.getAxis("top").setPen(pg.mkPen(color="#606060", width=1))
self.plt_2.getAxis("left").setPen(pg.mkPen(color="#606060", width=1))
#
self.plt_3.getAxis("bottom").setPen(pg.mkPen(color="#606060", width=1))
self.plt_3.getAxis("right").setPen(pg.mkPen(color="#606060", width=1))
self.plt_3.getAxis("top").setPen(pg.mkPen(color="#606060", width=1))
self.plt_3.getAxis("left").setPen(pg.mkPen(color="#606060", width=1))
# Set Link - Axis
self.plt_1.setXLink(self.plt_3)
self.plt_2.setXLink(self.plt_3)
# Update mc_mode
self._update_mc_mode()
# MC random
np.random.seed(self.seed)
print(f"\n{Fore.LIGHTYELLOW_EX}LOADING DATA...{Fore.RESET}")
def start(
self,
stop_rate: float | int | None = None,
gain_rate: float | int | None = None,
opers_fee: float | int | None = None,
metrics_riskfree: float | int = 10,
metrics_period: float | int = 365,
dist_bins: int = 50,
show_candles: bool = False,
strategy: Optional[Callable] = None,
str_params: list | None = None,
mc_paths_colors: bool = True,
mc_line_plots: bool = False,
mc_dist_bins: int = 50,
mc_nsim: int = 200,
mc_nsteps: int | None = None,
mc_sigma: float | int = 0.5,
mc_s0: float | int | None = None,
mc_r: float | int = 0.5,
mc_dt: float = (1 / 365),
mc_lambda_: float | int = 0.1,
mc_mu_y: float | int = 0.02,
mc_sigma_y: float | int = 0.1,
mc_rndnpositions: int = 10,
sim_taskmode: str = "process",
sim_method: str = "grid",
sim_params: dict = None,
sim_nbest: int = 10,
sim_nrandsims: int = 15,
sim_bayesopt_ncalls: int = 5,
sim_bayesopt_spaces: list | None = None,
sim_bayesopt_kwargs: dict = {},):
"""
This method initializes the project's graphical engine by configuring resources according to user-defined arguments.
Args:
stop_rate (int): Stop loss threshold (%).
gain_rate (int): Take profit threshold (%).
opers_fee (int): Emulation of operation fee (%).
metrics_riskfree (int): Risk-free parameter (%) used in Sharpe-Ratio and Sortino-Ratio calculations. Default is 10.
metrics_period (int): Period parameter for Sharpe-Ratio, Sortino-Ratio, and Calmar-Ratio calculations. Default is 365.
dist_bins (int): Number of bins for the price distribution plot. Default is 50.
show_candles (bool): Plot candlesticks. Disable for better performance with large datasets. Default is False.
strategy (function): Strategy function. Required for Monte Carlo tests and hyperparameter searches.
str_params (list): Strategy parameters. Necessary for Monte Carlo tests.
mc_paths_colors (bool): Enable Monte Carlo test path line coloring. Default is True.
mc_line_plots (bool): Enable Monte Carlo test path line plots. Disable for better performance at scale. Default is False.
mc_dist_bins (int): Number of bins for Monte Carlo test distribution plots. Default is 50.
mc_nsim (int): Number of Monte Carlo test simulations. Default is 200.
mc_nsteps (int): Number of Monte Carlo test steps, based on the length of the time frame. Default is None.
mc_sigma (float | int): Random price volatility (σ) for Black-Scholes and Merton models. Default is 0.5 (%).
mc_s0 (float | int): Initial stock price for Monte Carlo test (Black-Scholes and Merton models). Default is None.
mc_r (float | int): Risk-free rate for Monte Carlo test (Black-Scholes and Merton models). Default is 0.5.
mc_dt (float): Time step for Monte Carlo test (Black-Scholes and Merton models). Default is (1 / 365).
mc_lambda_ (float | int): Jump intensity (λ) for Monte Carlo test (Merton model). Default is 0.1.
mc_mu_y (float | int): Mean of jump sizes (μ_y) for Monte Carlo test (Merton model). Default is 0.02.
mc_sigma_y (float | int): Standard deviation of jump sizes (σ_y) for Monte Carlo test (Merton model). Default is 0.1.
mc_rndnpositions (int): Window size to randomize starting or ending positions in Monte Carlo test. Default is 10.
sim_taskmode (str): Simulation task mode ("process" or "thread"). Default is "process".
sim_method (str): Hyperparameter simulation method ("grid", "random", or "bayesian-opt"). Default is "grid".
sim_params (dict): Hyperparameter simulation strategy parameters for "grid" or "random" methods. Default is None.
sim_nbest (int): Number of best curves to show in hyperparameter search simulations. Default is 10.
sim_nrandsims (int): Number of random simulations for hyperparameter search simulations. Default is 15.
sim_bayesopt_ncalls (int): Number of calls for Bayesian optimization (scikit-optimize). Default is 5.
sim_bayesopt_spaces (list): Search spaces for Bayesian optimization (scikit-optimize). Default is None.
sim_bayesopt_kwargs (dict): Additional kwargs for Bayesian optimization (scikit-optimize). Default is {}.
"""
# Set positions | pred & true
if "pred" not in self.df_1.columns:
self.df_1["pred"] = self.df_1.positions
else:
self.df_1["positions"] = self.df_1.pred
self.pos_pred = self.df_1.pred.values
self.stop_rate = stop_rate
self.gain_rate = gain_rate
self.opers_fee = opers_fee
self.risk_free = metrics_riskfree
self.period = metrics_period
self.dist_bins = dist_bins
self.show_candles = show_candles
self.strategy = strategy
self.str_params = str_params
self.mc_paths_colors = mc_paths_colors
self.mc_line_plots = mc_line_plots
self.mc_dist_bins = mc_dist_bins
self.mc_nsim = mc_nsim
self.mc_nsteps = mc_nsteps
self.mc_sigma = mc_sigma
self.mc_s0 = mc_s0
self.mc_r = mc_r
self.mc_dt = mc_dt
self.mc_lambda_ = mc_lambda_
self.mc_mu_y = mc_mu_y
self.mc_rndnpositions = mc_rndnpositions
self.mc_sigma_y = mc_sigma_y
self.sim_taskmode = sim_taskmode
self.sim_method = sim_method
self.sim_params = sim_params
self.sim_nbest = sim_nbest
self.sim_nrandsims = sim_nrandsims
self.sim_bayesopt_spaces = sim_bayesopt_spaces
self.sim_bayesopt_kwargs = sim_bayesopt_kwargs
self.sim_bayesopt_ncalls = sim_bayesopt_ncalls
# Set first position
try:
if self.df_1.pred.values[0] == 0:
self.initial_pos = abs(self.pos_pred[self.pos_pred != 0][0])
else:
self.initial_pos = abs(self.pos_pred[0])
except Exception as e:
exception_type = f"EXCEPTION_TYPE: {type(e).__name__}\n"
exception_message = f"EXCEPTION_MESSAGE: {str(e)}"
track_line = f" L-{traceback.extract_tb(e.__traceback__)[0].lineno}"
print(
f"{Fore.LIGHTYELLOW_EX}{exception_type}{exception_message}{track_line}"
)
print(f"SET INITIAL POSITON TO 1{Fore.RESET}")
# raise sys.exc_info()[0]
self.initial_pos = 1
# Set y-true values
if "true" in self.df_1.columns:
self.pos_true = self.df_1.true.values
else:
self.pos_true = np.nan
# Process mouse events
self._mouse_events()
# Process df_1
self.df_1 = process_df(
self.df_1,
self.pos_true,
self.pos_pred,
self.stop_rate,
self.gain_rate,
self.initial_pos,
)
# Set crosshair
self._set_crosshair()
print(f"\n{Fore.LIGHTYELLOW_EX}INITIALIZING LabQuant...{Fore.RESET}")
# Set df_main & df_str_params
self.df_main = self.df_1.copy()
if self.str_params is not None:
self.df_str_params = self.str_params[0].copy()
# Plot logic
if self.test_:
if self.show_roi:
self.roi_plot_var = 1
self._update_plot_by_roi()
else:
self._show_plot()
else:
self.win_1.show()
if self.show_roi:
self.roi_plot_var = 1
QtCore.QTimer.singleShot(100, self._update_plot_by_roi)
else:
QtCore.QTimer.singleShot(100, self._show_plot)
# QApplication Main loop
if (
self.exec_loop
and (sys.flags.interactive != 1)
or not hasattr(QtCore, "PYQT_VERSION")
):
QApplication.instance().exec_()
def _show_plot(self):
"""
Displays the signals interface and switches between the signals and the performance interface.
"""
self.plt_1.clear()
self.plt_2.clear()
self.plt_3.clear()
self.button_1.show()
self.risk_metrics_textitem.hide()
self.pnl_textitem.hide()
self.drawdown_textitem.hide()
self.dist_textitem.hide()
self.scores_textitem.hide()
self.plt_1.showButtons()
self.plt_1.showAxis("top")
self.plt_1.showAxis("bottom")
self.plt_2.getAxis("bottom").setStyle(showValues=False)
# Enable | Disable simulations
self._simulations_logic()
# Returns pct
self.returns = self.df_1.c.pct_change()
# Strategy returns
self.strategy_returns_pred = (
self.returns * self.df_1.positions_pred.shift(1)
).fillna(0)
self.strategy_returns_true = (
self.returns * self.df_1.positions_true.shift(1)
).fillna(0)
# Apply opers fees
if self.opers_fee is not None:
strategy_returns_pred_ = apply_tax(
self.opers_fee,
self.strategy_returns_pred.values,
self.df_1.positions.values,
)
self.strategy_returns_pred = pd.Series(strategy_returns_pred_)
# Process Hit-Rate
hitrate = get_hitrate(self.df_1.signals_pred, self.strategy_returns_pred)
text = (
"HIT-RATE: {}% ".format(decimal_round(hitrate[2], 1))
+ "n-HITS: {} ".format(str(hitrate[0]))
+ "n-LOSSES: {} ".format(str(hitrate[1]))
+ "n-TRADS: {} ".format(str(hitrate[3]))
)
self.hit_trads_textitem.setText(text=text)
self.hit_trads_textitem.show()
self.n_trads = hitrate[3]
# Show Signals
if self.showplt1 == 1:
self.roi_plot_var = 1
self.value_var_hist_axis.value = 0
self.plt_1.show()
self.plt_2.show()
self.plt_3.show()
self._process_scatter()
self.button_2.show()
self.button_4.hide()
self.button_6.show()
self.button_9.hide()
self.returns_textitem.hide()
self.plt_2.setXLink(self.plt_3)
# Scatter plot y_true
if np.all(np.isnan(self.pos_true)):
self.plt_2.setTitle("Trade-Analysis")
self.plt_1.hide()
self.plt_1.hideAxis("top")
self.plt_1.hideAxis("bottom")
self.plt_1.hideButtons()
self.plot_widget_1.hide()
self.plot_widget_2.show()
self.plot_widget_3.show()
self.plt_1.setTitle("")
self.plt_1.setContentsMargins(0, 0, 0, 0)
self.plt_2.setContentsMargins(0, 0, 0, 0)
self.splitter.setSizes([50, 40, 0, 400, 150])
if self.show_candles:
candlestick_data = list(
zip(
self.df_1.dateindex.values,
self.df_1.o.values,
self.df_1.h.values,
self.df_1.l.values,
self.df_1.c.values,
)
)
item = CandlestickItem(candlestick_data)
self.plt_2.addItem(item)
else:
self.plt_2.plot(self.df_1.dateindex.values, self.df_1.c.values)
else:
self.plt_1.show()
self.plt_1.setTitle("y-true signals")
self.plt_2.setTitle("y-pred signals")
self.plt_1.plot(self.df_1.dateindex.values, self.df_1.c.values)
self.plt_2.plot(self.df_1.dateindex.values, self.df_1.c.values)
self.plot_widget_1.show()
self.plot_widget_2.show()
self.plot_widget_3.show()
self.plt_1.setContentsMargins(0, 0, 0, 0)
self.plt_2.setContentsMargins(0, 0, 0, 0)
self.splitter.setSizes([50, 40, 200, 200, 150])
text = "SCORE: {} ".format(
decimal_round(
accuracy_score(self.df_1["true"], self.df_1["pred"]), 2
)
) + "F1-SCORE: {} ".format(
decimal_round(
f1_score(
self.df_1["true"], self.df_1["pred"], average="weighted"
),
2,
)
)
self.scores_textitem.setText(text=text)
self.scores_textitem.show()
if not np.all(np.isnan(self.pos_true)):
self.plt_1.addItem(self.scatter_long_true)
self.plt_1.addItem(self.scatter_short_true)
self.plt_1.addItem(self.scatter_short_true_plus)
self.plt_1.addItem(self.scatter_short_true_minus)
self.plt_1.addItem(self.scatter_long_true_plus)
self.plt_1.addItem(self.scatter_long_true_minus)
self.plt_1.addItem(self.scatter_exit_true_long)
self.plt_1.addItem(self.scatter_exit_true_short)
self.plt_1.addItem(self.scatter_exit_gain_true)
self.plt_1.addItem(self.scatter_exit_stop_true)
self.plt_2.addItem(self.scatter_long_pred)
self.plt_2.addItem(self.scatter_short_pred)
self.plt_2.addItem(self.scatter_short_pred_plus)
self.plt_2.addItem(self.scatter_short_pred_minus)
self.plt_2.addItem(self.scatter_long_pred_plus)
self.plt_2.addItem(self.scatter_long_pred_minus)
self.plt_2.addItem(self.scatter_exit_pred_long)
self.plt_2.addItem(self.scatter_exit_pred_short)
self.plt_2.addItem(self.scatter_exit_gain_pred)
self.plt_2.addItem(self.scatter_exit_stop_pred)
# y_true x y_pred
if np.all(np.isnan(self.pos_true)):
self.plt_3.setTitle("Positions")
else:
self.plt_3.setTitle(
"y_true positions (green) | y_pred positions (red)"
)
self.plt_3.plot(
self.df_1.dateindex.values,
(self.df_1.positions_true * self.initial_pos).values,
pen={"color": (127, 200, 0), "width": 0.6},
) # GREEN
self.plt_3.plot(
self.df_1.dateindex.values,
(self.df_1.positions_pred * self.initial_pos).values,
pen={"color": (255, 20, 30)},
)
self.showplt1 = 2
self.showplt2 = 2
self.showplt11 = 1
if self.checkbox_scatter.isChecked():