-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevaluate.py
More file actions
1639 lines (1445 loc) · 69.7 KB
/
evaluate.py
File metadata and controls
1639 lines (1445 loc) · 69.7 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
"""
evaluate.py — CLI entry point for the Alpha Engine evaluator.
Runs all evaluation modules (signal quality analysis, component diagnostics,
self-adjustment optimizers) independently of simulation. Reads research.db
and trades.db directly; optionally reads simulation artifacts from S3
(sweep_df, portfolio_stats) if available.
Each module reports its data completeness — whether it had all inputs or
ran in degraded mode. The completeness manifest is saved alongside the
evaluation report.
Usage:
python evaluate.py --mode all # run everything
python evaluate.py --mode diagnostics # analysis modules only (no config promotion)
python evaluate.py --mode optimize # optimizer modules only
python evaluate.py --module signal-quality # single module
python evaluate.py --upload --freeze # upload results, skip S3 config writes
python evaluate.py --db /path/to/research.db # local DB override
python evaluate.py --trades-db /path/to/trades.db # local trades.db override
"""
from __future__ import annotations
import argparse
import io
import json
import logging
import os
import time as _time
from datetime import date
from pathlib import Path
# Structured logging + flow-doctor singleton via alpha-engine-lib (shared
# pattern across all 5 entrypoints; see executor/main.py for reference).
# Module-top so import-time errors in pandas / boto3 / analysis modules
# below are also captured by flow-doctor's ERROR handler. evaluate.py
# runs on EC2 spot via spot_backtest.sh; not in a Lambda image, so the
# simple repo-root path resolution works.
#
# exclude_patterns starts empty by deliberate convention.
from alpha_engine_lib.logging import setup_logging
_FLOW_DOCTOR_EXCLUDE_PATTERNS: list[str] = []
_FLOW_DOCTOR_YAML = os.path.join(os.path.dirname(os.path.abspath(__file__)), "flow-doctor.yaml")
setup_logging(
"evaluate",
flow_doctor_yaml=_FLOW_DOCTOR_YAML,
exclude_patterns=_FLOW_DOCTOR_EXCLUDE_PATTERNS,
)
import boto3
from botocore.exceptions import ClientError
import pandas as pd
import yaml
from analysis import signal_quality, regime_analysis, score_analysis, attribution
from analysis import factor_blend_sensitivity
from analysis import veto_analysis
from analysis import decision_capture_coverage, executor_decision_capture_coverage, provenance_grounding, quant_rank_quality
from analysis import agent_justification
from analysis import end_to_end
from analysis import trigger_scorecard, alpha_distribution, veto_value
from analysis import shadow_book as shadow_book_analysis
from analysis import exit_timing, macro_eval
from analysis import regime_stratified_sortino_runner
from optimizer import weight_optimizer, executor_optimizer, research_optimizer
from optimizer import (
trigger_optimizer, predictor_sizing_optimizer, barrier_sizing_optimizer,
stance_sizing_optimizer,
)
from optimizer import scanner_optimizer, pipeline_optimizer, tech_weight_ablation
from optimizer.config_archive import read_params_pit_or_current
from emailer import send_report_email
from reporter import build_report, save, upload_to_s3
from completeness import CompletenessTracker
from pipeline_common import (
load_config,
pull_research_db,
init_research_db,
find_trades_db,
push_predictor_rolling_metrics,
resolve_trading_day,
)
logger = logging.getLogger(__name__)
# ── CLI ──────────────────────────────────────────────────────────────────────
def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Alpha Engine Evaluator")
parser.add_argument(
"--mode", choices=["all", "diagnostics", "optimize"],
default="all",
help="all: run everything. diagnostics: analysis only. optimize: optimizers only.",
)
parser.add_argument(
"--module",
help="Run a single named module (e.g., signal-quality, weight-optimizer)",
)
parser.add_argument("--config", default="config.yaml")
parser.add_argument("--db", help="Override research_db path from config")
parser.add_argument("--trades-db", help="Override trades.db path")
parser.add_argument("--upload", action="store_true", help="Upload results to S3")
parser.add_argument("--date", default=date.today().isoformat(), help="Run date label")
parser.add_argument(
"--log-level", default="INFO",
choices=["DEBUG", "INFO", "WARNING", "ERROR"],
)
parser.add_argument(
"--freeze", action="store_true",
help="Compute recommendations but skip all S3 config promotions",
)
parser.add_argument(
"--stop-instance", action="store_true",
help="Stop this EC2 instance after completion (for scheduled runs)",
)
return parser.parse_args()
# ── Data source initialization ───────────────────────────────────────────────
def _init_data_sources(args: argparse.Namespace, config: dict) -> dict:
"""Initialize all data sources. Returns availability map."""
# Research DB
init_research_db(args.db, config)
db_path = config.get("research_db")
has_research_db = db_path is not None and os.path.exists(db_path)
# Trades DB
trades_db = getattr(args, "trades_db", None) or find_trades_db(config)
config["_trades_db"] = trades_db
has_trades_db = trades_db is not None and os.path.exists(trades_db)
# Simulation artifacts from S3 (written by backtest.py)
sweep_df = None
predictor_sweep_df = None
portfolio_stats = None
predictor_stats = None
bucket = config.get("output_bucket", config.get("signals_bucket", "alpha-engine-research"))
prefix = f"backtest/{args.date}"
s3 = boto3.client("s3")
missing_artifacts: list[str] = []
for artifact, loader in [
("sweep_df.parquet", lambda body: pd.read_parquet(io.BytesIO(body))),
("predictor_sweep_df.parquet", lambda body: pd.read_parquet(io.BytesIO(body))),
("portfolio_stats.json", lambda body: json.loads(body)),
("predictor_stats.json", lambda body: json.loads(body)),
]:
try:
resp = s3.get_object(Bucket=bucket, Key=f"{prefix}/{artifact}")
data = loader(resp["Body"].read())
if artifact == "sweep_df.parquet":
sweep_df = data
elif artifact == "predictor_sweep_df.parquet":
predictor_sweep_df = data
elif artifact == "portfolio_stats.json":
portfolio_stats = data
elif artifact == "predictor_stats.json":
predictor_stats = data
logger.info("Loaded simulation artifact: %s", artifact)
except ClientError as e:
# NoSuchKey is an expected state when backtest.py hasn't run
# for this date (e.g., first run after --mode param-sweep was
# skipped). Other ClientErrors are real S3 problems.
if e.response.get("Error", {}).get("Code") == "NoSuchKey":
logger.warning(
"Simulation artifact not found in S3: %s/%s — evaluator "
"will run without it (backtest.py may not have run)",
prefix, artifact,
)
missing_artifacts.append(artifact)
else:
logger.error(
"S3 ClientError loading %s/%s: %s — evaluator cannot "
"trust results", prefix, artifact, e,
)
raise
except Exception as e:
logger.error(
"Failed to parse simulation artifact %s/%s: %s — evaluator "
"cannot trust results", prefix, artifact, e, exc_info=True,
)
raise
# If ALL critical optimizer artifacts are missing, downstream optimizers
# will run against zero data and produce garbage config recommendations.
# Block the run by raising — operators must see the failure loudly so
# the Saturday pipeline does not auto-promote bad configs.
critical = {"sweep_df.parquet", "portfolio_stats.json"}
if critical.issubset(set(missing_artifacts)):
raise RuntimeError(
f"All critical simulation artifacts missing from "
f"s3://{bucket}/{prefix}/: {sorted(critical)}. "
f"backtest.py must run before evaluate.py in the Saturday "
f"pipeline. Check the upstream step status."
)
config["_sweep_df"] = sweep_df
config["_predictor_sweep_df"] = predictor_sweep_df
config["_portfolio_stats"] = portfolio_stats
config["_predictor_stats"] = predictor_stats
return {
"research_db": has_research_db,
"trades_db": has_trades_db,
"sweep_df": sweep_df is not None,
"predictor_sweep_df": predictor_sweep_df is not None,
"portfolio_stats": portfolio_stats is not None,
"predictor_stats": predictor_stats is not None,
}
# ── Signal quality pipeline ──────────────────────────────────────────────────
def _run_signal_quality(config: dict, tracker: CompletenessTracker, avail: dict) -> tuple:
"""Run signal quality analysis. Data seeding/backfilling is handled by
alpha-engine-data's signal_returns collector — the evaluator reads
research.db as-is.
Returns (sq_result, regime_rows, score_rows, attr_result, df_base).
"""
db_path = config.get("research_db")
# Check data completeness — warn if data module hasn't populated returns
if avail["research_db"]:
_check_data_freshness(db_path)
sq_result = tracker.run_module(
"signal_quality",
lambda: _compute_signal_quality(config),
required_inputs={"research_db": avail["research_db"]},
skip_if_missing=["research_db"],
)
if sq_result.get("status") in ("skipped", "error", "db_not_found"):
return sq_result, [], [], {"status": "skipped"}, None
# Load df_base for downstream modules
try:
df_base = signal_quality.load_score_performance(db_path)
except Exception:
df_base = None
regime_rows = tracker.run_module(
"regime_analysis",
lambda: _compute_regime(config),
required_inputs={"research_db": avail["research_db"]},
)
if not isinstance(regime_rows, list):
regime_rows = regime_rows.get("rows", []) if isinstance(regime_rows, dict) else []
score_rows = []
if df_base is not None:
thresholds = config.get("score_thresholds", [60, 65, 70, 75, 80, 85, 90])
min_samples = config.get("min_samples", 5)
score_rows = score_analysis.accuracy_by_threshold(
df_base, thresholds=thresholds, min_samples=min_samples,
)
attr_result = tracker.run_module(
"attribution",
lambda: attribution.compute_attribution(df_base) if df_base is not None else {"status": "skipped"},
required_inputs={"research_db": avail["research_db"], "df_base": df_base is not None},
skip_if_missing=["df_base"],
)
# Compute and push predictor rolling metrics (evaluation output, not data collection)
if avail["research_db"] and df_base is not None:
push_predictor_rolling_metrics(config, db_path or "")
return sq_result, regime_rows, score_rows, attr_result, df_base
def _check_data_freshness(db_path: str) -> None:
"""Warn if score_performance has stale rows that should have been backfilled by data module.
Non-fatal diagnostic: failures log at ERROR level so flow-doctor sees
them (corrupt DB, missing table, etc.) but do not raise — the caller's
main pipeline should continue. Previously this caught all exceptions
silently with ``pass``, which hid real DB corruption and SQL errors.
"""
import sqlite3
try:
conn = sqlite3.connect(db_path)
stale = conn.execute(
"SELECT COUNT(*) FROM score_performance "
"WHERE (return_5d IS NULL AND score_date <= date('now', '-10 days')) "
" OR (return_10d IS NULL AND score_date <= date('now', '-14 days')) "
" OR (return_30d IS NULL AND score_date <= date('now', '-45 days'))"
).fetchone()[0]
conn.close()
if stale > 0:
logger.warning(
"Data freshness: %d score_performance rows have missing returns "
"(data module may not have run signal_returns collector)", stale,
)
except Exception as exc:
logger.error(
"Data freshness check failed against %s: %s (non-fatal, "
"continuing with main pipeline)", db_path, exc, exc_info=True,
)
def _compute_signal_quality(config: dict) -> dict:
db_path = config.get("research_db")
min_samples = config.get("min_samples", 5)
if not db_path:
return {"status": "db_not_found"}
df_base = signal_quality.load_score_performance(db_path)
return signal_quality.compute_accuracy(df_base, min_samples=min_samples)
def _compute_regime(config: dict) -> dict:
db_path = config.get("research_db")
min_samples = config.get("min_samples", 5)
if not db_path:
return {"status": "skipped", "rows": []}
df_regime = regime_analysis.load_with_regime(db_path)
rows = regime_analysis.accuracy_by_regime(df_regime, min_samples=min_samples)
return {"status": "ok", "rows": rows}
# ── Diagnostics ──────────────────────────────────────────────────────────────
def _run_diagnostics(
config: dict,
tracker: CompletenessTracker,
avail: dict,
df_base,
) -> dict:
"""Run all diagnostic modules. Returns dict of results."""
db_path = config.get("research_db")
trades_db = config.get("_trades_db")
results = {}
# End-to-end lift metrics
results["e2e_lift"] = tracker.run_module(
"end_to_end_lift",
lambda: end_to_end.compute_lift_metrics(
research_db_path=db_path, trades_db_path=trades_db,
),
required_inputs={"research_db": avail["research_db"]},
skip_if_missing=["research_db"],
)
# Entry trigger scorecard
results["trigger_scorecard"] = tracker.run_module(
"trigger_scorecard",
lambda: trigger_scorecard.compute_trigger_scorecard(trades_db),
required_inputs={"trades_db": avail["trades_db"]},
skip_if_missing=["trades_db"],
)
# Alpha magnitude distribution
results["alpha_dist"] = tracker.run_module(
"alpha_distribution",
lambda: alpha_distribution.compute_alpha_distribution(db_path),
required_inputs={"research_db": avail["research_db"]},
skip_if_missing=["research_db"],
)
# Score calibration curve
results["score_calibration"] = tracker.run_module(
"score_calibration",
lambda: alpha_distribution.compute_score_calibration(db_path),
required_inputs={"research_db": avail["research_db"]},
skip_if_missing=["research_db"],
)
# Net veto value
results["veto_value"] = tracker.run_module(
"veto_value",
lambda: veto_value.compute_veto_value(
research_db_path=db_path, trades_db_path=trades_db,
),
required_inputs={"research_db": avail["research_db"]},
skip_if_missing=["research_db"],
)
# Predictor confusion matrix
results["confusion_matrix"] = tracker.run_module(
"predictor_confusion",
lambda: _run_confusion_matrix(db_path),
required_inputs={"research_db": avail["research_db"]},
skip_if_missing=["research_db"],
)
# Shadow book analysis
results["shadow_book"] = tracker.run_module(
"shadow_book",
lambda: shadow_book_analysis.compute_shadow_book_analysis(
trades_db_path=trades_db,
research_db_path=db_path if avail["research_db"] else None,
),
required_inputs={"trades_db": avail["trades_db"]},
skip_if_missing=["trades_db"],
)
# Exit timing analysis
results["exit_timing"] = tracker.run_module(
"exit_timing",
lambda: exit_timing.compute_exit_timing(trades_db),
required_inputs={"trades_db": avail["trades_db"]},
skip_if_missing=["trades_db"],
)
# Post-trade analysis
results["post_trade"] = tracker.run_module(
"post_trade",
lambda: _run_post_trade(trades_db),
required_inputs={"trades_db": avail["trades_db"]},
skip_if_missing=["trades_db"],
)
# Barrier coherence (predictor labels ↔ executor exits). The static
# definition-divergence leg runs even with no trades, so this is NOT gated on
# trades_db availability — it always emits an artifact (per the
# always-emit-observational-artifact convention).
results["barrier_coherence"] = tracker.run_module(
"barrier_coherence",
lambda: _run_barrier_coherence(config, trades_db),
required_inputs={},
)
# Factor blend sensitivity — config-vs-realized stance ordering check.
# PR 6 of scanner-placement arc + follow-up wire-in. Reads existing
# score_performance df_base; backtester config may override regime
# weights via factor_blend.regime_weights, else falls back to the
# canonical defaults mirroring alpha-engine-config/research/scoring.yaml.
fb_cfg = (config or {}).get("factor_blend") or {}
fb_regime_weights = fb_cfg.get(
"regime_weights",
factor_blend_sensitivity.DEFAULT_REGIME_WEIGHTS,
)
fb_horizon = fb_cfg.get("horizon", "10d")
results["factor_blend_sensitivity"] = tracker.run_module(
"factor_blend_sensitivity",
lambda: factor_blend_sensitivity.build_sensitivity_report(
df_base if df_base is not None else __import__("pandas").DataFrame(),
fb_regime_weights,
horizon=fb_horizon,
),
required_inputs={
"research_db": avail["research_db"],
"df_base": df_base is not None,
},
skip_if_missing=["df_base"],
)
# Macro multiplier evaluation
results["macro_eval"] = tracker.run_module(
"macro_eval",
lambda: macro_eval.compute_macro_evaluation(db_path),
required_inputs={"research_db": avail["research_db"]},
skip_if_missing=["research_db"],
)
# Regime-stratified Sortino (Stage C.2 T2). Reads score_performance,
# groups picks by market_regime, computes Sortino/Sharpe/log-alpha
# per (regime, horizon) and the bull-bear Sortino spread (headline
# T2 metric). Writes canonical eval-artifact to
# s3://{bucket}/regime/stratified_sortino/{run_id}.json + latest.json
# sidecar — consumed by the dashboard's Regime page.
results["regime_stratified_sortino"] = tracker.run_module(
"regime_stratified_sortino",
lambda: regime_stratified_sortino_runner.run_regime_stratified_sortino(
db_path=db_path,
s3_bucket=config.get("s3_bucket") or config.get("signals_bucket"),
),
required_inputs={"research_db": avail["research_db"]},
skip_if_missing=["research_db"],
)
# Monte Carlo significance test
results["monte_carlo"] = tracker.run_module(
"monte_carlo",
lambda: _run_monte_carlo(config),
required_inputs={"research_db": avail["research_db"]},
skip_if_missing=["research_db"],
)
# Production health monitoring
results["production_health"] = tracker.run_module(
"production_health",
lambda: _run_production_health(config),
required_inputs={"research_db": avail["research_db"]},
skip_if_missing=["research_db"],
)
# Decision-capture coverage (Phase 2 transparency-inventory).
# Reads S3 only — no local DB inputs required, runs even when the
# research DB pull fails. Returns "no_recent_sf_run" when the S3
# capture tree is empty for the trailing week (e.g. a smoke run on
# a brand-new bucket).
results["decision_capture_coverage"] = tracker.run_module(
"decision_capture_coverage",
lambda: decision_capture_coverage.compute_decision_capture_coverage(
bucket=config.get("signals_bucket", "alpha-engine-research"),
run_date=config.get("_run_date"),
),
required_inputs={},
)
# Stance-distribution drift — Phase 5 acceptance check
# (attractiveness-pillars-260520.md). Compares this week's
# predictor/predictions/{date}.json stance counts to the prior 4 ISO
# weeks' mean ± 2σ; fires a Telegram + SNS alert via
# alpha_engine_lib.alerts.publish on FAIL. Defense-in-depth against
# the pillar-aware classify_stance code path collapsing the
# distribution into a single stance without surfacing through NAV
# for weeks. ROADMAP L1614.
from analysis import stance_distribution
results["stance_distribution_drift"] = tracker.run_module(
"stance_distribution_drift",
lambda: stance_distribution.compute_stance_distribution_drift(
bucket=config.get("signals_bucket", "alpha-engine-research"),
current_date=config.get("_run_date") or date.today().isoformat(),
),
required_inputs={},
)
# Executor-side decision-capture coverage (L2308 PR 5). Sibling of the
# research-side coverage above; reads executor:* artifacts emitted by
# L2308 PRs 1-4 producers (entry_triggers / position_sizer /
# risk_guard / exit_rules). Insufficient_data until
# ALPHA_ENGINE_DECISION_CAPTURE_ENABLED is enabled on the trading EC2
# AND ≥1 weekday SF run has captured artifacts.
results["executor_decision_capture_coverage"] = tracker.run_module(
"executor_decision_capture_coverage",
lambda: executor_decision_capture_coverage.compute_executor_decision_capture_coverage(
bucket=config.get("signals_bucket", "alpha-engine-research"),
run_date=config.get("_run_date"),
),
required_inputs={},
)
# Provenance grounding — fourth leg of agent-justification stack.
# Per-agent tool-call + input-trace metrics on captured artifacts.
# Reads S3 only — no local DB inputs required.
results["provenance_grounding"] = tracker.run_module(
"provenance_grounding",
lambda: provenance_grounding.compute_provenance_grounding(
bucket=config.get("signals_bucket", "alpha-engine-research"),
run_date=config.get("_run_date"),
),
required_inputs={},
)
# Quant rank quality — per-sector corr(quant_rank, return_5d) over a
# rolling 8-week window. Surfaces "is the technical scorer's
# ranking even ordering correctly?" before drift compounds. The
# 2026-05-09 evaluator-email post-mortem found healthcare/industrials/
# tech rank-correlations at +0.33-0.36 (anti-skill); without this
# diagnostic running weekly the inversion was caught only in
# retrospect via per-stage decomposition.
results["quant_rank_quality"] = tracker.run_module(
"quant_rank_quality",
lambda: quant_rank_quality.compute_quant_rank_quality(
db_path=config.get("research_db"),
run_date=config.get("_run_date"),
),
required_inputs={"research_db": config.get("research_db")},
)
# Agent-justification stack summaries — judge / clustering / concordance /
# counterfactual aggregated across agents for the most-recent SF date.
# Pre-2026-05-07 reorder these Lambdas ran AFTER Evaluator so their
# outputs were absent from the email; the SF reorder moves them
# upstream of PredictorTraining so this loader has fresh data each
# week. S3-only reads; no DB inputs.
results["agent_justification"] = tracker.run_module(
"agent_justification",
lambda: agent_justification.summarize_all(
bucket=config.get("signals_bucket", "alpha-engine-research"),
run_date=config.get("_run_date"),
),
required_inputs={},
)
# Feature drift detection
results["feature_drift"] = tracker.run_module(
"feature_drift",
lambda: _run_feature_drift(config),
required_inputs={"research_db": avail["research_db"]},
skip_if_missing=["research_db"],
)
return results
def _run_confusion_matrix(db_path: str) -> dict:
from analysis.predictor_confusion import compute_confusion_matrix
return compute_confusion_matrix(db_path)
def _run_post_trade(trades_db: str) -> dict:
from analysis.post_trade import compute_post_trade_analysis
return compute_post_trade_analysis(trades_db)
def _run_barrier_coherence(config: dict, trades_db: str) -> dict:
"""Predictor↔executor triple-barrier coherence diagnostic.
Reads the LIVE, sweep-tuned executor barriers from
``config/executor_params.json`` on S3 so leg (a) compares against the real
execution policy, not stale defaults. On any S3 failure we fall back to the
documented defaults but record the fallback in ``exec_params_source`` and
WARN-log it — not a silent swallow (the diagnostic still runs; the source is
visible in the rendered artifact).
"""
from analysis.barrier_coherence import compute_barrier_coherence
bucket = config.get("signals_bucket", "alpha-engine-research")
exec_params: dict | None = None
exec_source = "defaults (executor/strategies/config.py)"
_BARRIER_KEYS = (
"atr_multiplier",
"profit_take_pct",
"time_decay_reduce_days",
"time_decay_exit_days",
)
try:
s3 = boto3.client("s3")
obj = s3.get_object(Bucket=bucket, Key="config/executor_params.json")
data = json.loads(obj["Body"].read())
exec_params = {k: data[k] for k in _BARRIER_KEYS if k in data}
if exec_params:
exec_source = "live S3 config/executor_params.json (sweep-tuned)"
else:
exec_params = None
logger.warning(
"barrier_coherence: executor_params.json present but carried no "
"barrier keys; falling back to documented defaults"
)
except Exception as e: # noqa: BLE001 — best-effort live read; fallback recorded, not swallowed.
logger.warning(
"barrier_coherence: could not read live executor_params.json (%s); "
"using documented defaults", e
)
return compute_barrier_coherence(
trades_db, exec_params=exec_params, exec_params_source=exec_source
)
def _run_monte_carlo(config: dict) -> dict:
from analysis.monte_carlo import run_monte_carlo
db_path = config.get("research_db")
return run_monte_carlo(
research_db_path=db_path,
n_permutations=config.get("monte_carlo_permutations", 200),
horizon=config.get("monte_carlo_horizon", "5d"),
)
def _run_production_health(config: dict) -> dict:
from analysis.production_health import compute_production_health
db_path = config.get("research_db", "")
bucket = config.get("signals_bucket", "alpha-engine-research")
return compute_production_health(db_path, bucket)
def _run_feature_drift(config: dict) -> dict:
from analysis.feature_drift import compute_feature_drift
db_path = config.get("research_db", "")
bucket = config.get("signals_bucket", "alpha-engine-research")
return compute_feature_drift(db_path, bucket)
# ── Optimizers ───────────────────────────────────────────────────────────────
def _read_current_weights(config: dict) -> dict:
"""Read current scoring weights from S3, local config, or defaults."""
bucket = config.get("signals_bucket", "alpha-engine-research")
try:
s3 = boto3.client("s3")
obj = s3.get_object(Bucket=bucket, Key="config/scoring_weights.json")
data = json.loads(obj["Body"].read())
weights = {k: float(data[k]) for k in ("news", "research") if k in data}
if len(weights) == 2:
return weights
except Exception:
pass
research_paths = config.get("research_paths", [])
if isinstance(research_paths, str):
research_paths = [research_paths]
research_path = next((p for p in research_paths if os.path.isdir(p)), None)
if research_path:
universe_yaml = os.path.join(research_path, "config", "universe.yaml")
try:
with open(universe_yaml) as f:
universe = yaml.safe_load(f)
weights = universe.get("scoring_weights", {})
if weights:
return weights
except Exception:
pass
return weight_optimizer._cfg.get("default_weights", weight_optimizer._DEFAULT_WEIGHTS).copy()
def _run_optimizers(
config: dict,
tracker: CompletenessTracker,
avail: dict,
df_base,
freeze: bool,
diagnostics: dict,
) -> dict:
"""Run all optimizer modules. Returns dict of results."""
bucket = config.get("signals_bucket", "alpha-engine-research")
db_path = config.get("research_db")
results = {}
# Weight optimizer
results["weight_result"] = tracker.run_module(
"weight_optimizer",
lambda: _run_weight_opt(config, df_base, freeze),
required_inputs={"research_db": avail["research_db"], "df_base": df_base is not None},
skip_if_missing=["df_base"],
)
# Veto analysis optimizer
results["veto_result"] = tracker.run_module(
"veto_optimizer",
lambda: _run_veto_opt(config, df_base, freeze),
required_inputs={"research_db": avail["research_db"], "df_base": df_base is not None},
skip_if_missing=["df_base"],
)
# Research params optimizer
results["research_params"] = tracker.run_module(
"research_optimizer",
lambda: _run_research_opt(config, df_base, freeze),
required_inputs={"research_db": avail["research_db"], "df_base": df_base is not None},
skip_if_missing=["df_base"],
)
# Trigger optimizer
trigger_result = diagnostics.get("trigger_scorecard")
results["trigger_opt"] = tracker.run_module(
"trigger_optimizer",
lambda: _run_trigger_opt(trigger_result, freeze, bucket),
required_inputs={"trigger_scorecard": trigger_result is not None and trigger_result.get("status") == "ok"},
skip_if_missing=["trigger_scorecard"],
)
# Predictor sizing optimizer
results["predictor_sizing"] = tracker.run_module(
"predictor_sizing",
lambda: _run_predictor_sizing(db_path, freeze, bucket),
required_inputs={"research_db": avail["research_db"]},
skip_if_missing=["research_db"],
)
# Barrier-win-prob sizing optimizer (Task B3). IC-criterion promotion gate
# for the executor's dormant barrier_win_prob sizing multiplier; mirrors
# predictor_sizing. Reports column_absent until alpha-engine-data records
# barrier_win_prob into predictor_outcomes (B3 activation prerequisite).
results["barrier_sizing"] = tracker.run_module(
"barrier_sizing",
lambda: _run_barrier_sizing(db_path, freeze, bucket),
required_inputs={"research_db": avail["research_db"]},
skip_if_missing=["research_db"],
)
# Stance-conditional sizing optimizer (L300). Offline-IC gate replacing the
# inert predictionless param sweep over stance_size_*; tunes the multipliers
# against realized per-stance alpha. Reports stance_column_absent until the
# score_performance stance migration lands (mirrors barrier).
stance_sizing_optimizer.init_config(config)
results["stance_sizing"] = tracker.run_module(
"stance_sizing",
lambda: _run_stance_sizing(db_path, freeze, bucket),
required_inputs={"research_db": avail["research_db"]},
skip_if_missing=["research_db"],
)
# Scanner optimizer
results["scanner_opt"] = tracker.run_module(
"scanner_optimizer",
lambda: _run_scanner_opt(config, db_path, freeze, bucket),
required_inputs={"research_db": avail["research_db"]},
skip_if_missing=["research_db"],
)
# Pipeline optimizer (team slots + CIO)
e2e_lift = diagnostics.get("e2e_lift")
has_e2e = e2e_lift is not None and e2e_lift.get("status") == "ok"
results["team_opt"] = tracker.run_module(
"team_slot_optimizer",
lambda: _run_team_opt(e2e_lift, freeze, bucket),
required_inputs={"e2e_lift": has_e2e},
skip_if_missing=["e2e_lift"],
)
results["cio_opt"] = tracker.run_module(
"cio_optimizer",
lambda: _run_cio_opt(e2e_lift, freeze, bucket),
required_inputs={"e2e_lift": has_e2e},
skip_if_missing=["e2e_lift"],
)
# Tech weight ablation — per-sector recommendation by sub-score
# rank-correlation grid search. Pairs with PR-A's quant_rank_quality
# diagnostic + PR-B's research v15 sub-score persistence.
# Status="insufficient_data" until ≥30 rows per team have populated
# sub-scores. Apply path is gated behind two flags
# (use_tech_ablation_target + enforce_tech_ablation) and a 4-week
# reproduction guard — see optimizer/tech_weight_ablation.apply().
results["tech_weight_ablation"] = tracker.run_module(
"tech_weight_ablation",
lambda: _run_tech_weight_ablation(config, freeze),
required_inputs={"research_db": avail["research_db"]},
skip_if_missing=["research_db"],
)
# Executor optimizer (needs sweep_df from simulation)
sweep_df = config.get("_sweep_df")
predictor_sweep_df = config.get("_predictor_sweep_df")
effective_sweep = sweep_df if sweep_df is not None else predictor_sweep_df
results["executor_rec"] = tracker.run_module(
"executor_optimizer",
lambda: _run_executor_opt(config, effective_sweep, freeze),
required_inputs={
"sweep_df": sweep_df is not None,
"predictor_sweep_df": predictor_sweep_df is not None,
},
skip_if_missing=None, # runs in degraded mode, doesn't skip
)
return results
def _run_weight_opt(config: dict, df_base, freeze: bool) -> dict:
bucket = config.get("signals_bucket", "alpha-engine-research")
current_weights = _read_current_weights(config)
min_samples = config.get("weight_optimizer_min_samples", 30)
df_with_sub = weight_optimizer.load_with_subscores(df_base, bucket)
result = weight_optimizer.compute_weights(
df_with_sub, current_weights=current_weights,
min_samples=min_samples, bucket=bucket,
)
if freeze:
result["apply_result"] = {"applied": False, "reason": "frozen (--freeze flag)"}
else:
result["apply_result"] = weight_optimizer.apply_weights(result, bucket)
return result
def _run_veto_opt(config: dict, df_base, freeze: bool) -> dict:
bucket = config.get("signals_bucket", "alpha-engine-research")
result = veto_analysis.analyze_veto_effectiveness(df_base, bucket)
if result.get("status") == "ok":
if freeze:
result["apply_result"] = {"applied": False, "reason": "frozen (--freeze flag)"}
else:
result["apply_result"] = veto_analysis.apply(result, bucket)
return result
def _run_research_opt(config: dict, df_base, freeze: bool) -> dict:
bucket = config.get("signals_bucket", "alpha-engine-research")
current_rp = read_params_pit_or_current(research_optimizer, bucket, config)
corr_result = research_optimizer.compute_boost_correlations(df_base, bucket)
if corr_result.get("status") != "ok":
return corr_result
rp_result = research_optimizer.recommend(corr_result, current_rp)
if rp_result.get("status") == "ok":
if freeze:
rp_result["apply_result"] = {"applied": False, "reason": "frozen (--freeze flag)"}
else:
rp_result["apply_result"] = research_optimizer.apply(rp_result, bucket)
return rp_result
def _run_trigger_opt(trigger_result: dict, freeze: bool, bucket: str) -> dict:
result = trigger_optimizer.analyze(trigger_result)
if result.get("status") == "ok":
if freeze:
result["apply_result"] = {"applied": False, "reason": "frozen (--freeze flag)"}
else:
result["apply_result"] = trigger_optimizer.apply(result, bucket)
return result
def _run_predictor_sizing(db_path: str, freeze: bool, bucket: str) -> dict:
result = predictor_sizing_optimizer.analyze(db_path)
if result.get("status") == "ok":
if freeze:
result["apply_result"] = {"applied": False, "reason": "frozen (--freeze flag)"}
elif result.get("recommendation") == "enable":
result["apply_result"] = predictor_sizing_optimizer.apply(result, bucket)
return result
def _run_barrier_sizing(db_path: str, freeze: bool, bucket: str) -> dict:
result = barrier_sizing_optimizer.analyze(db_path)
if result.get("status") == "ok":
if freeze:
result["apply_result"] = {"applied": False, "reason": "frozen (--freeze flag)"}
elif result.get("recommendation") == "enable":
result["apply_result"] = barrier_sizing_optimizer.apply(result, bucket)
return result
def _run_stance_sizing(db_path: str, freeze: bool, bucket: str) -> dict:
"""L300: offline-IC stance-sizing optimizer. Reports stance_column_absent
until the score_performance stance migration lands (mirrors barrier)."""
result = stance_sizing_optimizer.analyze(db_path)
if result.get("status") == "ok":
if freeze:
result["apply_result"] = {"applied": False, "reason": "frozen (--freeze flag)"}
elif result.get("recommendation") == "enable":
result["apply_result"] = stance_sizing_optimizer.apply(result, bucket)
return result
def _run_scanner_opt(config: dict, db_path: str, freeze: bool, bucket: str) -> dict:
analysis = scanner_optimizer.analyze(db_path)
if analysis.get("status") != "ok":
return analysis
current = read_params_pit_or_current(scanner_optimizer, bucket, config)
result = scanner_optimizer.recommend(analysis, current)
if result.get("status") == "ok":
if freeze:
result["apply_result"] = {"applied": False, "reason": "frozen (--freeze flag)"}
else:
result["apply_result"] = scanner_optimizer.apply(result, bucket)
result["analysis"] = analysis
return result
def _run_team_opt(e2e_lift: dict, freeze: bool, bucket: str) -> dict:
analysis = pipeline_optimizer.analyze_team_performance(e2e_lift)
if analysis.get("status") != "ok":
return analysis
result = pipeline_optimizer.recommend_team_slots(analysis)
if result.get("status") == "ok":
if freeze:
result["apply_result"] = {"applied": False, "reason": "frozen (--freeze flag)"}
else:
result["apply_result"] = pipeline_optimizer.apply_team_slots(result, bucket)
result["analysis"] = analysis
return result
def _run_cio_opt(e2e_lift: dict, freeze: bool, bucket: str) -> dict:
result = pipeline_optimizer.analyze_cio_performance(e2e_lift)
if result.get("status") == "ok":
if freeze:
result["apply_result"] = {"applied": False, "reason": "frozen (--freeze flag)"}
elif result.get("recommendation") == "deterministic":
result["apply_result"] = pipeline_optimizer.apply_cio_mode(result, bucket)
return result
def _run_tech_weight_ablation(config: dict, freeze: bool) -> dict:
"""Run tech_weight_ablation compute + apply path (ROADMAP L2553).
Apply contract mirrors executor_optimizer: compute the
recommendation, then call ``apply()`` to (optionally) write shadow
+ live S3 artifacts. ``freeze=True`` short-circuits the apply()
call entirely so ``--freeze`` evaluator runs produce zero S3 side
effects.
"""
bucket = config.get("signals_bucket", "alpha-engine-research")
result = tech_weight_ablation.compute_tech_weight_ablation(
db_path=config.get("research_db"),
run_date=config.get("_run_date"),
)
if freeze:
result["apply_result"] = {
"applied": False, "reason": "frozen (--freeze flag)",
}
else:
result["apply_result"] = tech_weight_ablation.apply(result, bucket)
return result
def _publish_executor_opt_rejection_alert(result: dict, config: dict) -> None:
"""Fire a named alert when ``executor_optimizer.recommend()`` returns
a non-``ok`` status — closes 5/23-SF P0 sweep item (c).
Pre-fix: REJECTED status surfaced ONLY in ``report.md`` ("Refusing to
promote — per the canonical-alpha framework, alpha-positive is a hard
constraint, not a side-output"). No CW metric, no Telegram, no SNS.
Operator only saw it if they read the report.