From c9a0711438d32f33b65ffa29d8efd7aa37d61bdc Mon Sep 17 00:00:00 2001
From: log
Date: Thu, 23 Jul 2026 21:54:18 +0800
Subject: [PATCH] feat: add validated ML factor model training

---
 a_stock_manager.py |  113 +++++++++++++++++++++++++++++++++++++++++++++++++++-----
 1 files changed, 103 insertions(+), 10 deletions(-)

diff --git a/a_stock_manager.py b/a_stock_manager.py
index b6ac6e5..7670b2c 100644
--- a/a_stock_manager.py
+++ b/a_stock_manager.py
@@ -22,6 +22,22 @@
 sys.path.insert(0, str(code_dir))
 sys.path.insert(0, str(project_root))
 
+
+def _configure_console_encoding():
+    """避免Windows GBK控制台因特殊符号中断长任务。"""
+    for stream in (sys.stdout, sys.stderr):
+        reconfigure = getattr(stream, 'reconfigure', None)
+        if reconfigure is None:
+            continue
+        try:
+            reconfigure(errors='backslashreplace')
+        except (OSError, ValueError):
+            pass
+
+
+_configure_console_encoding()
+
+
 class Color:
     """终端颜色"""
     HEADER = '\033[95m'
@@ -1858,30 +1874,107 @@
 def ml_factor_combiner():
     """ML因子组合器"""
     print_header("ML因子组合器")
-    print_info("功能:使用机器学习方法组合多个因子")
+    print_info("功能:训练并验证每日主控使用的独立因子二次排序模型")
     
     try:
-        from code.strategy.ml_factor_combiner import MLFactorCombiner
+        from scripts.train_ml_factor_model import (
+            load_model_summary,
+            train_and_save_model,
+        )
         
         print("\n机器学习方法:")
+        print("  • 梯度提升树(默认)")
         print("  • 随机森林")
-        print("  • XGBoost")
-        print("  • 神经网络")
+        print("  • Ridge线性模型")
         
         print("\n选择操作:")
         print("1. 训练模型")
-        print("2. 因子重要性分析")
+        print("2. 查看模型验证结果和因子重要性")
         print("0. 返回")
         
         choice = input("\n请选择 (0-2): ").strip()
         
         if choice == '1':
-            print_info("训练ML因子组合模型...")
-            combiner = MLFactorCombiner()
-            print_info("需要准备因子数据和标签")
+            print("\n选择训练方法:")
+            print("1. 梯度提升树(推荐)")
+            print("2. 随机森林")
+            print("3. Ridge线性模型")
+            print("0. 取消")
+            model_choice = input("\n请选择 (0-3): ").strip()
+            model_types = {'1': 'gbdt', '2': 'rf', '3': 'ridge'}
+            if model_choice == '0':
+                return
+            if model_choice not in model_types:
+                print_error("无效的训练方法")
+                return
+
+            print_info("开始生成因子、时间切分并训练模型...")
+            print_info("模型和验证记录只保存在本机 models 目录,不会上传")
+            result = train_and_save_model(model_type=model_types[model_choice])
+            metrics = result.get('metrics', {})
+            if metrics:
+                ic_mean = metrics.get('ic_mean')
+                print("\n样本外验证:")
+                print(
+                    f"  IC均值: {ic_mean:.4f}"
+                    if ic_mean is not None
+                    else "  IC均值: 不可用"
+                )
+                print(f"  有效IC天数: {metrics.get('valid_ic_days', 0)}")
+                print(f"  IC正向率: {metrics.get('ic_positive_rate', 0) or 0:.1%}")
+                print(f"  MAE: {metrics.get('mae', 0):.6f}")
+
+            if result.get('approved'):
+                print_success(result['message'])
+                print_info("下次运行每日主控时会自动加载该模型")
+            elif result.get('success'):
+                print_warning(result['message'])
+                print_info("候选模型已留在本机,未通过验证前不会参与每日排序")
+                if result.get('active_model_preserved'):
+                    print_info("已有正式模型未被覆盖")
+            else:
+                print_error(result.get('message', '训练失败'))
         elif choice == '2':
-            print_info("因子重要性分析...")
-            print("需要加载训练好的模型")
+            summary = load_model_summary()
+            if not summary:
+                print_warning("尚无训练记录,请先选择“训练模型”")
+                return
+
+            artifact_name = (
+                "正式模型"
+                if summary.get('artifact_kind') == 'active'
+                else "候选模型"
+            )
+            validation = summary.get('validation', {})
+            print(f"\n{artifact_name}:")
+            print(f"  方法: {summary.get('model_name', '未知')}")
+            print(f"  训练时间: {summary.get('trained_at', '未知')}")
+            print(
+                f"  验证区间: {summary.get('validation_start_date', '未知')}"
+                f" 至 {summary.get('validation_end_date', '未知')}"
+            )
+            ic_mean = validation.get('ic_mean')
+            print(
+                f"  样本外IC均值: {ic_mean:.4f}"
+                if ic_mean is not None
+                else "  样本外IC均值: 不可用"
+            )
+            print(f"  发布状态: {summary.get('promotion_status', '未知')}")
+
+            importance = summary.get('feature_importance', {})
+            print("\n重要性最高的因子:")
+            if not importance:
+                print("  暂无因子重要性记录")
+            else:
+                ranked = sorted(
+                    importance.items(),
+                    key=lambda item: item[1],
+                    reverse=True,
+                )
+                for index, (factor, weight) in enumerate(ranked[:10], start=1):
+                    print(f"  {index:2d}. {factor}: {weight:.2%}")
+        elif choice != '0':
+            print_error("无效的选择")
             
     except Exception as e:
         print_error(f"ML因子组合器启动失败: {e}")

--
Gitblit v1.8.0