-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstrategy-generalization-analysis.py
More file actions
executable file
·3568 lines (3138 loc) · 168 KB
/
strategy-generalization-analysis.py
File metadata and controls
executable file
·3568 lines (3138 loc) · 168 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
"""
Strategy Generalization Analysis
=================================
Analyzes how well walk-forward-optimized strategies generalize from history
(in-sample + out-of-sample windows) into unseen "live proxy" windows.
IMPORTANT: Strategy files analyzed by this script must be produced by
`run_strategies.py` (or the same backtesting framework). Each strategy
subfolder under `root_dir` must contain a `.txt` results file with lines
in the format:
W01 IS PF: 1.23 ROI: $456 Trades: 80 Win: 52.3%
W01 OOS PF: 1.10 ROI: $210 Trades: 40 Win: 54.0%
W01 IS+ENT PF: 1.18 ... <- robustness variant (optional)
W01 OOS+ENT PF: 1.05 ...
...
These files are generated automatically when you run run_strategies.py with
the following robustness switches enabled in BACKTESTER_OVERRIDES:
ENTRY_DRIFT = True -> produces IS+ENT / OOS+ENT lines
INDICATOR_VARIANCE= True -> produces IS+IND / OOS+IND lines
FEE_SHOCK = True -> produces IS+FEE / OOS+FEE lines
SLIPPAGE_SHOCK = True -> produces IS+SLI / OOS+SLI lines
You must enable at least one robustness switch to use any test with
"Eligible for manual export selection (robustness-required): YES".
WORKFLOW OVERVIEW:
1. Run run_strategies.py to generate strategy result folders under your output directory.
2. Set `root_dir` below to that same output directory.
3. Run this script once to see the "TEST ID MAPPING" output.
4. Pick a test ID marked as "Eligible ... : YES" and set SELECT_TEST_NUMBER.
5. Re-run to export an Excel file with passing strategies and portfolio stats.
QUICK START:
# Step 1: Point to your strategies folder
root_dir = r"C:\path\to\your\strategy_output_folder"
# Step 2: Run and read the TEST ID MAPPING printed to console
# Step 3: Choose a test and set SELECT_TEST_NUMBER (e.g. 10)
# Step 4: Re-run -> Excel exported to root_dir
See the CONFIG section below for all tunable parameters.
"""
import os
import re
import math
import sys
import subprocess
import json
import tempfile
from collections import defaultdict
from statistics import median
from builtins import print as _builtin_print
import numpy as np
import matplotlib.pyplot as plt
# Excel export
import pandas as pd
# Beta-Binomial lower bound
try:
from scipy.stats import beta as beta_dist
except ImportError as e:
raise ImportError("scipy is required for beta.ppf (pip install scipy).") from e
# ---------------------------------------------------------------------------
# USER CONFIGURATION: Set this to the folder produced by run_strategies.py
# ---------------------------------------------------------------------------
# This should be the `base_output` folder you passed to run_strategies.py.
# Example (Windows): r"C:\Strategies\MyRun"
# Example (Linux/Mac): "/home/user/strategies/myrun"
root_dir = r"YOUR_STRATEGY_OUTPUT_FOLDER_HERE"
RE_WINDOW_LINE_DETECT = re.compile(r"^\s*W(\d{2,3})\s+(IS|OOS)\b", re.IGNORECASE)
def log_line(*args, **kwargs):
"""Single output wrapper used across the script for consistent messaging."""
_builtin_print(*args, **kwargs)
def detect_windows_in_file(root_dir_path: str, preferred_windows: int = None):
"""
Detect total window count from strategy .txt files under root_dir.
If preferred_windows is provided, prefer the first file that matches it.
Returns (windows_in_file, file_used).
"""
first_txt = None
first_txt_windows = None
for subdir, _, files in os.walk(root_dir_path):
for fn in files:
if fn.lower().endswith(".txt"):
candidate = os.path.join(subdir, fn)
max_w = 0
with open(candidate, "r", encoding="utf-8") as f:
for line in f:
m = RE_WINDOW_LINE_DETECT.match(line)
if not m:
continue
w = int(m.group(1))
if w > max_w:
max_w = w
if max_w <= 0:
continue
if first_txt is None:
first_txt = candidate
first_txt_windows = max_w
if preferred_windows is not None and max_w == preferred_windows:
return max_w, candidate
if not first_txt:
raise FileNotFoundError(f"No .txt strategy files found under root_dir: {root_dir_path}")
return first_txt_windows, first_txt
# ---------------------------------------------------------------------------
# CONFIG - Tune these settings before running
# ---------------------------------------------------------------------------
# Core window geometry for each run:
# - EXPECTED_WINDOWS defines how many windows are analyzed in one active run.
# - WINDOWS_IN_FILE is either auto-detected or manually set and is the total windows in source files.
# How many WFO windows exist in each run_strategies.py output file.
# Must match the number of windows your backtester produced.
# Typical values: 4, 6, 7. Must be >= 2.
EXPECTED_WINDOWS = 6
AUTO_DETECT_WINDOWS_IN_FILE = True
WINDOWS_IN_FILE = None # set manual value only when AUTO_DETECT_WINDOWS_IN_FILE=False
PF_OK = 1.0
ENABLE_PLOTS = True # disable for faster/headless runs
# Execution modes:
# - LIVE_MODE: shifts the active window block forward by 2 windows and treats
# the most recent windows as current (not as held-out live proxies).
# Use this when deploying live and you want to re-apply the filter without
# a held-out test period.
# - META_MODE: re-runs the script across every possible sliding window block
# and prints a summary table, showing temporal stability across all offsets.
# Set to False for a single-run analysis.
LIVE_MODE = False
META_MODE = False
# Portfolio generation controls:
# - PORTFOLIO_SIZE: number of strategies per sampled portfolio (e.g. 5 or 20).
# - MAX_PORTFOLIO_COMBOS: maximum number of portfolios to sample. Increase for
# more statistical precision, decrease for faster runs.
# - TOP_STRATEGIES_POOL: portfolios are sampled from the top-N strategies
# ranked by TOP_STRATEGY_RANK_METRIC ("sharpe", "pf", or "maxdd").
PORTFOLIO_SIZE = 20
MAX_PORTFOLIO_COMBOS = 10000
BUILD_PAIR_PORTFOLIOS = False # compatibility flag; pair generation is not used
TOP_STRATEGIES_POOL = 24 # random portfolios are sampled from top-N history performers
TOP_STRATEGY_RANK_METRIC = "pf" # accepted values: "sharpe", "pf", "maxdd"
# ---------------------------------------------------------------------------
# RISK & MILESTONE THRESHOLDS (used by portfolio challenge-style tests)
# ---------------------------------------------------------------------------
# These simulate prop-firm-style challenges on the live proxy windows:
# - TARGET_R / DRAWDOWN_LIMIT_R / DAY_LOSS_LIMIT_R: R-unit based thresholds.
# - USE_PCT_MODE: if True, converts everything to % of ACCOUNT_BALANCE.
# - RISK_PCT_PER_R: % of equity risked per 1R trade (compounded).
TARGET_R = 10 # e.g., reach 5R profit
DRAWDOWN_LIMIT_R = -10 # e.g., avoid losing 3R before target
DAY_LOSS_LIMIT_R = -5 # e.g., avoid losing 4R in a single day before target
USE_PCT_MODE = True # if True, use percentage-based equity milestones instead of R
ACCOUNT_BALANCE = 1000.0 # starting balance for percentage mode
RISK_PCT_PER_R = 0.1 # e.g., 0.01 = 1% of equity per 1R; compounded per trade
R_UNIT_SCALE = 10 # fixed-risk mode: scale Live_R by this factor (e.g., 0.2 means 1R=0.2 units)
# Backtest-only mode:
# - When Backtest_only=True, the script skips the full pipeline and only runs
# diagnostic plots/statistics for a specific window block, then exits.
# - Useful for inspecting distribution curves and equity curves without
# running a full analysis.
# - The window selector below defines the split between history and live windows.
Backtest_only = False
Backtest_only_plot_selected_portfolio = False
Backtest_all_strategies_distribution_curve = True
Backtest_all_portfolios_distribution_curve = True
# Backtest-only window block selector:
# start=1 -> history W01..W04, live W05..W06
# start=3 -> history W03..W06, live W07..W08
Backtest_only_window_start = 1
Backtest_only_history_windows = 4
Backtest_only_live_windows = 2
backtest_list = {
"ATR_x_EMA100_normalized_price_src_skew_SL3": 1.0,
"SMA_x_SMA100_roc_BW_filter_SL2": 1.0,
"SMA_x_SMA50_fold_dev_InsideBar_SL2": 1.0,
"RSI_x_EMA50_bias_calc_skew_SL3": 1.0,
"ATR_x_EMA100_normalized_price_src_SL3": 1.0,
"RSI_x_EMA20_skew_SL3": 1.0,
"EMA_x_EMA50_roc_atr_pct0.8_SL3": 1.0,
"RSI_x_EMA50_atr_pct_SL3": 1.0,
"ATR_x_EMA100_normalized_price_src_RSIge40_SL3": 1.0,
"RSI_x_EMA100_accel_src_BW_filter_SL3": 1.0,
"RSI_x_EMA100_normalized_price_src_atr_pct_SL3": 1.0,
"ATR_x_EMA200_accel_src_Pge0.7_SL3": 1.0,
"MACD(42,110)_roc_InsideBar_SL3": 1.0,
"STOCHK_SMA_55_normalized_price_src_Pge0.7_SL2": 1.0,
"STOCHK_EMA_89_fold_dev_calc_Pge0.7_SL3": 1.0,
"ATR_x_EMA200_slope_src_SL3": 1.0,
"ATR_x_EMA100_rank_resid_src_skew_SL3": 1.0,
"RSI_x_SMA50_slope_calc_Pge0.8_SL2": 1.0,
"PPO_x_EMA50_volZ_calc_Pge0.7_SL2": 1.0,
"ATR_x_EMA100_volZ_src_Pge0.8_SL3": 1.0,
}
# ---------------------------------------------------------------------------
# TEST SELECTION
# ---------------------------------------------------------------------------
# STEP 1: Run the script once with any SELECT_TEST_NUMBER.
# Read the "TEST ID MAPPING" block printed to the console.
# STEP 2: Choose a test ID where:
# "Eligible for manual export selection (robustness-required): YES"
# These tests require that your strategy files contain robustness
# lines (IS+ENT, OOS+ENT, etc.) produced by run_strategies.py when
# ENTRY_DRIFT / INDICATOR_VARIANCE / FEE_SHOCK etc. are enabled.
# STEP 3: Set SELECT_TEST_NUMBER to that number and re-run to export.
#
# DO NOT pick base-only quality-gate tests (e.g. ">100 trades + dedup")
# for the main export — those have no robustness requirement.
SELECT_TEST_NUMBER = 10
TEST_ID_MAP_TAGS = ["ENT", "IND", "FEE", "SLI"]
def _startup_build_pipeline_names(tags: list = None) -> list:
tags = TEST_ID_MAP_TAGS if tags is None else tags
names = ["Strategies with >100 trades total (base IS+OOS across all windows) + deduped"]
for tag in tags:
names.append(f"Strategies with 2 or more profitable windows (base) + IS+{tag} + OOS")
names.append(f"Strategies with 2 or more profitable windows (base) + IS+{tag} + OOS + OOS+{tag}")
names.append(f"Strategies with 3 or more profitable windows (base) + IS+{tag} + OOS")
names.append(f"Strategies with 3 or more profitable windows (base) + IS+{tag} + OOS + OOS+{tag}")
if EXPECTED_WINDOWS >= 4:
names.append(f"Strategies with 4 profitable windows (base) + IS+{tag} + OOS")
names.append(f"Strategies with 4 profitable windows (base) + IS+{tag} + OOS + OOS+{tag}")
return names
def _print_startup_test_id_mapping_first():
"""
Prints test ID mapping immediately on startup, before any other runtime work.
"""
pipeline_names = _startup_build_pipeline_names()
log_line("\n==================== TEST ID MAPPING (startup-first) ====================\n")
for idx, pname in enumerate(pipeline_names, start=1):
log_line(f"test {idx}: {pname}")
log_line("")
_print_startup_test_id_mapping_first()
if AUTO_DETECT_WINDOWS_IN_FILE:
WINDOWS_IN_FILE, WINDOWS_DETECTED_FROM = detect_windows_in_file(root_dir, preferred_windows=EXPECTED_WINDOWS)
else:
if WINDOWS_IN_FILE is None:
WINDOWS_IN_FILE = EXPECTED_WINDOWS
WINDOWS_DETECTED_FROM = "manual"
if WINDOWS_IN_FILE < EXPECTED_WINDOWS:
raise ValueError("WINDOWS_IN_FILE must be >= EXPECTED_WINDOWS.")
ENV_WINDOW_OFFSET_OVERRIDE = "WFO_WINDOW_OFFSET_OVERRIDE"
ENV_META_CHILD = "WFO_META_CHILD"
ENV_META_PLOT_DIR = "WFO_META_PLOT_DIR"
ENV_META_PLOT_PREFIX = "WFO_META_PLOT_PREFIX"
ENV_META_DEFER_PLOTS = "WFO_META_DEFER_PLOTS"
ENV_FORCE_FULL_PIPELINE = "WFO_FORCE_FULL_PIPELINE"
ENV_BACKTEST_PORT_ROI_OUT = "WFO_BACKTEST_PORTFOLIO_ROI_OUT"
ENV_BACKTEST_SKIP_XLSX = "WFO_BACKTEST_SKIP_XLSX"
if os.environ.get(ENV_FORCE_FULL_PIPELINE) == "1":
Backtest_only = False
_window_offset_override_raw = os.environ.get(ENV_WINDOW_OFFSET_OVERRIDE, "").strip()
if _window_offset_override_raw:
try:
WINDOW_OFFSET = int(_window_offset_override_raw)
except ValueError as e:
raise ValueError(
f"{ENV_WINDOW_OFFSET_OVERRIDE} must be an integer, got: {_window_offset_override_raw!r}"
) from e
else:
WINDOW_OFFSET = max(0, WINDOWS_IN_FILE - EXPECTED_WINDOWS)
_max_window_offset = WINDOWS_IN_FILE - EXPECTED_WINDOWS
if WINDOW_OFFSET < 0 or WINDOW_OFFSET > _max_window_offset:
raise ValueError(
f"WINDOW_OFFSET={WINDOW_OFFSET} is invalid for WINDOWS_IN_FILE={WINDOWS_IN_FILE} "
f"and EXPECTED_WINDOWS={EXPECTED_WINDOWS}. Allowed range: 0..{_max_window_offset}."
)
WINDOW_FILE_START = 1 + WINDOW_OFFSET
WINDOW_FILE_END = WINDOW_FILE_START + EXPECTED_WINDOWS - 1
# Live proxy windows:
# - If 7 windows: W06 & W07
# - If 4 windows: W03 & W04
# - Otherwise: last two windows
if EXPECTED_WINDOWS == 7:
LIVE_WA = 6
LIVE_WB = 7
elif EXPECTED_WINDOWS == 4:
LIVE_WA = 3
LIVE_WB = 4
else:
LIVE_WA = EXPECTED_WINDOWS - 1
LIVE_WB = EXPECTED_WINDOWS
# Indices in Python lists
LIVE_IA = LIVE_WA - 1
LIVE_IB = LIVE_WB - 1
# Windows used for "history" (W1..W5 in 7-window case; W1..W2 in 4-window case)
HIST_WINDOWS = max(1, EXPECTED_WINDOWS - 2) # always excludes the last 2 proxy windows
HIST_IDXS = list(range(HIST_WINDOWS)) # 0..HIST_WINDOWS-1
HIST_W_NUMS = list(range(1, HIST_WINDOWS + 1))
# Live-mode re-application skips the earliest windows and reuses the most recent ones
LIVE_MODE_SKIP = 2
LIVE_MODE_START = min(EXPECTED_WINDOWS, 1 + LIVE_MODE_SKIP)
LIVE_MODE_WINDOWS = list(range(LIVE_MODE_START, EXPECTED_WINDOWS + 1)) if LIVE_MODE_START <= EXPECTED_WINDOWS else []
# Base tiers (keep your original tier names / concept, but "RB" is now per TAG)
TIERS_BASE = ["IS"]
TIERS_RB = ["IS_ISRB", "IS_ISRB_OOS", "IS_ISRB_OOS_OOSRB"]
def log_runtime_configuration():
"""Emit a readable summary of runtime controls and derived window roles."""
log_line("\n==================== RUNTIME CONFIGURATION ====================\n")
log_line(f"Root directory: {root_dir}")
log_line(
"Window policy: "
f"EXPECTED_WINDOWS={EXPECTED_WINDOWS}, WINDOWS_IN_FILE={WINDOWS_IN_FILE}, "
f"active file windows=W{WINDOW_FILE_START:02d}..W{WINDOW_FILE_END:02d}, offset={WINDOW_OFFSET}"
)
log_line(
"Role mapping: "
f"history windows=W01..W{HIST_WINDOWS:02d}, live proxies=W{LIVE_WA:02d}&W{LIVE_WB:02d}"
)
log_line(
"Mode flags: "
f"LIVE_MODE={LIVE_MODE}, META_MODE={META_MODE}, Backtest_only={Backtest_only}, ENABLE_PLOTS={ENABLE_PLOTS}"
)
log_line(
"Portfolio config: "
f"size={PORTFOLIO_SIZE}, max_combos={MAX_PORTFOLIO_COMBOS}, top_rank_metric={TOP_STRATEGY_RANK_METRIC}, "
f"top_pool={TOP_STRATEGIES_POOL}"
)
if USE_PCT_MODE:
log_line(
"Risk model: percentage-compounding "
f"(ACCOUNT_BALANCE={ACCOUNT_BALANCE}, RISK_PCT_PER_R={RISK_PCT_PER_R})"
)
else:
log_line(f"Risk model: fixed-risk R units (R_UNIT_SCALE={R_UNIT_SCALE})")
if Backtest_only:
log_line(
"Backtest-only windows: "
f"start=W{Backtest_only_window_start:02d}, history_count={Backtest_only_history_windows}, "
f"live_count={Backtest_only_live_windows}"
)
def _extract_meta_run_summary(stdout_text: str) -> dict:
def _find_int(pattern: str):
m = re.search(pattern, stdout_text, flags=re.MULTILINE)
return int(m.group(1)) if m else None
def _find_float(pattern: str):
m = re.search(pattern, stdout_text, flags=re.MULTILINE)
return float(m.group(1)) if m else None
return {
"exported_portfolios": _find_int(r"^Portfolios \(\d+-strategy equal-weight\):\s*(\d+)\s*$"),
"total_portfolios": _find_int(r"^Total portfolios:\s*(\d+)\s*$"),
"profitable": _find_int(r"^Profitable .*?:\s*(\d+)\s*$"),
"unprofitable": _find_int(r"^Unprofitable .*?:\s*(\d+)\s*$"),
"avg_live_pct": _find_float(r"^Average W\d+&W\d+ result \(%\):\s*([+-]?\d+(?:\.\d+)?)%\s*$"),
"avg_maxdd_pct": _find_float(r"^Average max drawdown \(%\):\s*([+-]?\d+(?:\.\d+)?)%\s*$"),
"avg_prof_dd_r": _find_float(r"^Avg max DD \(profitable, R\):\s*([+-]?\d+(?:\.\d+)?)\s*$"),
"avg_unprof_dd_r": _find_float(r"^Avg max DD \(unprofitable, R\):\s*([+-]?\d+(?:\.\d+)?)\s*$"),
}
def _maybe_run_meta_mode():
if not META_MODE:
return
if os.environ.get(ENV_META_CHILD) == "1":
return
max_offset = WINDOWS_IN_FILE - EXPECTED_WINDOWS
if max_offset < 2:
log_line(
f"[META MODE] Disabled for this run: requires at least EXPECTED_WINDOWS + 2 windows "
f"(>= {EXPECTED_WINDOWS + 2}), but detected {WINDOWS_IN_FILE}."
)
return
script_path = os.path.abspath(__file__) if "__file__" in globals() else None
if not script_path or not os.path.isfile(script_path):
log_line("[META MODE] Could not resolve script path; running normal mode instead.")
return
run_offsets = list(range(0, max_offset + 1))
total_runs = len(run_offsets)
meta_results = []
meta_plot_dir = tempfile.mkdtemp(prefix="wfo_meta_plots_") if ENABLE_PLOTS else None
log_line("\n==================== META MODE ====================\n")
log_line(f"Expected windows per run: {EXPECTED_WINDOWS}")
log_line(f"Detected windows in file: {WINDOWS_IN_FILE}")
log_line(f"Sliding runs to execute: {total_runs} (offsets 0..{max_offset})")
log_line(f"Selected test number (reused each run): {SELECT_TEST_NUMBER}")
for run_idx, offset in enumerate(run_offsets, start=1):
file_start = 1 + offset
file_end = file_start + EXPECTED_WINDOWS - 1
live_a_file = file_start + (LIVE_WA - 1)
live_b_file = file_start + (LIVE_WB - 1)
log_line("\n" + "=" * 60)
log_line(
f"[META RUN {run_idx}/{total_runs}] File windows W{file_start:02d}-W{file_end:02d} | "
f"Live proxies W{live_a_file:02d}-W{live_b_file:02d} | offset={offset}"
)
log_line("=" * 60)
env = os.environ.copy()
env[ENV_WINDOW_OFFSET_OVERRIDE] = str(offset)
env[ENV_META_CHILD] = "1"
if ENABLE_PLOTS and meta_plot_dir:
env[ENV_META_DEFER_PLOTS] = "1"
env[ENV_META_PLOT_DIR] = meta_plot_dir
env[ENV_META_PLOT_PREFIX] = f"run{run_idx:02d}_W{file_start:02d}_W{file_end:02d}"
env.setdefault("PYTHONIOENCODING", "utf-8")
proc = subprocess.run(
[sys.executable, script_path],
cwd=os.path.dirname(script_path) or None,
capture_output=True,
text=True,
errors="replace",
env=env,
)
stdout_text = proc.stdout or ""
stderr_text = proc.stderr or ""
if stdout_text:
log_line(stdout_text, end="" if stdout_text.endswith("\n") else "\n")
if stderr_text.strip():
log_line("\n[META RUN STDERR]")
log_line(stderr_text, end="" if stderr_text.endswith("\n") else "\n")
run_summary = _extract_meta_run_summary(stdout_text)
run_summary.update({
"run_idx": run_idx,
"offset": offset,
"file_start": file_start,
"file_end": file_end,
"live_a_file": live_a_file,
"live_b_file": live_b_file,
"returncode": proc.returncode,
})
meta_results.append(run_summary)
if proc.returncode != 0:
log_line(f"\n[META MODE] Stopping because run {run_idx}/{total_runs} failed with exit code {proc.returncode}.")
raise SystemExit(proc.returncode)
log_line("\n==================== META SUMMARY ====================\n")
for r in meta_results:
total_pf = r.get("total_portfolios")
exported_pf = r.get("exported_portfolios")
profitable = r.get("profitable")
unprofitable = r.get("unprofitable")
avg_live_pct = r.get("avg_live_pct")
avg_maxdd_pct = r.get("avg_maxdd_pct")
avg_prof_dd_r = r.get("avg_prof_dd_r")
avg_unprof_dd_r = r.get("avg_unprof_dd_r")
log_line(
f"Run {r['run_idx']}/{total_runs} | W{r['file_start']:02d}-W{r['file_end']:02d} "
f"(live W{r['live_a_file']:02d}-W{r['live_b_file']:02d})"
)
log_line(
f" Total portfolios: {total_pf if total_pf is not None else 'n/a'} | "
f"Exported portfolios: {exported_pf if exported_pf is not None else 'n/a'} | "
f"Profitable: {profitable if profitable is not None else 'n/a'} | "
f"Unprofitable: {unprofitable if unprofitable is not None else 'n/a'}"
)
if avg_live_pct is not None or avg_maxdd_pct is not None:
log_line(f" Avg live result (%): {avg_live_pct:.2f}" if avg_live_pct is not None else " Avg live result (%): n/a")
log_line(f" Avg max drawdown (%): {avg_maxdd_pct:.2f}" if avg_maxdd_pct is not None else " Avg max drawdown (%): n/a")
if avg_prof_dd_r is not None or avg_unprof_dd_r is not None:
log_line(f" Avg max DD (profitable, R): {avg_prof_dd_r:.2f}" if avg_prof_dd_r is not None else " Avg max DD (profitable, R): n/a")
log_line(f" Avg max DD (unprofitable, R): {avg_unprof_dd_r:.2f}" if avg_unprof_dd_r is not None else " Avg max DD (unprofitable, R): n/a")
if ENABLE_PLOTS and meta_plot_dir and os.path.isdir(meta_plot_dir):
saved_plot_files = sorted(
[os.path.join(meta_plot_dir, fn) for fn in os.listdir(meta_plot_dir) if fn.lower().endswith(".png")]
)
if saved_plot_files:
log_line("\n==================== META PLOTS (DEFERRED) ====================\n")
log_line(f"Opening {len(saved_plot_files)} matplotlib figure(s) after all meta runs...")
for img_path in saved_plot_files:
try:
img = plt.imread(img_path)
fig = plt.figure()
ax = fig.add_subplot(111)
ax.imshow(img)
ax.set_title(os.path.basename(img_path))
ax.axis("off")
except Exception as e:
log_line(f"[META MODE] Failed to open deferred plot {img_path}: {e}")
plt.show()
else:
log_line("\n[META MODE] No deferred plots were captured.\n")
raise SystemExit(0)
if os.environ.get(ENV_META_CHILD) != "1":
log_runtime_configuration()
_maybe_run_meta_mode()
# ---------------------------------------------------------------------------
# TEST ID INFRASTRUCTURE + EARLY MAPPING PRINT
# ---------------------------------------------------------------------------
# Moved before the file walk so the mapping is printed on startup,
# even if root_dir doesn't exist or contains no files yet.
# --- compact pipeline IDs ("test 1", "test 2", ...)
pipeline_rows = [] # every row = (test_id, metric, lower_bound, point_est, n)
test_id_map = {} # full_pipeline_name -> "test N"
test_id_reverse = {} # "test N" -> full_pipeline_name
_next_test_id = 1
def get_test_id(full_name: str) -> str:
global _next_test_id
full_name = full_name.strip()
if full_name in test_id_map:
return test_id_map[full_name]
tid = f"test {_next_test_id}"
_next_test_id += 1
test_id_map[full_name] = tid
test_id_reverse[tid] = full_name
return tid
def _add_pipeline_row(pipeline_name: str, metric: str, n: int, point_est_pct: float):
lb = beta_lower_bound_95(point_est_pct, n)
tid = get_test_id(pipeline_name)
pipeline_rows.append({
"pipeline": tid,
"metric": metric,
"lower_bound": lb,
"point_est": point_est_pct,
"n": n
})
def _print_block_and_collect(pipeline_name: str, bucket: dict):
n = int(bucket["count"])
wa_pct = _pct(bucket["wa"], n)
wb_pct = _pct(bucket["wb"], n)
wab_pct = _pct(bucket["wab"], n)
log_line(f"\n{pipeline_name}")
log_line(f" - Matched strategies: {n}")
log_line(f" - Live proxy W{LIVE_WA} profitable rate: {wa_pct:.2f}%")
log_line(f" - Live proxy W{LIVE_WB} profitable rate: {wb_pct:.2f}%")
log_line(f" - Both live proxies profitable rate: {wab_pct:.2f}%")
_add_pipeline_row(pipeline_name, f"W{LIVE_WA}", n, wa_pct)
_add_pipeline_row(pipeline_name, f"W{LIVE_WB}", n, wb_pct)
_add_pipeline_row(pipeline_name, f"W{LIVE_WA}&W{LIVE_WB}", n, wab_pct)
def _agg_rb_bucket(tag, tier, k_min=None, k_exact=None):
out = {"count": 0, "wa": 0, "wb": 0, "wab": 0}
if tag not in stats_by_rb:
return out
if k_exact is not None:
ks = [k_exact]
else:
k_min = 1 if k_min is None else k_min
ks = list(range(k_min, EXPECTED_WINDOWS + 1))
for k in ks:
s = stats_by_rb[tag][k][tier]
out["count"] += s["count"]
out["wa"] += s["wa"]
out["wb"] += s["wb"]
out["wab"] += s["wab"]
return out
# -------------------------------
# TEST ID MAPPING (kept so you can choose SELECT_TEST_NUMBER)
# -------------------------------
# HOW TO READ THIS BLOCK:
# - Every "test N" is one pipeline/filter definition.
# - "Requirements" tells which robustness runs must exist and pass for a strategy.
# - If you require robustness-tested strategies, only choose tests marked:
# "Eligible for manual export selection (robustness-required): YES"
def _describe_pipeline_human_readable(pipeline_name: str) -> str:
"""
Convert internal pipeline labels into a short explanation of what the test filters for.
This helps when selecting SELECT_TEST_NUMBER.
"""
s = pipeline_name.strip()
if s.startswith("Strategies with >100 trades total"):
return "Base quality gate: at least 100 total trades across windows + deduplicated signatures."
m = re.match(
r"^Strategies with (\d+) or more profitable windows \(base\) \+ IS\+([A-Z+]+) \+ OOS( \+ OOS\+\2)?$",
s
)
if m:
kmin = int(m.group(1))
tag = m.group(2).upper()
with_oos_rb = (m.group(3) is not None)
if with_oos_rb:
return (
f"Robustness funnel: base has >= {kmin} profitable IS windows, "
f"IS+{tag} must pass, OOS must pass, and OOS+{tag} must also pass."
)
return (
f"Robustness funnel: base has >= {kmin} profitable IS windows, "
f"then IS+{tag} and OOS must pass."
)
m = re.match(
r"^Strategies with (\d+) profitable windows \(base\) \+ IS\+([A-Z+]+) \+ OOS( \+ OOS\+\2)?$",
s
)
if m:
kexact = int(m.group(1))
tag = m.group(2).upper()
with_oos_rb = (m.group(3) is not None)
if with_oos_rb:
return (
f"Robustness funnel (exact-k): base has exactly {kexact} profitable IS windows, "
f"then IS+{tag}, OOS, and OOS+{tag} must pass."
)
return (
f"Robustness funnel (exact-k): base has exactly {kexact} profitable IS windows, "
f"then IS+{tag} and OOS must pass."
)
return "Pipeline meaning could not be auto-parsed from its label."
def parse_pipeline_descriptor(name: str) -> dict:
"""Parse pipeline text into a structured descriptor for selection and requirement checks."""
s = name.strip()
if s.startswith("Strategies with >100 trades total"):
return {"type": "GT100_DEDUP"}
m = re.match(
r"^Strategies with (\d+) or more profitable windows \(base\) \+ IS\+([A-Z+]+) \+ OOS( \+ OOS\+\2)?$",
s
)
if m:
kmin = int(m.group(1))
tag = m.group(2).upper()
with_oos_rb = (m.group(3) is not None)
return {"type": "RB_FUNNEL", "k_mode": "MIN", "k": kmin, "tag": tag, "with_oos_rb": with_oos_rb}
m = re.match(
r"^Strategies with (\d+) profitable windows \(base\) \+ IS\+([A-Z+]+) \+ OOS( \+ OOS\+\2)?$",
s
)
if m:
kexact = int(m.group(1))
tag = m.group(2).upper()
with_oos_rb = (m.group(3) is not None)
return {"type": "RB_FUNNEL", "k_mode": "EXACT", "k": kexact, "tag": tag, "with_oos_rb": with_oos_rb}
return {"type": "UNKNOWN", "raw": s}
def _pipeline_requirements_human_readable(pipeline_name: str) -> str:
"""
Describe required line availability in each strategy file for this test.
This is the key section for test selection.
"""
desc = parse_pipeline_descriptor(pipeline_name)
if desc["type"] == "RB_FUNNEL":
k_part = f">= {desc['k']}" if desc["k_mode"] == "MIN" else f"exactly {desc['k']}"
req = (
f"Requires robustness runs: base IS has {k_part} profitable windows, "
f"plus IS+{desc['tag']} and base OOS lines must exist and pass."
)
if desc.get("with_oos_rb"):
req += f" Also requires OOS+{desc['tag']} lines to exist and pass."
return req
if desc["type"] == "GT100_DEDUP":
return "No robustness-tag requirement (base-only quality gate)."
return "Requirements could not be parsed from pipeline label."
def _pre_print_test_id_map():
"""
Pre-populate test_id_map / test_id_reverse and print the TEST ID MAPPING
before any file walking begins. Uses the same pipeline registration order
as the main analysis so SELECT_TEST_NUMBER values remain consistent.
"""
# Register pipelines in same order the main analysis would
get_test_id("Strategies with >100 trades total (base IS+OOS across all windows) + deduped")
for tag in TEST_ID_MAP_TAGS:
get_test_id(f"\nStrategies with 2 or more profitable windows (base) + IS+{tag} + OOS")
get_test_id(f"Strategies with 2 or more profitable windows (base) + IS+{tag} + OOS + OOS+{tag}")
get_test_id(f"\nStrategies with 3 or more profitable windows (base) + IS+{tag} + OOS")
get_test_id(f"Strategies with 3 or more profitable windows (base) + IS+{tag} + OOS + OOS+{tag}")
if EXPECTED_WINDOWS >= 4:
get_test_id(f"\nStrategies with 4 profitable windows (base) + IS+{tag} + OOS")
get_test_id(f"Strategies with 4 profitable windows (base) + IS+{tag} + OOS + OOS+{tag}")
log_line("\n==================== TEST ID MAPPING (preliminary) ====================\n")
log_line("Static requirements-only mapping (independent of current files). A complete version is printed after the full file walk.")
log_line("Test selection rule: only robustness-funnel tests (IS+TAG / OOS+TAG pipelines) are eligible for export.\n")
for tid in sorted(test_id_reverse.keys(), key=lambda x: int(x.split()[1])):
pname = test_id_reverse[tid]
pdesc = parse_pipeline_descriptor(pname)
eligible = "YES" if pdesc["type"] == "RB_FUNNEL" else "NO"
log_line(f"{tid}: {pname.strip()}")
log_line(f" Meaning: {_describe_pipeline_human_readable(pname)}")
log_line(f" Requirements: {_pipeline_requirements_human_readable(pname)}")
log_line(f" Eligible for manual export selection (robustness-required): {eligible}")
if os.environ.get(ENV_META_CHILD) != "1":
_pre_print_test_id_map()
_ORIG_PLT_SHOW = plt.show
_meta_show_batch_counter = 0
def _wfo_show_wrapper(*args, **kwargs):
global _meta_show_batch_counter
if os.environ.get(ENV_META_DEFER_PLOTS) != "1":
return _ORIG_PLT_SHOW(*args, **kwargs)
plot_dir = os.environ.get(ENV_META_PLOT_DIR, "").strip()
prefix = os.environ.get(ENV_META_PLOT_PREFIX, "meta")
if not plot_dir:
return None
os.makedirs(plot_dir, exist_ok=True)
fig_nums = list(plt.get_fignums())
if not fig_nums:
return None
_meta_show_batch_counter += 1
batch_id = _meta_show_batch_counter
for seq, fig_num in enumerate(fig_nums, start=1):
fig = plt.figure(fig_num)
out_name = f"{prefix}_show{batch_id:02d}_fig{seq:02d}.png"
out_path = os.path.join(plot_dir, out_name)
try:
fig.savefig(out_path, dpi=120, bbox_inches="tight")
except Exception:
# Fallback without bbox if a backend/artist complains
fig.savefig(out_path, dpi=120)
plt.close(fig)
return None
plt.show = _wfo_show_wrapper
# -------------------------------
# STATS STRUCTURES
# -------------------------------
# Baseline stats: group by k=number of profitable IS windows, evaluate LIVE using base OOS
stats_base = {
k: {
tier: {"count": 0, "wa": 0, "wb": 0, "wab": 0}
for tier in TIERS_BASE
}
for k in range(1, EXPECTED_WINDOWS + 1)
}
# Per-robustness stats: tag -> k -> tier -> counts
stats_by_rb = {} # filled dynamically: stats_by_rb[tag][k][tier] = {...}
# NEW FILTER 1: At least 4/5 profitable IS in W1..W5 (generalized to HIST_WINDOWS)
need_hist_prof = int(np.ceil(0.8 * HIST_WINDOWS))
flt_is_hist_80 = {"count": 0, "wa": 0, "wb": 0}
# NEW FILTER 2: per robustness tag, at least 80% history windows profitable in BOTH IS and IS+TAG
flt_is_rb_hist_80 = {} # tag -> bucket dict
# NEW FILTER 3: OOS winrate bins over history window set (generalized)
winrate_bins = {
"OOS_WR_<50": {"count": 0, "wa": 0, "wb": 0},
"OOS_WR_50_70": {"count": 0, "wa": 0, "wb": 0},
"OOS_WR_>70": {"count": 0, "wa": 0, "wb": 0},
}
# -------------------------------
# Regex
# -------------------------------
# Capture any robustness suffix, e.g. +ENT, +FEE, +SLI, +ENT+IND, +RB (old)
RE_LINE = re.compile(r"^\s*W(\d{2})\s+(IS|OOS)(?:\+([A-Za-z+]+))?", re.IGNORECASE)
RE_PF = re.compile(r"PF:\s*([+-]?\d+(?:\.\d+)?)", re.IGNORECASE)
RE_WIN = re.compile(r"\bWin:\s*([+-]?\d+(?:\.\d+)?)\s*%", re.IGNORECASE)
RE_ROI = re.compile(r"ROI:\s*\$([+-]?\d[\d,]*(?:\.\d+)?)", re.IGNORECASE)
RE_TRADES = re.compile(r"Trades:\s*([0-9]+)", re.IGNORECASE)
# Generic key:value parser (to export "everything available" from each line)
RE_KV = re.compile(r"(\b[A-Za-z][A-Za-z0-9_]*\b):\s*(\$)?([+-]?\d[\d,]*(?:\.\d+)?)(%)?", re.IGNORECASE)
# Stop loss parsing from filename: "..._SLX..." where X can be int or float
RE_SL = re.compile(r"_SL(\d+(?:\.\d+)?)", re.IGNORECASE)
total_strategies = 0
parsed_strategies = 0
robust_tags_seen = set()
# -------------------------------
# EXTRA: >100 trades (TOTAL across all samples) + dedupe bucket
# -------------------------------
dedupe_signatures_seen = set()
dup_removed_count = 0
lt100_skipped_count = 0
flt_gt100_dedup = {"count": 0, "wa": 0, "wb": 0, "wab": 0}
# -------------------------------
# Helpers
# -------------------------------
def map_file_window_to_active(file_window: int):
"""Map file window numbers to active 1..EXPECTED_WINDOWS space; return None if outside active range."""
if file_window < WINDOW_FILE_START or file_window > WINDOW_FILE_END:
return None
return file_window - WINDOW_OFFSET
def normalize_window_label_to_active(label: str):
"""
Convert file labels like W03..W08 into active labels W01..W06 when offset is used.
Labels outside the active range are returned unchanged.
"""
s = str(label).strip().upper()
m = re.match(r"^W(\d{1,3})$", s)
if not m:
return s
file_w = int(m.group(1))
active_w = map_file_window_to_active(file_w)
if active_w is None:
return s
return f"W{active_w:02d}"
def ensure_rb_tag(tag: str):
"""Initialize per-tag stats/buckets the first time we see a robustness tag."""
if tag not in stats_by_rb:
stats_by_rb[tag] = {
k: {
tier: {"count": 0, "wa": 0, "wb": 0, "wab": 0}
for tier in TIERS_RB
}
for k in range(1, EXPECTED_WINDOWS + 1)
}
if tag not in flt_is_rb_hist_80:
flt_is_rb_hist_80[tag] = {"count": 0, "wa": 0, "wb": 0}
def expand_robustness_tags(tag_raw: str):
"""
Expand robustness suffixes into component tags.
Example: "ENT+IND" -> ["ENT", "IND"].
"""
if not tag_raw:
return []
out = []
seen = set()
for part in str(tag_raw).upper().split("+"):
p = part.strip()
if not p or p in seen:
continue
seen.add(p)
out.append(p)
return out
def bump_bucket(bucket, oos_list):
bucket["count"] += 1
wa = (oos_list[LIVE_IA] >= PF_OK)
wb = (oos_list[LIVE_IB] >= PF_OK)
if wa:
bucket["wa"] += 1
if wb:
bucket["wb"] += 1
def bump_base_k(k, oos_list):
s = stats_base[k]["IS"]
s["count"] += 1
wa = (oos_list[LIVE_IA] >= PF_OK)
wb = (oos_list[LIVE_IB] >= PF_OK)
if wa:
s["wa"] += 1
if wb:
s["wb"] += 1
if wa and wb:
s["wab"] += 1
def bump_rb_k_tier(tag, k, tier, oos_list):
s = stats_by_rb[tag][k][tier]
s["count"] += 1
wa = (oos_list[LIVE_IA] >= PF_OK)
wb = (oos_list[LIVE_IB] >= PF_OK)
if wa:
s["wa"] += 1
if wb:
s["wb"] += 1
if wa and wb:
s["wab"] += 1
def parse_money_to_float(s: str) -> float:
return float(s.replace(",", ""))
def compute_hist_trades(base_is_trades: dict, base_oos_trades: dict, start_w: int = 1, hist_windows: int = HIST_WINDOWS):
"""
History trade count uses IS at start_w plus OOS for start_w..end_w.
Returns (has_all, total_trades).
"""
end_w = min(EXPECTED_WINDOWS, start_w + hist_windows - 1)
has_is = start_w in base_is_trades
has_hist_oos = all(w in base_oos_trades for w in range(start_w, end_w + 1))
if not (has_is and has_hist_oos):
return False, 0
total = base_is_trades[start_w] + sum(base_oos_trades[w] for w in range(start_w, end_w + 1))
return True, total
def compute_total_trades_range(base_is_trades: dict, base_oos_trades: dict, start_w: int, end_w: int):
"""
Total trade count for dedupe over an arbitrary window range (inclusive).
"""
if start_w > end_w:
return False, 0
has_is = start_w in base_is_trades
has_all_oos = all(w in base_oos_trades for w in range(start_w, end_w + 1))
if not (has_is and has_all_oos):
return False, 0
total = base_is_trades[start_w] + sum(base_oos_trades[w] for w in range(start_w, end_w + 1))
return True, total
def compute_total_trades_all(base_is_trades: dict, base_oos_trades: dict):
"""
Total trade count for dedupe: W01-IS plus OOS for all windows.
Returns (has_all, total_trades).
"""
return compute_total_trades_range(base_is_trades, base_oos_trades, 1, EXPECTED_WINDOWS)
def get_sl_from_filename_global(fname: str):
m = RE_SL.search(fname)
if not m:
return None
try:
return float(m.group(1))
except ValueError:
return None
def find_trade_list_file_global(strategy_dir: str):
p1 = os.path.join(strategy_dir, "trade_list", "trade_list.csv")
if os.path.isfile(p1):
return p1
p2 = os.path.join(strategy_dir, "trade_list.csv")
if os.path.isfile(p2):
return p2
tl_dir = os.path.join(strategy_dir, "trade_list")
if os.path.isdir(tl_dir):
candidates = []
for fn in os.listdir(tl_dir):
fp = os.path.join(tl_dir, fn)
if not os.path.isfile(fp):
continue
ext = os.path.splitext(fn)[1].lower()
if ext in (".csv", ".tsv", ".txt"):
pri = 0 if fn.lower() == "trade_list.csv" else (1 if ext == ".csv" else 2)
candidates.append((pri, fp))
if candidates:
candidates.sort(key=lambda x: x[0])
return candidates[0][1]
return None
def load_trade_list_global(strategy_dir: str):
fp = find_trade_list_file_global(strategy_dir)
if fp is None:
return None, None
try:
tdf = pd.read_csv(fp, sep=None, engine="python")
except Exception:
return None, fp
tdf.columns = [str(c).strip() for c in tdf.columns]
cols_lc = {c.lower(): c for c in tdf.columns}
required = ["window", "sample", "pnl"]
if not all(r in cols_lc for r in required):
return None, fp
tdf = tdf.rename(columns={
cols_lc["window"]: "window",
cols_lc["sample"]: "sample",
cols_lc["pnl"]: "pnl",
})
if "exit_time" in cols_lc:
tdf = tdf.rename(columns={cols_lc["exit_time"]: "exit_time"})
if "entry_time" in cols_lc:
tdf = tdf.rename(columns={cols_lc["entry_time"]: "entry_time"})
tdf["window"] = tdf["window"].astype(str).str.strip().map(normalize_window_label_to_active)