-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathOptimizeV7.py
More file actions
6727 lines (6116 loc) · 372 KB
/
OptimizeV7.py
File metadata and controls
6727 lines (6116 loc) · 372 KB
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
import streamlit as st
import pbgui_help
import json
import psutil
import sys
import platform
import subprocess
import glob
import configparser
import time
import multiprocessing
from Exchange import Exchange, V7
from PBCoinData import CoinData
from pbgui_func import pb7dir, pb7venv, PBGDIR, load_symbols_from_ini, error_popup, info_popup, get_navi_paths, replace_special_chars, render_log_viewer, redirect_to_fastapi_v7_backtest_draft, redirect_to_fastapi_v7_backtest_queue_draft
from pbgui_purefunc import pb7_suite_preflight_errors
import uuid
from pathlib import Path, PurePath
from User import Users
import shutil
import datetime
import BacktestV7
from Config import (
ConfigV7,
Bounds,
Logging,
SHARED_METRICS,
CURRENCY_METRICS,
get_all_metrics_list,
get_metrics_by_group,
get_metric_groups,
get_metric_group,
get_limits_type_help_text,
get_limits_metric_list_help_text,
is_currency_metric,
canonicalize_metric_name,
ALLOWED_OVERRIDES,
get_aggregate_metrics,
ConfigV7Editor,
)
from PBCoinData import normalize_symbol
import traceback
from logging_helpers import human_log as _log
import os
import fnmatch
import math
class OptimizeV7QueueItem:
def __init__(self):
self.name = None
self.filename = None
self.json = None
self.exchange = None
self.starting_config = False
self.log = None
self.log_show = False
self.pid = None
self.pidfile = None
def remove(self):
self.stop()
file = Path(f'{PBGDIR}/data/opt_v7_queue/{self.filename}.json')
file.unlink(missing_ok=True)
self.log.unlink(missing_ok=True)
# Also clean up old log location in case it was never migrated
old_log = Path(f'{PBGDIR}/data/opt_v7_queue/{self.filename}.log')
old_log.unlink(missing_ok=True)
self.pidfile.unlink(missing_ok=True)
def load_log(self, log_size: int = 50):
if self.log:
if self.log.exists():
# Open the file in binary mode to handle raw bytes
with open(self.log, 'rb') as f:
# Move the pointer to the last log_size KB (100 * 1024 bytes)
f.seek(0, 2) # Move to the end of the file
file_size = f.tell()
# Ensure that we don't try to read more than the file size
start_pos = max(file_size - log_size * 1024, 0)
f.seek(start_pos)
# Read the last 100 KB (or less if the file is smaller)
return f.read().decode('utf-8', errors='ignore') # Decode and ignore errors
@st.fragment
def view_log(self):
col1, col2, col3 = st.columns([1,1,8], vertical_alignment="bottom")
with col1:
st.checkbox("Reverse", value=True, key=f'reverse_view_log_{self.filename}')
with col2:
st.selectbox("view last kB", [50, 100, 250, 500, 1000, 2000, 5000, 10000, 100000], key=f'size_view_log_{self.filename}')
with col3:
if st.button(":material/refresh:", key=f'refresh_view_log_{self.filename}'):
st.rerun(scope="fragment")
logfile = self.load_log(st.session_state[f'size_view_log_{self.filename}'])
if logfile:
if st.session_state[f'reverse_view_log_{self.filename}']:
logfile = '\n'.join(logfile.split('\n')[::-1])
with st.container(height=1200):
st.code(logfile)
def status(self):
if self.is_optimizing():
return "optimizing..."
if self.is_running():
return "running"
if self.is_finish():
return "complete"
if self.is_error():
return "error"
else:
return "not started"
def is_existing(self):
if Path(f'{PBGDIR}/data/opt_v7_queue/{self.filename}.json').exists():
return True
return False
def is_running(self):
self.load_pid()
try:
if self.pid and psutil.pid_exists(self.pid) and any(sub.lower().endswith("optimize.py") for sub in psutil.Process(self.pid).cmdline()):
return True
except (psutil.NoSuchProcess, psutil.ZombieProcess, psutil.AccessDenied):
pass
return False
def is_finish(self):
log = self.load_log(log_size=1000)
if log:
if "successfully processed optimize_results" in log or "Optimization complete" in log:
return True
else:
return False
else:
return False
def is_error(self):
log = self.load_log(log_size=1000)
if log:
if "successfully processed optimize_results" in log or "Optimization complete" in log:
return False
else:
return True
else:
return False
def is_optimizing(self):
if self.is_running():
log = self.load_log(log_size=1000)
if log:
if "Optimization complete" in log:
return False
elif "Initial population size" in log:
return True
else:
return False
def stop(self):
if self.is_running():
parent = psutil.Process(self.pid)
children = parent.children(recursive=True)
children.append(parent)
for p in children:
try:
p.kill()
except psutil.NoSuchProcess:
pass
def load_pid(self):
if self.pidfile.exists():
with open(self.pidfile) as f:
pid = f.read()
self.pid = int(pid) if pid.isnumeric() else None
def save_pid(self):
with open(self.pidfile, 'w') as f:
f.write(str(self.pid))
def run(self):
if not self.is_finish() and not self.is_running():
def _emit_error(message: str) -> None:
try:
st.error(message)
except Exception:
_log('OptimizeV7', message, level='ERROR')
try:
with open(self.json, "r", encoding="utf-8") as f:
opt_config = json.load(f)
except Exception as exc:
msg = f"Failed to read optimize config JSON: {self.json} ({exc})"
_emit_error(msg)
try:
self.log.parent.mkdir(parents=True, exist_ok=True)
with open(self.log, "w", encoding="utf-8") as log_f:
log_f.write(msg + "\n")
except Exception:
pass
return
preflight_errors = pb7_suite_preflight_errors(opt_config)
if preflight_errors:
msg = "\n\n".join(preflight_errors)
_emit_error(msg)
try:
self.log.parent.mkdir(parents=True, exist_ok=True)
with open(self.log, "w", encoding="utf-8") as log_f:
log_f.write(msg + "\n")
except Exception:
pass
return
old_os_path = os.environ.get('PATH', '')
new_os_path = os.path.dirname(pb7venv()) + os.pathsep + old_os_path
os.environ['PATH'] = new_os_path
if self.starting_config:
cmd = [pb7venv(), '-u', PurePath(f'{pb7dir()}/src/optimize.py'), '-t', str(PurePath(f'{self.json}')), str(PurePath(f'{self.json}'))]
else:
cmd = [pb7venv(), '-u', PurePath(f'{pb7dir()}/src/optimize.py'), str(PurePath(f'{self.json}'))]
self.log.parent.mkdir(parents=True, exist_ok=True)
log = open(self.log,"w")
if platform.system() == "Windows":
creationflags = subprocess.DETACHED_PROCESS
creationflags |= subprocess.CREATE_NO_WINDOW
btm = subprocess.Popen(cmd, stdout=log, stderr=log, cwd=pb7dir(), text=True, creationflags=creationflags)
else:
btm = subprocess.Popen(cmd, stdout=log, stderr=log, cwd=pb7dir(), text=True, start_new_session=True)
self.pid = btm.pid
self.save_pid()
os.environ['PATH'] = old_os_path
class OptimizeV7Queue:
def __init__(self):
self.items = []
self.d = []
self.sort = "Time"
self.sort_order = True
pb_config = configparser.ConfigParser()
pb_config.read('pbgui.ini')
if not pb_config.has_section("optimize_v7"):
pb_config.add_section("optimize_v7")
pb_config.set("optimize_v7", "autostart", "False")
with open('pbgui.ini', 'w') as f:
pb_config.write(f)
self._autostart = eval(pb_config.get("optimize_v7", "autostart"))
self.load_sort_queue()
if self._autostart:
self.run()
@property
def autostart(self):
return self._autostart
@autostart.setter
def autostart(self, new_autostart):
self._autostart = new_autostart
pb_config = configparser.ConfigParser()
pb_config.read('pbgui.ini')
pb_config.set("optimize_v7", "autostart", str(self._autostart))
with open('pbgui.ini', 'w') as f:
pb_config.write(f)
if self._autostart:
self.run()
else:
self.stop()
def add(self, qitem : OptimizeV7QueueItem):
for index, item in enumerate(self.items):
if item.filename == qitem.filename:
return
self.items.append(qitem)
def remove_finish(self, all : bool = False):
if all:
self.stop()
for item in self.items[:]:
if item.is_finish():
item.remove()
self.items.remove(item)
else:
if all:
item.stop()
item.remove()
self.items.remove(item)
if self._autostart:
self.run()
self.refresh()
def remove_selected(self):
ed_key = st.session_state.ed_key
ed = st.session_state[f'view_opt_v7_queue_{ed_key}']
for row in ed["edited_rows"]:
if "delete" in ed["edited_rows"][row]:
if ed["edited_rows"][row]["delete"]:
self.d[row]["item"].remove()
self.items.remove(self.d[row]["item"])
self.refresh()
def running(self):
for item in self.items:
if item.is_running():
return True
return False
def downloading(self):
for item in self.items:
if item.is_running() and not item.is_optimizing():
return True
return False
def load(self):
dest = Path(f'{PBGDIR}/data/opt_v7_queue')
p = str(Path(f'{dest}/*.json'))
items = glob.glob(p)
for item in items:
with open(item, "r", encoding='utf-8') as f:
q_config = json.load(f)
qitem = OptimizeV7QueueItem()
qitem.name = q_config["name"]
qitem.filename = q_config["filename"]
qitem.json = q_config["json"]
config = OptimizeV7Item(qitem.json)
qitem.exchange = q_config["exchange"]
qitem.starting_config = config.config.pbgui.starting_config
qitem.log = Path(f'{PBGDIR}/data/logs/optimizes/{qitem.filename}.log')
qitem.pidfile = Path(f'{PBGDIR}/data/opt_v7_queue/{qitem.filename}.pid')
self.add(qitem)
# Remove items that are not existing anymore
for item in self.items[:]:
if not Path(f'{PBGDIR}/data/opt_v7_queue/{item.filename}.json').exists():
item.remove()
self.items.remove(item)
def run(self):
if not self.is_running():
cmd = [sys.executable, '-u', PurePath(f'{PBGDIR}/OptimizeV7.py')]
dest = Path(f'{PBGDIR}/data/logs')
if not dest.exists():
dest.mkdir(parents=True)
logfile = Path(f'{dest}/OptimizeV7.log')
if logfile.exists():
if logfile.stat().st_size >= 1048576:
logfile.replace(f'{str(logfile)}.old')
log = open(logfile,"a")
if platform.system() == "Windows":
creationflags = subprocess.DETACHED_PROCESS
creationflags |= subprocess.CREATE_NO_WINDOW
subprocess.Popen(cmd, stdout=log, stderr=log, cwd=PBGDIR, text=True, creationflags=creationflags)
else:
subprocess.Popen(cmd, stdout=log, stderr=log, cwd=PBGDIR, text=True, start_new_session=True)
def stop(self):
if self.is_running():
self.pid().kill()
def is_running(self):
if self.pid():
return True
return False
def pid(self):
for process in psutil.process_iter():
try:
cmdline = process.cmdline()
except (psutil.AccessDenied, psutil.ZombieProcess, psutil.NoSuchProcess):
continue
if any("OptimizeV7.py" in sub for sub in cmdline):
return process
@staticmethod
def _exchange_to_str(exchange_value) -> str:
if exchange_value is None:
return ""
if isinstance(exchange_value, (list, tuple, set)):
return ",".join(str(x) for x in exchange_value)
if isinstance(exchange_value, dict):
try:
return json.dumps(exchange_value, sort_keys=True)
except Exception:
return str(exchange_value)
return str(exchange_value)
def refresh(self):
# Remove items from d that are not in items anymore
self.d = [item for item in self.d if item.get('filename') in [i.filename for i in self.items]]
# Add items to d that are in items but not in d
for item in self.items:
if not any(d_item.get('filename') == item.filename for d_item in self.d):
self.d.append({
'id': len(self.d),
'run': item.is_running(),
'Status': item.status(),
'edit': False,
'log': item.log_show,
'delete': False,
'starting_config': item.starting_config,
'name': item.name,
'filename': item.filename,
'Time': datetime.datetime.fromtimestamp(Path(f'{PBGDIR}/data/opt_v7_queue/{item.filename}.json').stat().st_mtime),
'exchange': self._exchange_to_str(item.exchange),
'finish': item.is_finish(),
'item': item,
})
# Update status of all items in d
for row in self.d:
for item in self.items:
if row['filename'] == item.filename:
row['run'] = item.is_running()
row['Status'] = item.status()
row['log'] = item.log_show
row['finish'] = item.is_finish()
def view(self):
if not self.items:
self.load()
self.refresh()
if not "ed_key" in st.session_state:
st.session_state.ed_key = 0
ed_key = st.session_state.ed_key
if f'view_opt_v7_queue_{ed_key}' in st.session_state:
ed = st.session_state[f'view_opt_v7_queue_{ed_key}']
for row in ed["edited_rows"]:
if "run" in ed["edited_rows"][row]:
if ed["edited_rows"][row]["run"]:
self.d[row]["item"].run()
else:
self.d[row]["item"].stop()
self.refresh()
if "edit" in ed["edited_rows"][row]:
st.session_state.opt_v7 = OptimizeV7Item(f'{PBGDIR}/data/opt_v7/{self.d[row]["item"].name}.json')
st.session_state["_opt_v7_main_view_next"] = "Config"
st.rerun()
if "log" in ed["edited_rows"][row]:
if ed["edited_rows"][row]["log"]:
# Exclusive selection: clear all others first
for i, d_row in enumerate(self.d):
d_row["item"].log_show = (i == int(row))
d_row["log"] = (i == int(row))
log_file = self.d[int(row)]["item"].log
# Migrate old log location (data/opt_v7_queue/) → new location (data/logs/optimizes/)
if log_file and not log_file.exists():
old_log = Path(f'{PBGDIR}/data/opt_v7_queue/{log_file.name}')
if old_log.exists():
log_file.parent.mkdir(parents=True, exist_ok=True)
try:
old_log.rename(log_file)
except Exception:
pass
if log_file:
st.session_state["opt_v7_queue_log_preselect"] = f"optimizes/{log_file.name}"
# Bump ed_key so data_editor re-renders with fresh checkbox state
st.session_state.ed_key = ed_key + 1
st.session_state["_opt_v7_main_view_next"] = "Log"
st.rerun()
else:
self.d[int(row)]["item"].log_show = False
self.d[int(row)]["log"] = False
# Clear log selection when returning from Log tab
prev = st.session_state.get("_opt_v7_queue_prev_view", "Queue")
if prev == "Log":
any_set = any(d_row["log"] for d_row in self.d)
if any_set:
for d_row in self.d:
d_row["item"].log_show = False
d_row["log"] = False
st.session_state.ed_key = st.session_state.ed_key + 1
st.session_state["_opt_v7_queue_prev_view"] = "Queue"
st.rerun()
st.session_state["_opt_v7_queue_prev_view"] = "Queue"
column_config = {
# "id": None,
"run": st.column_config.CheckboxColumn('Start/Stop', default=False),
"edit": st.column_config.CheckboxColumn('Edit'),
"log": st.column_config.CheckboxColumn(label="View Logfile"),
"delete": st.column_config.CheckboxColumn(label="Delete"),
"item": None,
}
#Display Queue
height = 36+(len(self.d))*35
if height > 1000: height = 1016
if "sort_opt_v7_queue" in st.session_state:
if st.session_state.sort_opt_v7_queue != self.sort:
self.sort = st.session_state.sort_opt_v7_queue
self.save_sort_queue()
else:
st.session_state.sort_opt_v7_queue = self.sort
if "sort_opt_v7_queue_order" in st.session_state:
if st.session_state.sort_opt_v7_queue_order != self.sort_order:
self.sort_order = st.session_state.sort_opt_v7_queue_order
self.save_sort_queue()
else:
st.session_state.sort_opt_v7_queue_order = self.sort_order
# Display sort options
col1, col2 = st.columns([1, 9], vertical_alignment="bottom")
with col1:
st.selectbox("Sort by:", ['Time', 'name', 'Status', 'exchange', 'finish'], key=f'sort_opt_v7_queue', index=0)
with col2:
st.checkbox("Reverse", value=True, key=f'sort_opt_v7_queue_order')
self.d = sorted(self.d, key=lambda x: x[st.session_state[f'sort_opt_v7_queue']], reverse=st.session_state[f'sort_opt_v7_queue_order'])
st.data_editor(data=self.d, height="auto", key=f'view_opt_v7_queue_{ed_key}', hide_index=None, column_order=None, column_config=column_config, disabled=['id','filename','starting_config','name','finish','running'])
def view_log(self):
"""Render the streaming log viewer for the currently selected optimize job log."""
st.session_state["_opt_v7_queue_prev_view"] = "Log"
_log_item_name = ""
for d_row in self.d:
if d_row.get("log"):
_log_item_name = str(d_row.get("name") or "")
item = d_row["item"]
# Ensure log is migrated to the canonical location before viewing
if item.log and not item.log.exists():
old_log = Path(f'{PBGDIR}/data/opt_v7_queue/{item.log.name}')
if old_log.exists():
item.log.parent.mkdir(parents=True, exist_ok=True)
try:
old_log.rename(item.log)
st.session_state["opt_v7_queue_log_preselect"] = f"optimizes/{item.log.name}"
except Exception:
pass
break
preselect = st.session_state.get("opt_v7_queue_log_preselect", "")
if not preselect:
for item in self.items:
if item.is_running() and item.log:
preselect = f"optimizes/{item.log.name}"
break
render_log_viewer(preselect=preselect, iframe_height_offset=300, display_title=_log_item_name)
def load_sort_queue(self):
pb_config = configparser.ConfigParser()
pb_config.read('pbgui.ini')
self.sort = pb_config.get("optimize_v7", "sort_queue") if pb_config.has_option("optimize_v7", "sort_queue") else "Time"
self.sort_order = eval(pb_config.get("optimize_v7", "sort_queue_order")) if pb_config.has_option("optimize_v7", "sort_queue_order") else True
def save_sort_queue(self):
pb_config = configparser.ConfigParser()
pb_config.read('pbgui.ini')
if not pb_config.has_section("optimize_v7"):
pb_config.add_section("optimize_v7")
pb_config.set("optimize_v7", "sort_queue", str(self.sort))
pb_config.set("optimize_v7", "sort_queue_order", str(self.sort_order))
with open('pbgui.ini', 'w') as f:
pb_config.write(f)
class OptimizeV7Results:
def __init__(self):
self.results_path = Path(f'{pb7dir()}/optimize_results')
self.selected_analysis = "analyses_combined"
self.results_new = []
self.results_d = []
self.sort_results = "Result Time"
self.sort_results_order = True
self.paretos = []
self.filter = ""
self.initialize()
self.load_sort_results()
def initialize(self):
self.find_results()
@staticmethod
def _reset_pareto_selection_state():
current_key = st.session_state.get("ed_key", 0)
st.session_state.pop(f'select_paretos_{current_key}', None)
st.session_state.ed_key = current_key + 1
@staticmethod
def _dedupe_paths(paths: list[str]) -> list[str]:
unique_paths = []
seen = set()
for path in paths:
if not path or path in seen:
continue
unique_paths.append(path)
seen.add(path)
return unique_paths
def find_results(self):
if self.results_path.exists():
p = str(self.results_path) + "/*/all_results.bin"
self.results_new = glob.glob(p, recursive=False)
self.results_d = []
def find_result_name_new(self, result_file):
p = str(PurePath(result_file).parent / "pareto" / "*.json")
files = glob.glob(p, recursive=False)
if files:
config = ConfigV7(files[0])
config.load_config()
result_time = Path(files[0]).stat().st_mtime
return config.backtest.base_dir.split("/")[-1], result_time
else:
return None, None
def view_results(self):
# Init
if not "ed_key" in st.session_state:
st.session_state.ed_key = 0
ed_key = st.session_state.ed_key
if "select_opt_v7_result_filter" in st.session_state:
if st.session_state.select_opt_v7_result_filter != self.filter:
self.filter = st.session_state.select_opt_v7_result_filter
self.results_new = []
self.results_d = []
self.find_results()
else:
st.session_state.select_opt_v7_result_filter = self.filter
# Remove results that are not in the filter
if not self.filter == "":
for result in self.results_new.copy():
name, result_time = self.find_result_name_new(result)
if not name:
self.results_new.remove(result)
continue
if not fnmatch.fnmatch(name.lower(), self.filter.lower()):
self.results_new.remove(result)
st.text_input("Filter by Optimize Name", value="", help=pbgui_help.smart_filter, key="select_opt_v7_result_filter")
if not self.results_d:
for id, opt in enumerate(self.results_new):
name, result_time = self.find_result_name_new(opt)
if name:
result = PurePath(opt).parent.name
self.results_d.append({
'id': id,
'Name': name,
'Result Time': datetime.datetime.fromtimestamp(result_time),
'view': False,
'3d plot': False,
'🎯 explorer': False,
'delete' : False,
'Result': result,
'index': opt,
})
column_config_new = {
"id": None,
"edit": st.column_config.CheckboxColumn(label="Edit"),
"view": st.column_config.CheckboxColumn(label="View Paretos"),
"🎯 explorer": st.column_config.CheckboxColumn(label="🎯 Pareto Explorer"),
"Result Time": st.column_config.DatetimeColumn(format="YYYY-MM-DD HH:mm:ss"),
"Result": st.column_config.TextColumn(label="Result Directory", width="50px"),
}
if "sort_opt_v7_results" in st.session_state:
if st.session_state.sort_opt_v7_results != self.sort_results:
self.sort_results = st.session_state.sort_opt_v7_results
self.save_sort_results()
else:
st.session_state.sort_opt_v7_results = self.sort_results
if "sort_opt_v7_results_order" in st.session_state:
if st.session_state.sort_opt_v7_results_order != self.sort_results_order:
self.sort_results_order = st.session_state.sort_opt_v7_results_order
self.save_sort_results()
else:
st.session_state.sort_opt_v7_results_order = self.sort_results_order
# Display sort options
col1, col2 = st.columns([1, 9], vertical_alignment="bottom")
with col1:
st.selectbox("Sort by:", ['Result Time', 'Name'], key=f'sort_opt_v7_results', index=0)
with col2:
st.checkbox("Reverse", value=True, key=f'sort_opt_v7_results_order')
# Sort results
self.results_d = sorted(self.results_d, key=lambda x: x[st.session_state[f'sort_opt_v7_results']], reverse=st.session_state[f'sort_opt_v7_results_order'])
#Display optimizes
st.data_editor(data=self.results_d, height=36+(len(self.results_d))*35, key=f'select_optresults_new_{st.session_state.ed_key}', hide_index=None, column_order=None, column_config=column_config_new, disabled=['id','name','index'])
if f'select_optresults_new_{st.session_state.ed_key}' in st.session_state:
ed = st.session_state[f'select_optresults_new_{st.session_state.ed_key}']
for row in ed["edited_rows"]:
if "view" in ed["edited_rows"][row]:
if ed["edited_rows"][row]["view"]:
if self.results_d[row]["Result"]:
self._reset_pareto_selection_state()
st.session_state.opt_v7_pareto = self.results_d[row]["index"]
st.session_state.opt_v7_pareto_name = self.results_d[row]["Name"]
st.session_state.opt_v7_pareto_directory = self.results_d[row]["Result"]
st.rerun()
if "3d plot" in ed["edited_rows"][row]:
if ed["edited_rows"][row]["3d plot"]:
self.run_3d_plot(self.results_d[row]["index"])
st.session_state.ed_key += 1
if "🎯 explorer" in ed["edited_rows"][row]:
if ed["edited_rows"][row]["🎯 explorer"]:
self.run_pareto_explorer(self.results_d[row]["index"])
st.session_state.ed_key += 1
def load_sort_results(self):
pb_config = configparser.ConfigParser()
pb_config.read('pbgui.ini')
self.sort_results = pb_config.get("optimize_v7", "sort_results") if pb_config.has_option("optimize_v7", "sort_results") else "Result Time"
self.sort_results_order = eval(pb_config.get("optimize_v7", "sort_results_order")) if pb_config.has_option("optimize_v7", "sort_results_order") else True
def save_sort_results(self):
pb_config = configparser.ConfigParser()
pb_config.read('pbgui.ini')
if not pb_config.has_section("optimize_v7"):
pb_config.add_section("optimize_v7")
pb_config.set("optimize_v7", "sort_results", str(self.sort_results))
pb_config.set("optimize_v7", "sort_results_order", str(self.sort_results_order))
with open('pbgui.ini', 'w') as f:
pb_config.write(f)
def run_3d_plot(self, index):
# run 3d plot
directory = Path(index).parent / "pareto"
cmd = [pb7venv(), '-u', PurePath(f'{pb7dir()}/src/pareto_store.py'), str(directory)]
if platform.system() == "Windows":
creationflags = subprocess.CREATE_NO_WINDOW
result = subprocess.run(cmd, capture_output=True, cwd=pb7dir(), text=True, creationflags=creationflags)
else:
result = subprocess.run(cmd, capture_output=True, cwd=pb7dir(), text=True, start_new_session=True)
info_popup(f"3D Plot Generated {result.stdout}")
def run_pareto_explorer(self, index):
"""Open Pareto Explorer within PBGui"""
results_dir = Path(index).parent
# Check if all_results.bin exists
all_results_path = results_dir / "all_results.bin"
if not all_results_path.exists():
error_popup(f"❌ all_results.bin not found in {results_dir}")
return
# Store path in session state and navigate to explorer
st.session_state.pareto_explorer_path = str(results_dir)
# Bump ed_key before switching page so the checkbox is cleared on return
st.session_state.ed_key = st.session_state.get("ed_key", 0) + 1
st.switch_page("navi/v7_pareto_explorer.py")
def load_paretos(self, index):
self.paretos = []
paretos_path = PurePath(f'{index}').parent / "pareto"
if Path(paretos_path).exists():
# find all json files in paretos_path
p = str(paretos_path) + "/*.json"
paretos = glob.glob(p, recursive=False)
for pareto in paretos:
with open(pareto, "r", encoding='utf-8') as f:
pareto_data = json.load(f)
pareto_data['index_filename'] = pareto
self.paretos.append(pareto_data)
# sort by index_filename
self.paretos.sort(key=lambda x: x['index_filename'])
def view_pareto(self, index):
if not self.paretos:
self.load_paretos(index)
select_analysis = []
# Detect format:
# - Suite format: has "suite_metrics" with scenarios
# - Non-suite format: has "metrics" with stats but no suite_metrics
# - Old format: has "analyses_combined"
has_suite_metrics = "suite_metrics" in self.paretos[0]
has_metrics_only = "metrics" in self.paretos[0] and not has_suite_metrics
is_new_format = has_suite_metrics or has_metrics_only
if has_suite_metrics:
# Suite format: get scenario labels
scenario_labels = self.paretos[0].get("suite_metrics", {}).get("scenario_labels", [])
elif has_metrics_only:
# Non-suite format: no scenarios, only single result
scenario_labels = []
else:
# Old format
if "analyses_combined" in self.paretos[0]:
select_analysis.append("analyses_combined")
if "analyses" in self.paretos[0]:
for analyse in self.paretos[0]["analyses"]:
select_analysis.append(analyse)
# Validate and fix the selected analysis BEFORE using it
if select_analysis:
if "opt_v7_pareto_select_analysis" not in st.session_state:
st.session_state.opt_v7_pareto_select_analysis = select_analysis[0]
self.selected_analysis = select_analysis[0]
elif st.session_state.opt_v7_pareto_select_analysis not in select_analysis:
# Current selection is invalid, reset to first available
st.session_state.opt_v7_pareto_select_analysis = select_analysis[0]
self.selected_analysis = select_analysis[0]
if "d_paretos" in st.session_state:
del st.session_state.d_paretos
def clear_paretos():
if "d_paretos" in st.session_state:
del st.session_state.d_paretos
self._reset_pareto_selection_state()
# New format: Show dropdowns based on whether suite is enabled
if is_new_format:
if has_suite_metrics:
# Suite format: Two dropdowns for Scenario and Statistic
if "opt_v7_pareto_scenario" not in st.session_state:
st.session_state.opt_v7_pareto_scenario = "Aggregated"
if "opt_v7_pareto_statistic" not in st.session_state:
st.session_state.opt_v7_pareto_statistic = "mean"
col1, col2, col3 = st.columns([1, 1, 2], gap="small")
with col1:
scenario_options = ["Aggregated"] + scenario_labels
st.selectbox('Scenario', options=scenario_options, key="opt_v7_pareto_scenario", on_change=clear_paretos)
with col2:
# Statistic dropdown - only enabled for Aggregated
is_aggregated = st.session_state.opt_v7_pareto_scenario == "Aggregated"
stat_options = ["mean", "min", "max", "std"]
st.selectbox('Statistic', options=stat_options, key="opt_v7_pareto_statistic",
disabled=not is_aggregated, on_change=clear_paretos,
help=pbgui_help.stats_aggregation_help)
else:
# Non-suite format: Only Statistic dropdown (no scenarios)
if "opt_v7_pareto_statistic" not in st.session_state:
st.session_state.opt_v7_pareto_statistic = "mean"
col1, col2 = st.columns([1, 3], gap="small")
with col1:
stat_options = ["mean", "min", "max", "std"]
st.selectbox('Statistic', options=stat_options, key="opt_v7_pareto_statistic",
on_change=clear_paretos,
help=pbgui_help.stats_value_help)
else:
# Old format: single dropdown
col1, col2 = st.columns([1, 3], gap="small")
with col1:
if select_analysis:
if st.session_state.opt_v7_pareto_select_analysis != self.selected_analysis:
self.selected_analysis = st.session_state.opt_v7_pareto_select_analysis
st.selectbox('analyses', options=select_analysis, key="opt_v7_pareto_select_analysis", on_change=clear_paretos)
if not "d_paretos" in st.session_state:
d = []
for id, pareto in enumerate(self.paretos):
name = pareto["index_filename"].split("/")[-1]
if is_new_format:
if has_suite_metrics:
# Suite format: extract from suite_metrics
suite_metrics = pareto.get("suite_metrics", {}).get("metrics", {})
# Determine which value to extract based on scenario/statistic selection
selected_scenario = st.session_state.opt_v7_pareto_scenario
selected_stat = st.session_state.opt_v7_pareto_statistic
# Helper to get the correct value based on scenario and statistic
def get_metric_value(metric_name, default=0):
metric_data = suite_metrics.get(metric_name, {})
if selected_scenario == "Aggregated":
# Use the stats aggregation
return metric_data.get("stats", {}).get(selected_stat, default)
else:
# Use the specific scenario value
return metric_data.get("scenarios", {}).get(selected_scenario, default)
d.append({
'Select': False,
'id': id,
'view': False,
'adg': get_metric_value("adg_usd"),
'mdg': get_metric_value("mdg_usd"),
'drawdown_worst': get_metric_value("drawdown_worst_usd"),
'gain': get_metric_value("gain_usd"),
'loss_profit_ratio': get_metric_value("loss_profit_ratio"),
'position_held_hours_max': get_metric_value("position_held_hours_max"),
'sharpe_ratio': get_metric_value("sharpe_ratio_usd"),
'Name': name,
'file': pareto["index_filename"],
})
else:
# Non-suite format: extract from metrics.stats
metrics_stats = pareto.get("metrics", {}).get("stats", {})
selected_stat = st.session_state.opt_v7_pareto_statistic
# Helper to get the stat value
def get_stat_value(metric_name, default=0):
return metrics_stats.get(metric_name, {}).get(selected_stat, default)
d.append({
'Select': False,
'id': id,
'view': False,
'adg': get_stat_value("adg_usd"),
'mdg': get_stat_value("mdg_usd"),
'drawdown_worst': get_stat_value("drawdown_worst_usd"),
'gain': get_stat_value("gain_usd"),
'loss_profit_ratio': get_stat_value("loss_profit_ratio"),
'position_held_hours_max': get_stat_value("position_held_hours_max"),
'sharpe_ratio': get_stat_value("sharpe_ratio_usd"),
'Name': name,
'file': pareto["index_filename"],
})
else:
# Old format
if select_analysis and st.session_state.opt_v7_pareto_select_analysis in select_analysis:
if st.session_state.opt_v7_pareto_select_analysis == "analyses_combined":
analysis = pareto["analyses_combined"]
# Support both old format (_max suffix) and new format (_mean suffix)
adg = analysis.get("adg_max", analysis.get("adg_mean", 0))
mdg = analysis.get("mdg_max", analysis.get("mdg_mean", 0))
drawdown_worst = analysis.get("drawdown_worst_max", analysis.get("drawdown_worst_mean", 0))
gain = analysis.get("gain_max", analysis.get("gain_mean", 0))
loss_profit_ratio = analysis.get("loss_profit_ratio_max", analysis.get("loss_profit_ratio_mean", 0))
position_held_hours_max = analysis.get("position_held_hours_max_max", analysis.get("position_held_hours_max_mean", 0))
sharpe_ratio = analysis.get("sharpe_ratio_max", analysis.get("sharpe_ratio_mean", 0))
d.append({
'Select': False,
'id': id,
'view': False,
'adg': adg,
'mdg': mdg,
'drawdown_worst': drawdown_worst,
'gain': gain,
'loss_profit_ratio': loss_profit_ratio,
'position_held_hours_max': position_held_hours_max,
'sharpe_ratio': sharpe_ratio,
'Name': name,
'file': pareto["index_filename"],
})
else:
# Check if the selected analysis exists in this pareto's analyses
if st.session_state.opt_v7_pareto_select_analysis in pareto.get("analyses", {}):
analysis = pareto["analyses"][st.session_state.opt_v7_pareto_select_analysis]
d.append({
'Select': False,
'id': id,
'view': False,
'adg': analysis["adg"],
'mdg': analysis["mdg"],
'drawdown_worst': analysis["drawdown_worst"],
'gain': analysis["gain"],
'loss_profit_ratio': analysis["loss_profit_ratio"],
'position_held_hours_max': analysis["position_held_hours_max"],
'sharpe_ratio': analysis["sharpe_ratio"],
'Name': name,
'file': pareto["index_filename"],
})
st.session_state.d_paretos = d
d_paretos = st.session_state.d_paretos
column_config = {
"id": None,
"Select": st.column_config.CheckboxColumn(label="Select"),
"file": None,
"view": st.column_config.CheckboxColumn(label="View"),
"delete": st.column_config.CheckboxColumn(label="Delete"),
}
#Display paretos
height = 36+(len(d_paretos))*35
if height > 1000: height = 1016
st.data_editor(data=d_paretos, height="auto", key=f'select_paretos_{st.session_state.ed_key}', hide_index=None, column_order=None, column_config=column_config, disabled=['id','file'])
if f'select_paretos_{st.session_state.ed_key}' in st.session_state:
ed = st.session_state[f'select_paretos_{st.session_state.ed_key}']
for row in ed["edited_rows"]:
if "view" in ed["edited_rows"][row]:
if ed["edited_rows"][row]["view"]:
st.write(f"Pareto {d_paretos[row]['Name']}")
st.code(json.dumps(self.paretos[row], indent=4))
def cleanup_bt_session_state(self):
if "bt_v7_queue" in st.session_state:
del st.session_state.bt_v7_queue
if "bt_v7_results" in st.session_state:
del st.session_state.bt_v7_results
if "bt_v7_edit_symbol" in st.session_state:
del st.session_state.bt_v7_edit_symbol
if "config_v7_archives" in st.session_state:
del st.session_state.config_v7_archives
if "config_v7_config_archive" in st.session_state:
del st.session_state.config_v7_config_archive
def _build_backtest_queue_draft_items(self, backtest_paths: list[str]) -> list[dict]:
items = []
for backtest_path in self._dedupe_paths(backtest_paths):
bt_v7 = BacktestV7.BacktestV7Item(backtest_path)
base_name = bt_v7.name or "rebacktest"
suffix = replace_special_chars(Path(backtest_path).stem)
if suffix and suffix != base_name:
queue_name = f"{base_name}_{suffix}"
else:
queue_name = base_name
items.append({"name": queue_name, "config": bt_v7.config.config})
return items
def _get_selected_pareto_paths(self, d_paretos: list[dict], ed: dict) -> list[str]:
selected_paths = []
edited_rows = (ed or {}).get("edited_rows", {})
for row, changes in edited_rows.items():
if not isinstance(changes, dict) or not changes.get("Select"):
continue
try:
row_index = int(row)
except (TypeError, ValueError):
continue
if row_index < 0 or row_index >= len(d_paretos):
continue
path = d_paretos[row_index].get("file")
if path:
selected_paths.append(path)
return self._dedupe_paths(selected_paths)
def backtest_selected(self):
if "d_paretos" in st.session_state: