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 |  163 +++++++++++++++++++++++++++++++++++++++++++++--------
 1 files changed, 137 insertions(+), 26 deletions(-)

diff --git a/a_stock_manager.py b/a_stock_manager.py
index 59cc850..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'
@@ -346,41 +362,48 @@
     print("  • 支持多种数据源:AKShare、BaoStock、腾讯行情")
     print("  • 自动计算技术因子指标")
     print("  • 自动运行增强因子系统")
-    print("  • 支持增量更新")
+    print("  • 默认增量更新,全量重建需显式选择")
+    print("  • 重置数据会先移动到备份目录,不直接永久删除")
     
     print("\n选择数据更新方式:")
-    print("1. 使用真实数据源(AKShare/BaoStock)⭐推荐")
-    print("2. 使用本地模拟数据(仅测试用)")
-    print("3. 从AKShare在线获取(需要网络)")
-    print("4. 仅重新计算因子(不更新数据)⭐新增")
+    print("1. 增量更新全部A股 ⭐推荐")
+    print("2. 全量重建全部A股(耗时较长)")
+    print("3. 快速增量更新500只(连通性测试)")
+    print("4. 仅重新计算因子(不更新数据)")
     print("5. 仅补充北交所历史数据")
+    print("6. 安全重置本地数据(自动备份)")
+    print("7. 使用本地模拟数据(仅测试用)")
     print("0. 返回")
     
-    choice = input("\n请选择 (0-5): ").strip()
+    choice = input("\n请选择 (0-7): ").strip()
     
     if choice == '1':
-        result = fetch_real_data()
+        result = run_script(
+            'update_stock_data.py',
+            "增量更新全部A股",
+        )
         if result:
             print_info("数据更新完成,正在运行增强因子系统...")
             run_enhanced_factor_system()
         return result
     elif choice == '2':
-        result = run_script('data_update_v3.py', "使用本地模拟数据")
+        result = run_script(
+            'update_stock_data.py',
+            "全量重建全部A股",
+            args=['--full', '--n-stocks', 'all', '--days', '730'],
+        )
         if result:
-            print_info("数据更新完成,正在运行增强因子系统...")
+            print_info("全量重建完成,正在运行增强因子系统...")
             run_enhanced_factor_system()
         return result
     elif choice == '3':
-        args, stock_count_desc = prompt_stock_count_args()
-        if args is None:
-            return False
         result = run_script(
-            'data_update_v2.py',
-            f"从AKShare在线获取数据({stock_count_desc})",
-            args=args,
+            'update_stock_data.py',
+            "快速增量更新500只",
+            args=['--n-stocks', '500', '--force'],
         )
         if result:
-            print_info("数据更新完成,正在运行增强因子系统...")
+            print_info("快速增量更新完成,正在运行增强因子系统...")
             run_enhanced_factor_system()
         return result
     elif choice == '4':
@@ -393,6 +416,17 @@
         )
         if result:
             print_info("北交所数据补充完成,正在运行增强因子系统...")
+            run_enhanced_factor_system()
+        return result
+    elif choice == '6':
+        return run_script(
+            'reset_stock_data.py',
+            "安全重置本地行情、因子和选股数据",
+        )
+    elif choice == '7':
+        result = run_script('data_update_v3.py', "使用本地模拟数据")
+        if result:
+            print_info("模拟数据生成完成,正在运行增强因子系统...")
             run_enhanced_factor_system()
         return result
 
@@ -1840,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