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 |  215 ++++++++++++++++++++++++++++++++++++++++++++++-------
 1 files changed, 185 insertions(+), 30 deletions(-)

diff --git a/a_stock_manager.py b/a_stock_manager.py
index ae2e11e..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'
@@ -183,23 +199,23 @@
     """打印信息消息"""
     print(f"{Color.OKCYAN}ℹ {text}{Color.ENDC}")
 
-def run_script(script_name, description="", return_result=False):
+def run_script(script_name, description="", return_result=False, args=None):
     """运行脚本"""
     if description:
         print_info(f"正在执行: {description}")
     script_path = scripts_dir / script_name
+    command = [sys.executable, str(script_path)]
+    if args:
+        command.extend(args)
+
     try:
         result = subprocess.run(
-            [sys.executable, str(script_path)],
+            command,
             cwd=project_root,
-            capture_output=True,
+            capture_output=False,
             text=True
         )
-        if result.stdout:
-            print(result.stdout)
-        if result.stderr:
-            print_error(result.stderr)
-        
+
         if return_result:
             result_file = project_root / 'logs' / 'script_result.json'
             if result_file.exists():
@@ -213,6 +229,32 @@
     except Exception as e:
         print_error(f"执行失败: {e}")
         return False
+
+
+def prompt_stock_count_args():
+    """选择数据更新股票数量,并返回传给数据更新脚本的参数。"""
+    print(f"\n{Color.BOLD}【股票数量】{Color.ENDC}")
+    print("1. 快速更新 500 只股票 ⭐推荐")
+    print("2. 全量更新全部A股(较慢)")
+    print("3. 自定义数量")
+    print("0. 返回")
+
+    choice = input("\n请选择股票数量 (0-3): ").strip()
+    if choice == '1':
+        return ["--n-stocks", "500"], "500只股票"
+    if choice == '2':
+        return ["--n-stocks", "all"], "全量A股"
+    if choice == '3':
+        value = input("请输入股票数量: ").strip()
+        if not value.isdigit() or int(value) <= 0:
+            print_error("股票数量必须是正整数")
+            return None, None
+        return ["--n-stocks", value], f"{value}只股票"
+    if choice == '0':
+        return None, None
+
+    print_error("无效的选择")
+    return None, None
 
 def run_enhanced_factor_system(data_file=None):
     """运行增强因子系统"""
@@ -317,40 +359,76 @@
     
     print(f"\n{Color.BOLD}【功能说明】{Color.ENDC}")
     print("  数据更新用于获取最新的股票市场数据")
-    print("  • 支持多种数据源:AKShare、BaoStock")
+    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-4): ").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':
-        result = run_script('data_update_v2.py', "从AKShare在线获取数据")
+        result = run_script(
+            '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':
         return run_enhanced_factor_system()
+    elif choice == '5':
+        result = run_script(
+            'data_update_v2.py',
+            "补充北交所历史数据并合并现有数据",
+            args=['--bse-only', '--n-stocks', 'all'],
+        )
+        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
 
 def fetch_real_data():
     """获取真实数据"""
@@ -1796,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