"""Inspect a finished Optuna study and print the best trial + diverse top-N.""" from __future__ import annotations import sys from pathlib import Path PROJECT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(PROJECT)) import optuna from shared.optimizer.selector import select_diverse_topn from strategies.gold_scalper_pro.search_space import SEARCH_SPACE def main() -> int: db = sys.argv[1] if len(sys.argv) > 1 else str(PROJECT / "studies" / "optuna" / "gold_scalper_pro_is2025.db") name = sys.argv[2] if len(sys.argv) > 2 else "gold_scalper_pro_is2025" study = optuna.load_study(study_name=name, storage=f"sqlite:///{db}") completed = [t for t in study.trials if t.state.name == "COMPLETE"] passing = [t for t in completed if not t.user_attrs.get("violations")] print(f"=== study: {name} ===") print(f" total trials : {len(study.trials)}") print(f" completed : {len(completed)}") print(f" constraint-pass : {len(passing)}") if not passing: # Show the best by value anyway. best = max(completed, key=lambda t: t.value) print(f"\n no constraint-passing trials; best-by-value:") _print_trial(best, "best-by-value") return 1 print(f"\n === best (by score) ===") _print_trial(study.best_trial, "best") print(f"\n === diverse top-3 finalists ===") finalists = select_diverse_topn(study, n=3, ranges=SEARCH_SPACE) for i, t in enumerate(finalists, 1): _print_trial(t, f"finalist #{i}") return 0 def _print_trial(t, label: str) -> None: a = t.user_attrs print(f" [{label}] trial #{t.number} score={t.value:.2f}") print(f" net={a['net_profit']:.2f} PF={a['profit_factor']:.2f} " f"trades={a['total_trades']} DD%={a['max_equity_dd_pct']:.2%} " f"sharpe={a['sharpe']:.2f}") if a.get("violations"): print(f" violations: {a['violations']}") print(f" params:") for k, v in t.params.items(): print(f" {k:24s}={v}") if __name__ == "__main__": raise SystemExit(main())