3 files added
7 files modified
| | |
| | | # A股量化系统 v5.3 |
| | | # A股量化系统 v5.4 |
| | | |
| | | > 智能α因子选股 + 持仓跟踪 + 换仓策略 + 风控体系 + 专业推送 + 统一命令行入口 |
| | | |
| | |
| | | - 🎮 **统一命令行入口**(`a_stock_manager.py` - 所有功能一键管理) |
| | | - 📱 多数据源整合(智兔数服、腾讯财经、新浪财经、AKShare等) |
| | | |
| | | **最新更新(v5.3):** |
| | | **最新更新(v5.4):** |
| | | |
| | | - ✅ **默认增量更新** - 普通更新刷新并覆盖最近行情窗口,补齐上次可能缺失的数据 |
| | | - ✅ **显式全量重建** - 仅在指定 `--full` 时重新下载全部历史数据 |
| | | - ✅ **安全数据重置** - 行情、因子和选股结果先移动到时间戳备份目录,不直接永久删除 |
| | | - ✅ **OpenClaw Skill 路由** - “更新A股数据”默认调用增量入口,支持全量重建和安全重置指令 |
| | | |
| | | **版本 v5.3:** |
| | | |
| | | - ✅ **README完整功能文档** - 详细列出主入口所有菜单功能(6大模块+4个快捷入口) |
| | | - ✅ **Skill文件创建** - 添加 `.trae/skills/a-stock-advisor/SKILL.md` 适配所有功能 |
| | | - ✅ **Skill文件创建** - 添加 `openclaw-skill/a-stock-advisor/SKILL.md` 适配 OpenClaw |
| | | - ✅ **功能统计** - 主入口包含 50+ 子功能,覆盖量化投资全流程 |
| | | |
| | | **版本 v5.2:** |
| | |
| | | |
| | | ```bash |
| | | # 进入项目目录 |
| | | cd /Users/variya/.openclaw/workspace/projects/a-stock-advisor |
| | | cd /path/to/a-stock-advisor |
| | | |
| | | # 运行主入口(推荐方式) |
| | | python3 a_stock_manager.py |
| | |
| | | |
| | | #### 1. 数据工程 |
| | | |
| | | - **1. 数据更新** ⭐推荐 - 从AKShare/BaoStock获取真实数据,支持增量更新 |
| | | - **1. 数据更新** ⭐推荐 - 默认增量更新,支持显式全量重建、北交所补数和安全重置 |
| | | - **2. 数据质量检查** - 完整Pipeline检查+清洗+验证,自动修复数据问题 |
| | | - **3. 数据时效性检查** - 检查数据新鲜度,显示数据年龄和更新时间 |
| | | - **4. 多源数据获取** - 智兔数服/腾讯/新浪/AKShare多源切换 |
| | |
| | | 或直接运行: |
| | | |
| | | ```bash |
| | | python3 scripts/data_update_v2.py |
| | | # 默认:增量更新全部A股 |
| | | python3 scripts/update_stock_data.py |
| | | |
| | | # 明确要求时:全量重建 |
| | | python3 scripts/update_stock_data.py --full --n-stocks all --days 730 |
| | | |
| | | # 仅补充北交所历史行情 |
| | | python3 scripts/data_update_v2.py --bse-only --days 730 |
| | | |
| | | # 数据质量检查 |
| | | python3 scripts/fix_data_quality_v2.py |
| | | ``` |
| | | |
| | | 增量更新会读取本地最近完整交易日,保留重叠窗口,并按“股票代码 + 日期”替换去重。即使日期已经是最新,默认仍会刷新最近窗口,以覆盖并补齐上一次可能不完整的数据;只有显式添加 `--skip-if-current` 才会在日期相同时跳过网络请求。若正式数据文件不存在,则自动执行首次全量初始化。下载覆盖率低于90%时不会覆盖正式数据。 |
| | | |
| | | 安全重置数据: |
| | | |
| | | ```bash |
| | | python3 scripts/reset_stock_data.py |
| | | # 按提示输入 RESET |
| | | ``` |
| | | |
| | | 重置不会永久删除文件,而会移动到 `data/backups/stock_data_时间戳/`。下次运行默认更新时会自动执行全量初始化。 |
| | | |
| | | ### 3.1 OpenClaw Skill |
| | | |
| | | Skill 源文件位于: |
| | | |
| | | ```text |
| | | openclaw-skill/a-stock-advisor/SKILL.md |
| | | ``` |
| | | |
| | | 安装到 OpenClaw 工作区后,将其中的 `PROJECT_DIR` 改为本项目绝对路径,并重启 Gateway: |
| | | |
| | | ```bash |
| | | openclaw gateway restart |
| | | openclaw skills info a-stock-advisor |
| | | ``` |
| | | |
| | | 常用指令及对应行为: |
| | | |
| | | | 对 OpenClaw 说 | 执行方式 | |
| | | |---|---| |
| | | | 更新A股数据 | 默认增量更新 | |
| | | | 全量重建A股数据 | 全量重新下载历史行情 | |
| | | | 更新数据后运行每日选股 | 先增量更新,再计算增强因子并选股 | |
| | | | 重置股票数据 | 明确确认后,将正式数据移动到备份目录 | |
| | | |
| | | ### 4. 运行每日主控流程 |
| | | |
| | |
| | | python3 scripts/health_check.py |
| | | ``` |
| | | |
| | | 每日主控会先排除 ST、`*ST`、退市整理及最新成交额位于市场后20%的股票,候选和最终名单中的北交所股票目标占比不超过30%。动态权重会按因子 IC 方向实际参与最新截面排序;ML 报告仅使用按时间留出的样本外区间计算 IC/IR。风险过滤后无合格股票时输出空名单,不再回退到高风险候选。报告属于量化研究与模拟验证结果,不生成实盘交易指令。 |
| | | |
| | | *** |
| | | |
| | | ## 📁 目录结构 |
| | |
| | | ├── README.md # ✅ 项目说明 |
| | | ├── scripts/ # ✅ 核心脚本(20个) |
| | | │ ├── daily_master.py # ⭐ 完整主控流程(推荐) |
| | | │ ├── data_update_v2.py # 数据更新 |
| | | │ ├── update_stock_data.py # ⭐ 默认增量更新/显式全量重建入口 |
| | | │ ├── data_update_v2.py # 多数据源全量与专项更新引擎 |
| | | │ ├── reset_stock_data.py # 安全重置并备份正式数据 |
| | | │ ├── fix_data_quality_v2.py # 数据质量修复 |
| | | │ ├── is_trading_day.py # 交易日判断 |
| | | │ ├── unified_daily_push.py # 统一日报推送 |
| | |
| | | # 每日3:00 - 系统健康检查 |
| | | 0 3 * * * cd /path/to/a-stock-advisor && python3 scripts/health_check.py >> logs/health_check.log 2>&1 |
| | | |
| | | # 每日4:00 - 数据更新 |
| | | 0 4 * * * cd /path/to/a-stock-advisor && python3 scripts/data_update_v2.py >> logs/data_update.log 2>&1 |
| | | # 每日4:00 - 默认增量数据更新 |
| | | 0 4 * * * cd /path/to/a-stock-advisor && python3 scripts/update_stock_data.py >> logs/data_update.log 2>&1 |
| | | ``` |
| | | |
| | | ### 安装定时任务 |
| | |
| | | |
| | | ## 🌟 版本历史 |
| | | |
| | | ### v5.4 (2026-07-11) |
| | | |
| | | - ✅ 默认数据更新改为增量模式,并刷新最近窗口以补齐不完整行情 |
| | | - ✅ 新增显式全量重建入口和90%下载覆盖率写入门控 |
| | | - ✅ 新增备份式安全数据重置入口 |
| | | - ✅ OpenClaw Skill 更新为默认增量路由 |
| | | - ✅ 每日选股增加可交易池、流动性、北交所占比与回撤约束 |
| | | - ✅ ML 指标改为样本外评估,动态权重和因子风险暴露接入最终报告 |
| | | |
| | | ### v5.3 (2026-03-12) |
| | | |
| | | - ✅ **README完整功能文档** - 详细列出主入口所有菜单功能(6大模块+4个快捷入口) |
| | |
| | | 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': |
| | |
| | | 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(): |
| | | """获取真实数据""" |
| | |
| | | --- |
| | | name: a-stock-advisor |
| | | description: 操作本地 A 股量化项目,执行行情数据更新、北交所补数、数据质量检查、因子分析、每日选股、报告读取、日志诊断、回测和模拟交易。用户提到 A 股、股票同步、AKShare、BaoStock、腾讯行情、因子 IC/IR、选股结果、每日主控、回测、模拟盘或量化报告时使用。不得执行真实券商委托或资金操作。 |
| | | metadata: {"version":"2026.7.10.2"} |
| | | metadata: {"version":"2026.7.11.3"} |
| | | --- |
| | | |
| | | # A股量化助手 |
| | |
| | | |
| | | | 用户意图 | 必须执行 | |
| | | |---|---| |
| | | | “更新A股数据”“同步股票数据”“获取最新行情” | `{PYTHON} scripts/data_update_v2.py --n-stocks all --days 730` | |
| | | | “快速更新500只” | `{PYTHON} scripts/data_update_v2.py --n-stocks 500 --days 730` | |
| | | | “更新A股数据”“同步股票数据”“获取最新行情” | `{PYTHON} scripts/update_stock_data.py` | |
| | | | “全量更新”“全量重建数据” | `{PYTHON} scripts/update_stock_data.py --full --n-stocks all --days 730` | |
| | | | “快速更新500只” | `{PYTHON} scripts/update_stock_data.py --n-stocks 500 --force` | |
| | | | “只更新北交所” | `{PYTHON} scripts/data_update_v2.py --bse-only --days 730` | |
| | | | “运行每日选股” | `{PYTHON} scripts/daily_master.py` | |
| | | | “更新数据后运行每日选股” | 先执行全量 `data_update_v2.py`,成功后再执行不带参数的 `daily_master.py` | |
| | | | “更新数据后运行每日选股” | 先执行增量 `update_stock_data.py`,成功后再执行不带参数的 `daily_master.py` | |
| | | | “重置/清空股票数据” | 先向用户解释将自动备份并要求明确确认;确认后执行 `{PYTHON} scripts/reset_stock_data.py --yes` | |
| | | |
| | | 处理数据更新请求时禁止调用: |
| | | |
| | |
| | | - `a_stock_manager.py` 的交互菜单 |
| | | - 直接调用 AKShare、BaoStock 或腾讯接口的临时代码 |
| | | |
| | | `scripts/data_update_v2.py` 是唯一的数据更新入口。它内部使用经过项目优化的多数据源流程:AKShare 获取股票列表和首选行情,连续失败后自动切换 BaoStock 获取沪深历史行情,并使用腾讯行情补充北交所及新旧代码映射。 |
| | | `scripts/update_stock_data.py` 是默认数据更新入口:存在正式数据时执行增量合并,不存在时自动执行全量初始化。`scripts/data_update_v2.py` 是底层全量和专项修复引擎。两者都复用经过项目优化的多数据源流程:AKShare 获取股票列表和首选行情,失败或覆盖不足时自动切换 BaoStock 获取沪深历史行情,并使用腾讯行情补充北交所及新旧代码映射。 |
| | | |
| | | 执行前必须向用户显示即将运行的完整命令。若实际命令不包含 `scripts/data_update_v2.py`,立即停止并纠正路由。 |
| | | 执行前必须向用户显示即将运行的完整命令。普通更新若实际命令不是 `scripts/update_stock_data.py`,立即停止并纠正路由。 |
| | | |
| | | ## 工作原则 |
| | | |
| | |
| | | |
| | | 向用户报告:创建时间、行情日期范围、股票数、记录数、数据源、最近一次任务是否完成。不要直接打印整个 pickle 文件。 |
| | | |
| | | ### 更新股票行情 |
| | | ### 增量更新股票行情 |
| | | |
| | | 用户只说“更新A股数据”而没有指定数量时,默认更新全部 A 股,直接运行: |
| | | 用户只说“更新A股数据”而没有指定数量时,默认更新全部 A 股的增量行情,直接运行: |
| | | |
| | | ```text |
| | | {PYTHON} scripts/data_update_v2.py --n-stocks all --days 730 |
| | | {PYTHON} scripts/update_stock_data.py |
| | | ``` |
| | | |
| | | 用户指定股票数量或历史天数时,将 `all` 和 `730` 替换为用户给定值。小范围连通性测试使用: |
| | | 增量模式会读取本地最近完整交易日,保留重叠窗口,并按 `股票代码 + 日期` 替换去重。即使日期已经是最新,默认仍会刷新并覆盖最近窗口,以补齐上一次可能缺失的数据。只有用户明确要求“数据已最新就跳过”时才添加 `--skip-if-current`。若正式数据文件不存在,会自动执行首次全量初始化。 |
| | | |
| | | 用户指定股票数量时使用 `--n-stocks`。小范围连通性测试使用: |
| | | |
| | | ```text |
| | | {PYTHON} scripts/data_update_v2.py --n-stocks 10 --days 30 |
| | | {PYTHON} scripts/update_stock_data.py --n-stocks 10 --force |
| | | ``` |
| | | |
| | | 注意:小范围测试会写入正式数据文件。除非用户明确允许,不要用小范围测试替换已经存在的全量数据。 |
| | | 增量小范围测试只合并相应股票,不会把其他股票从正式文件删除。 |
| | | |
| | | 用户明确要求全量重建时才运行: |
| | | |
| | | ```text |
| | | {PYTHON} scripts/update_stock_data.py --full --n-stocks all --days 730 |
| | | ``` |
| | | |
| | | 运行期间通过 `logs/data_update_v3.log` 判断进度。只有当日志超过 5 分钟没有新增、进程也没有网络或 CPU 活动时,才提示可能停滞。 |
| | | |
| | |
| | | |
| | | 正确流程的日志必须依次包含以下关键标记: |
| | | |
| | | 1. `数据更新任务开始 - 使用真实数据源` |
| | | 2. `更新范围: 全部A股`,或用户明确指定的数量 |
| | | 3. `获取A股股票列表` |
| | | 1. `数据更新任务开始 - 默认增量模式` |
| | | 2. `本地完整交易日`、`预期最新交易日` 和 `本地最新日覆盖` |
| | | 3. 即使日期已最新,默认仍出现“刷新并覆盖最近行情窗口”,随后继续获取股票列表 |
| | | 4. AKShare 成功,或者出现切换备用数据源的说明 |
| | | 5. BaoStock 沪深历史行情进度(发生降级时) |
| | | 6. 腾讯北交所历史行情进度(切换备用源且存在北交所股票时) |
| | | 7. `数据更新任务完成` |
| | | 7. `增量数据更新完成` |
| | | |
| | | 如果日志出现 `执行完整数据管道` 或只显示固定 `500` 只,而用户没有要求快速更新,说明走错入口;停止该任务并改用上面的强制命令。 |
| | | 如果普通更新日志出现 `更新模式: 全量重建`,但用户没有明确要求全量,说明走错入口;停止该任务并改用默认增量命令。 |
| | | |
| | | ### 仅补充北交所行情 |
| | | |
| | |
| | | {PYTHON} scripts/daily_master.py |
| | | ``` |
| | | |
| | | 用户要求“更新数据后选股”时,不使用 `--run-pipeline`。先运行优化后的 `data_update_v2.py --n-stocks all --days 730`,确认成功后再运行不带参数的 `daily_master.py`。 |
| | | 用户要求“更新数据后选股”时,不使用 `--run-pipeline`。先运行默认增量入口 `update_stock_data.py`,确认成功后再运行不带参数的 `daily_master.py`。 |
| | | |
| | | 每日选股完成后必须核对日志中的 `增强因子`、`ML二次排序`、`动态权重` 和 `因子风险` 四项状态。主结果读取 `data/selection_result.json` 的 `selected_stocks`;`candidate_stocks` 仅用于诊断,不能当作最终推荐。系统会在打分前排除 ST、退市整理和低流动性股票,并限制北交所候选占比;风险过滤后为空时应如实报告“无合格候选”,不得回退或自行补入原始候选。 |
| | | |
| | | 报告中的 ML IC/IR 仅按样本外口径解释。`ML二次排序: 未应用(独立二次排序模型尚未训练)` 不代表增强因子内部的生产模型未训练。所有报告均为量化研究与模拟验证,不得转述为实盘交易指令。 |
| | | |
| | | ### 安全重置数据 |
| | | |
| | | 只有用户明确要求重置或清空数据时才允许执行。先说明行情、增强因子和选股结果会从正式位置移走,并要求用户明确确认。确认后运行: |
| | | |
| | | ```text |
| | | {PYTHON} scripts/reset_stock_data.py --yes |
| | | ``` |
| | | |
| | | 该命令不会永久删除文件,而会移动到 `data/backups/stock_data_时间戳/`。完成后,下一次普通更新会自动执行全量初始化。不得自行删除备份目录。 |
| | | |
| | | 完成后读取并总结: |
| | | |
| | |
| | | import logging |
| | | import json |
| | | import pickle |
| | | from pathlib import Path |
| | | import pandas as pd |
| | | import numpy as np |
| | | from typing import Dict, List, Tuple, Optional |
| | |
| | | except ImportError: |
| | | FACTOR_RISK_AVAILABLE = False |
| | | |
| | | PROJECT_ROOT = Path(__file__).resolve().parents[1] |
| | | LOG_DIR = PROJECT_ROOT / 'logs' |
| | | LOG_DIR.mkdir(parents=True, exist_ok=True) |
| | | |
| | | |
| | | def _configure_console_encoding() -> None: |
| | | """Keep Windows GBK consoles from aborting on symbols or emoji.""" |
| | | 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() |
| | | |
| | | logging.basicConfig( |
| | | level=logging.INFO, |
| | | format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', |
| | | handlers=[ |
| | | logging.FileHandler('logs/daily_master.log'), |
| | | logging.FileHandler(LOG_DIR / 'daily_master.log', encoding='utf-8'), |
| | | logging.StreamHandler() |
| | | ] |
| | | ) |
| | | logger = logging.getLogger(__name__) |
| | | |
| | | |
| | | DEFAULT_MIN_LIQUIDITY_QUANTILE = 0.20 |
| | | DEFAULT_MAX_BSE_RATIO = 0.30 |
| | | DEFAULT_CANDIDATE_COUNT = 20 |
| | | DEFAULT_FINAL_SELECTION_COUNT = 10 |
| | | DEFAULT_MAX_DRAWDOWN_PCT = -40.0 |
| | | |
| | | |
| | | def infer_stock_market(stock_code: str) -> str: |
| | | """Classify normalized A-share codes into a broad listing market.""" |
| | | code = ''.join(ch for ch in str(stock_code) if ch.isdigit()).zfill(6) |
| | | if code.startswith(('4', '8', '92')): |
| | | return '北交所' |
| | | if code.startswith('6'): |
| | | return '上交所' |
| | | return '深交所' |
| | | |
| | | |
| | | def filter_tradable_universe( |
| | | df: pd.DataFrame, |
| | | min_liquidity_quantile: float = DEFAULT_MIN_LIQUIDITY_QUANTILE, |
| | | ) -> Tuple[pd.DataFrame, Dict]: |
| | | """Remove special-treatment, delisting and illiquid rows before ranking.""" |
| | | working = df.copy() |
| | | metadata = { |
| | | 'universe_before_filters': int(len(working)), |
| | | 'excluded_special_treatment': 0, |
| | | 'excluded_invalid_price': 0, |
| | | 'excluded_low_liquidity': 0, |
| | | 'liquidity_amount_threshold': None, |
| | | } |
| | | |
| | | if 'stock_name' in working.columns: |
| | | names = working['stock_name'].fillna('').astype(str) |
| | | elif '股票名称' in working.columns: |
| | | names = working['股票名称'].fillna('').astype(str) |
| | | else: |
| | | names = pd.Series('', index=working.index, dtype='object') |
| | | upper_names = names.str.upper() |
| | | special_treatment = upper_names.str.contains('ST', regex=False) | names.str.contains( |
| | | '退', regex=False |
| | | ) |
| | | metadata['excluded_special_treatment'] = int(special_treatment.sum()) |
| | | |
| | | invalid_price = pd.Series(False, index=working.index) |
| | | if 'close' in working.columns: |
| | | prices = pd.to_numeric(working['close'], errors='coerce') |
| | | invalid_price = prices.isna() | (prices <= 0) |
| | | metadata['excluded_invalid_price'] = int(invalid_price.sum()) |
| | | |
| | | low_liquidity = pd.Series(False, index=working.index) |
| | | if 'amount' in working.columns: |
| | | amounts = pd.to_numeric(working['amount'], errors='coerce') |
| | | positive_amounts = amounts[amounts > 0] |
| | | if len(positive_amounts) >= 20: |
| | | threshold = float(positive_amounts.quantile(min_liquidity_quantile)) |
| | | low_liquidity = amounts.isna() | (amounts < threshold) |
| | | metadata['liquidity_amount_threshold'] = threshold |
| | | else: |
| | | low_liquidity = amounts.isna() | (amounts <= 0) |
| | | metadata['excluded_low_liquidity'] = int(low_liquidity.sum()) |
| | | |
| | | excluded = special_treatment | invalid_price | low_liquidity |
| | | working = working.loc[~excluded].copy() |
| | | working['market'] = working['stock_code'].map(infer_stock_market) |
| | | metadata['universe_after_filters'] = int(len(working)) |
| | | metadata['excluded_total'] = int(excluded.sum()) |
| | | return working, metadata |
| | | |
| | | |
| | | def calculate_dynamic_cross_section_score( |
| | | df: pd.DataFrame, |
| | | weights: Dict[str, float], |
| | | evaluation: Dict[str, Dict], |
| | | ) -> Tuple[pd.Series, List[str]]: |
| | | """Calculate an IC-directed percentile score for one market cross-section.""" |
| | | usable = [ |
| | | factor |
| | | for factor, weight in weights.items() |
| | | if factor in df.columns and float(weight) > 0 |
| | | ] |
| | | if not usable: |
| | | return pd.Series(np.nan, index=df.index, dtype=float), [] |
| | | |
| | | normalized_weights = { |
| | | factor: float(weights[factor]) |
| | | for factor in usable |
| | | } |
| | | total_weight = sum(normalized_weights.values()) |
| | | if total_weight <= 0: |
| | | return pd.Series(np.nan, index=df.index, dtype=float), [] |
| | | normalized_weights = { |
| | | factor: weight / total_weight |
| | | for factor, weight in normalized_weights.items() |
| | | } |
| | | |
| | | score = pd.Series(0.0, index=df.index, dtype=float) |
| | | applied = [] |
| | | for factor, weight in normalized_weights.items(): |
| | | values = pd.to_numeric(df[factor], errors='coerce') |
| | | if values.notna().sum() < 2: |
| | | continue |
| | | factor_score = values.rank(pct=True, method='average') |
| | | if evaluation.get(factor, {}).get('ic_mean', 0) < 0: |
| | | factor_score = 1.0 - factor_score |
| | | score += factor_score.fillna(0.5) * weight |
| | | applied.append(factor) |
| | | |
| | | if not applied: |
| | | return pd.Series(np.nan, index=df.index, dtype=float), [] |
| | | score_min = score.min() |
| | | score_max = score.max() |
| | | if score_max > score_min: |
| | | score = (score - score_min) / (score_max - score_min) |
| | | else: |
| | | score[:] = 0.5 |
| | | return score, applied |
| | | |
| | | |
| | | def select_market_balanced_rows( |
| | | df: pd.DataFrame, |
| | | score_col: str, |
| | | limit: int, |
| | | max_bse_ratio: float = DEFAULT_MAX_BSE_RATIO, |
| | | ) -> pd.DataFrame: |
| | | """Select ranked rows while enforcing the BSE cap on every prefix.""" |
| | | if df is None or len(df) == 0 or limit <= 0: |
| | | return pd.DataFrame(columns=df.columns if df is not None else None) |
| | | |
| | | ranked = df.sort_values(score_col, ascending=False, kind='mergesort').copy() |
| | | if 'market' not in ranked.columns: |
| | | ranked['market'] = ranked['stock_code'].map(infer_stock_market) |
| | | |
| | | remaining = list(ranked.index) |
| | | selected_indices = [] |
| | | bse_count = 0 |
| | | while remaining and len(selected_indices) < limit: |
| | | slot = len(selected_indices) + 1 |
| | | max_bse_for_prefix = int(np.ceil(slot * max_bse_ratio)) |
| | | chosen_position = None |
| | | for position, index in enumerate(remaining): |
| | | is_bse = ranked.at[index, 'market'] == '北交所' |
| | | if not is_bse or bse_count < max_bse_for_prefix: |
| | | chosen_position = position |
| | | break |
| | | if chosen_position is None: |
| | | break |
| | | index = remaining.pop(chosen_position) |
| | | selected_indices.append(index) |
| | | if ranked.at[index, 'market'] == '北交所': |
| | | bse_count += 1 |
| | | |
| | | return ranked.loc[selected_indices].copy() |
| | | |
| | | |
| | | def select_latest_complete_cross_section( |
| | |
| | | advanced_factors = [ |
| | | 'rel_momentum', 'rel_industry_momentum', 'industry_rank', 'market_rank', |
| | | 'industry_strength', 'vol_change', 'vol_ma_ratio', 'vol_price_trend', |
| | | 'downside_vol', 'reversal_5', 'reversal_10', 'price_position', |
| | | 'ml_score', 'final_score' |
| | | 'downside_vol', 'reversal_5', 'reversal_10', 'price_position' |
| | | ] |
| | | |
| | | # 增强因子(来自enhanced_factor_system v4.0) |
| | |
| | | |
| | | def update_dynamic_weights(self, evaluation: Dict): |
| | | """基于评估结果更新动态权重""" |
| | | total_ic = sum(abs(f['ic_mean']) for f in evaluation.values() if f['effective']) |
| | | |
| | | weights = {} |
| | | if total_ic > 0: |
| | | for factor, result in evaluation.items(): |
| | | if result['effective']: |
| | | weights[factor] = abs(result['ic_mean']) / total_ic |
| | | else: |
| | | weights[factor] = 0.01 |
| | | else: |
| | | n = len(evaluation) |
| | | if n > 0: |
| | | equal_weight = 1.0 / n |
| | | weights = {f: equal_weight for f in evaluation.keys()} |
| | | effective = { |
| | | factor: abs(result['ic_mean']) |
| | | for factor, result in evaluation.items() |
| | | if result.get('effective') and abs(result.get('ic_mean', 0)) > 0 |
| | | } |
| | | if not effective: |
| | | effective = { |
| | | factor: abs(result.get('ic_mean', 0)) |
| | | for factor, result in evaluation.items() |
| | | if abs(result.get('ic_mean', 0)) > 0 |
| | | } |
| | | |
| | | total_ic = sum(effective.values()) |
| | | weights = ( |
| | | {factor: value / total_ic for factor, value in effective.items()} |
| | | if total_ic > 0 |
| | | else {} |
| | | ) |
| | | |
| | | with open(self.factor_weights_file, 'w', encoding='utf-8') as f: |
| | | json.dump({ |
| | |
| | | dynamic_weights: Dict, |
| | | portfolio: Dict, |
| | | backtest_results: Dict, |
| | | risk_signals: List[Dict]) -> str: |
| | | risk_signals: List[Dict], |
| | | factor_risk_analysis: Optional[Dict] = None) -> str: |
| | | """生成完整报告""" |
| | | now = datetime.now() |
| | | |
| | |
| | | lines.append('🦞 A股量化日报 - 盘前推送(增强版)') |
| | | lines.append('━━━━━━━━━━━━━━━━━━━━━━━━') |
| | | lines.append(f'📅 推送时间: {now.strftime("%Y-%m-%d %H:%M")}') |
| | | lines.append(f'📌 类型: 实盘推送(含因子评估、风险控制)') |
| | | lines.append('📌 类型: 量化研究候选(非交易指令)') |
| | | lines.append('') |
| | | |
| | | lines.append('📊 因子有效性评估') |
| | |
| | | for factor, result in sorted(factor_evaluation.items(), |
| | | key=lambda x: abs(x[1]['ic_mean']), reverse=True)[:6]: |
| | | status = '✅' if result['effective'] else '⚠️' |
| | | lines.append(f'{status} {factor}: IC={result["ic_mean"]:.3f}, IR={result["ir"]:.2f}') |
| | | label = ( |
| | | f'{factor}(样本外)' |
| | | if factor == 'ml_score_return_5d' |
| | | else factor |
| | | ) |
| | | lines.append(f'{status} {label}: IC={result["ic_mean"]:.3f}, IR={result["ir"]:.2f}') |
| | | else: |
| | | lines.append('暂无因子评估数据') |
| | | lines.append('') |
| | | |
| | | lines.append('⚖️ 动态因子权重') |
| | | lines.append('⚖️ 已应用动态因子权重') |
| | | lines.append('────────────────────') |
| | | if dynamic_weights: |
| | | for factor, weight in sorted(dynamic_weights.items(), key=lambda x: -x[1]): |
| | | lines.append(f' • {factor}: {weight*100:.1f}%') |
| | | else: |
| | | lines.append('使用默认等权') |
| | | lines.append('本次未应用动态权重') |
| | | lines.append('') |
| | | |
| | | lines.append('🎯 今日推荐') |
| | | lines.append('🎯 今日研究候选') |
| | | lines.append('────────────────────') |
| | | |
| | | stock_name_map = {} |
| | |
| | | except: |
| | | pass |
| | | |
| | | if not selected_stocks: |
| | | lines.append('今日无满足交易池与风险约束的候选股票') |
| | | |
| | | for i, stock in enumerate(selected_stocks[:10], 1): |
| | | code = stock.get('stock_code', stock.get('code', 'N/A')) |
| | | name = stock.get('stock_name', stock.get('name', 'N/A')) |
| | |
| | | code_num = code.replace('sh', '').replace('sz', '').replace('bj', '') |
| | | name = stock_name_map.get(code_num, name) |
| | | |
| | | price = self._get_stock_price(code) |
| | | try: |
| | | price = float(stock.get('price', 0) or 0) |
| | | except (TypeError, ValueError): |
| | | price = 0.0 |
| | | if price <= 0: |
| | | price = self._get_stock_price(code) |
| | | price_str = f'¥{price:.2f}' if price > 0 else '价格未知' |
| | | |
| | | lines.append(f'{i}. {name}({code}) - α得分: {score:.2f} | {price_str}') |
| | | market = stock.get('market', infer_stock_market(code)) |
| | | lines.append(f'{i}. {name}({code}) [{market}] - 综合得分: {score:.2f} | {price_str}') |
| | | backtest = backtest_results.get(str(code), {}) |
| | | if backtest: |
| | | lines.append(f' 📈 回测: 收益{backtest.get("total_return_pct", 0):.1f}% | ' |
| | | lines.append(f' 📈 近60日观察: 收益{backtest.get("total_return_pct", 0):.1f}% | ' |
| | | f'夏普{backtest.get("sharpe_ratio", 0):.2f} | ' |
| | | f'回撤{backtest.get("max_drawdown_pct", 0):.1f}% | ' |
| | | f'胜率{backtest.get("win_rate_pct", 0):.0f}%') |
| | | lines.append('') |
| | | |
| | | lines.append('🛡️ 因子风险暴露') |
| | | lines.append('────────────────────') |
| | | factor_risk_analysis = factor_risk_analysis or {} |
| | | exposures = factor_risk_analysis.get('portfolio_exposure', {}) |
| | | if factor_risk_analysis.get('status') == 'ok' and exposures: |
| | | for factor, exposure in sorted( |
| | | exposures.items(), key=lambda item: abs(item[1]), reverse=True |
| | | )[:5]: |
| | | lines.append(f' • {factor}: {exposure:+.2f}σ') |
| | | alerts = factor_risk_analysis.get('exposure_alerts', []) |
| | | lines.append(f'暴露预警: {len(alerts)}项' if alerts else '未触发暴露预警') |
| | | else: |
| | | lines.append(f'未形成有效风险暴露分析({factor_risk_analysis.get("status", "无数据")})') |
| | | lines.append('') |
| | | |
| | | lines.append('💼 当前持仓') |
| | |
| | | f'{pnl_text} | ' |
| | | f'¥{pos["current_value"]:,.0f}') |
| | | else: |
| | | lines.append('当前无持仓,建议按今日推荐建仓') |
| | | lines.append('当前无模拟持仓') |
| | | lines.append('') |
| | | |
| | | if risk_signals: |
| | |
| | | lines.append(f'{emoji} {signal["stock_name"]}({signal["stock_code"]}): {signal["reason"]}') |
| | | lines.append('') |
| | | |
| | | lines.append('📢 今日交易指令') |
| | | lines.append('📢 模拟组合调整提示') |
| | | lines.append('────────────────────') |
| | | lines.append('【卖出指令】') |
| | | lines.append('【模拟卖出提示】') |
| | | sell_amount = 0 |
| | | for signal in risk_signals: |
| | | if signal['type'] == 'stop_loss': |
| | |
| | | lines.append(f'操作后现金: ¥{cash_after:,.0f}') |
| | | lines.append('') |
| | | |
| | | lines.append('【买入指令】') |
| | | lines.append('【模拟买入观察】') |
| | | if selected_stocks: |
| | | industries = {} |
| | | for i, stock in enumerate(selected_stocks[:5], 1): |
| | |
| | | code_num = code.replace('sh', '').replace('sz', '').replace('bj', '') |
| | | name = stock_name_map.get(code_num, name) |
| | | |
| | | price = self._get_stock_price(code) |
| | | try: |
| | | price = float(stock.get('price', 0) or 0) |
| | | except (TypeError, ValueError): |
| | | price = 0.0 |
| | | if price <= 0: |
| | | price = self._get_stock_price(code) |
| | | alloc_amount = cash_after * 0.12 |
| | | |
| | | if price > 0: |
| | |
| | | lines.append('• 关注市场变化') |
| | | lines.append('') |
| | | else: |
| | | lines.append('📢 今日操作建议') |
| | | lines.append('📢 今日研究结论') |
| | | lines.append('────────────────────') |
| | | lines.append('• 当前无持仓,建议按今日推荐建仓') |
| | | lines.append('• 分批买入,每只股票10-12%仓位') |
| | | lines.append('• 保留25%现金应对加仓机会') |
| | | lines.append('• 当前无模拟持仓,本报告仅保留候选观察') |
| | | lines.append('• 未经过完整走样回测和交易成本验证,不生成实盘指令') |
| | | lines.append('') |
| | | |
| | | lines.append('━━━━━━━━━━━━━━━━━━━━━━') |
| | | lines.append('📊 数据来源: AKShare + 动态因子模型') |
| | | lines.append('📊 数据来源: AKShare/BaoStock/腾讯行情 + 动态因子模型') |
| | | lines.append('⚠️ 仅供量化研究与模拟验证,不构成投资建议') |
| | | lines.append(f'🦞 A股量化系统 v3.1 | {now.strftime("%Y-%m-%d")}') |
| | | |
| | | return '\n'.join(lines) |
| | |
| | | logger.warning("⚠️ ML因子组合器不可用") |
| | | self.ml_optimization_applied = False |
| | | self.ml_optimization_status = ( |
| | | '未应用(模型尚未训练)' |
| | | '未应用(独立二次排序模型尚未训练)' |
| | | if self.ml_combiner is not None |
| | | else '未应用(组件不可用)' |
| | | ) |
| | | self.enhanced_factor_status = '未运行' |
| | | self.enhanced_ml_metrics = {} |
| | | self.dynamic_weight_status = '未应用' |
| | | self.latest_selection_metadata = {} |
| | | |
| | | if DYNAMIC_WEIGHT_AVAILABLE: |
| | | self.dynamic_weight_system = DynamicFactorWeightSystem() |
| | |
| | | logger.error(f"❌ 数据管道执行失败: {e}") |
| | | return None |
| | | |
| | | def _run_advanced_factor_system(self, df: pd.DataFrame) -> pd.DataFrame: |
| | | def _run_advanced_factor_system(self, df: pd.DataFrame) -> Optional[pd.DataFrame]: |
| | | """运行增强因子系统""" |
| | | try: |
| | | from scripts.enhanced_factor_system import EnhancedFactorSystem |
| | |
| | | pickle.dump(df, f) |
| | | |
| | | effective_count = sum(1 for r in results.values() if r.get('effective', False)) |
| | | self.enhanced_factor_status = '已完成' |
| | | self.enhanced_ml_metrics = ml_metrics |
| | | logger.info(f"✓ 增强因子系统执行完成,有效因子: {effective_count}/{len(results)}") |
| | | |
| | | if ml_metrics: |
| | | logger.info(f" ML模型IR: {ml_metrics.get('ir', 0):.2f}") |
| | | logger.info(f" ML样本外IR: {ml_metrics.get('ir', 0):.2f}") |
| | | |
| | | return df |
| | | |
| | | except ImportError: |
| | | logger.warning("⚠️ 增强因子系统模块不可用") |
| | | return df |
| | | except ImportError as e: |
| | | self.enhanced_factor_status = f'失败(模块不可用: {e})' |
| | | logger.error(f"❌ 增强因子系统模块不可用: {e}") |
| | | return None |
| | | except Exception as e: |
| | | logger.error(f"❌ 增强因子系统执行失败: {e}") |
| | | return df |
| | | self.enhanced_factor_status = f'失败({e})' |
| | | logger.error(f"❌ 增强因子系统执行失败: {e}", exc_info=True) |
| | | return None |
| | | |
| | | def load_data(self) -> pd.DataFrame: |
| | | """加载数据""" |
| | |
| | | logger.info(f"✓ 因子评估完成,有效因子{sum(1 for f in evaluation.values() if f['effective'])}个") |
| | | return evaluation, dynamic_weights |
| | | |
| | | def select_stocks(self, df: pd.DataFrame) -> List[Dict]: |
| | | """差异化选股""" |
| | | def select_stocks( |
| | | self, |
| | | df: pd.DataFrame, |
| | | dynamic_weights: Optional[Dict[str, float]] = None, |
| | | factor_evaluation: Optional[Dict[str, Dict]] = None, |
| | | ) -> List[Dict]: |
| | | """Build a tradable, liquid and market-balanced candidate pool.""" |
| | | logger.info("🎯 执行差异化选股...") |
| | | |
| | | if len(df) == 0: |
| | | return [] |
| | | |
| | | # 数据源收盘时间可能不同,使用最近一个覆盖完整市场的交易日。 |
| | | |
| | | selection_metadata = {} |
| | | if {'date', 'stock_code'}.issubset(df.columns): |
| | | df, selection_metadata = select_latest_complete_cross_section(df) |
| | |
| | | logger.warning( |
| | | f"⚠️ 最新日期{latest_observed_date}仅有" |
| | | f"{selection_metadata.get('latest_observed_stocks', 0)}只股票," |
| | | f"低于完整截面要求" |
| | | f"{selection_metadata.get('minimum_required_stocks', 0)}只;" |
| | | f"已回退到{selection_date}" |
| | | f"已回退到完整截面{selection_date}" |
| | | ) |
| | | excluded = selection_metadata.get('excluded_short_history_stocks', 0) |
| | | if excluded: |
| | | logger.info(f"已排除历史不足60个交易日的股票: {excluded}只") |
| | | |
| | | # 如果最新日期数据按股票分组后有多条记录,取最新一条 |
| | | |
| | | if 'stock_code' in df.columns: |
| | | df = df.groupby('stock_code').last().reset_index() |
| | | |
| | | logger.info(f"有{len(df)}只股票数据") |
| | | |
| | | # 检查是否有综合得分列(优先使用final_score) |
| | | |
| | | df, filter_metadata = filter_tradable_universe(df) |
| | | selection_metadata.update(filter_metadata) |
| | | logger.info( |
| | | f"可交易股票池: {len(df)}只;排除ST/退市" |
| | | f"{filter_metadata['excluded_special_treatment']}只," |
| | | f"低流动性{filter_metadata['excluded_low_liquidity']}只" |
| | | ) |
| | | if len(df) == 0: |
| | | logger.error("❌ 交易池过滤后无可选股票") |
| | | self.latest_selection_metadata = selection_metadata |
| | | return [] |
| | | |
| | | score_col = None |
| | | for col in ['final_score', 'alpha_score', 'score', '综合得分']: |
| | | if col in df.columns: |
| | | score_col = col |
| | | break |
| | | |
| | | # 如果没有得分列,使用amount作为排序依据 |
| | | dynamic_weights = dynamic_weights or {} |
| | | factor_evaluation = factor_evaluation or {} |
| | | if dynamic_weights and factor_evaluation: |
| | | dynamic_score, applied_factors = calculate_dynamic_cross_section_score( |
| | | df, |
| | | dynamic_weights, |
| | | factor_evaluation, |
| | | ) |
| | | if applied_factors: |
| | | df['dynamic_score'] = dynamic_score |
| | | score_col = 'dynamic_score' |
| | | self.dynamic_weight_status = f'已应用({len(applied_factors)}个因子)' |
| | | selection_metadata['applied_dynamic_factors'] = applied_factors |
| | | logger.info(f"✓ 动态权重已参与排序: {len(applied_factors)}个因子") |
| | | |
| | | if score_col is None: |
| | | if 'amount' in df.columns: |
| | | df['temp_score'] = df['amount'] / df['amount'].max() if df['amount'].max() > 0 else 1.0 |
| | | for col in ['final_score', 'alpha_score', 'score', '综合得分']: |
| | | if col in df.columns: |
| | | score_col = col |
| | | break |
| | | if score_col is not None: |
| | | self.dynamic_weight_status = '未应用(使用静态综合得分)' |
| | | logger.warning(f"⚠️ 动态权重未应用,回退使用{score_col}") |
| | | elif 'amount' in df.columns: |
| | | max_amount = pd.to_numeric(df['amount'], errors='coerce').max() |
| | | df['temp_score'] = ( |
| | | pd.to_numeric(df['amount'], errors='coerce') / max_amount |
| | | if max_amount > 0 |
| | | else 1.0 |
| | | ) |
| | | score_col = 'temp_score' |
| | | logger.info("使用成交额作为排序依据") |
| | | self.dynamic_weight_status = '未应用(使用成交额)' |
| | | logger.warning("⚠️ 无综合得分,回退使用成交额排序") |
| | | else: |
| | | logger.error("❌ 无可用排序依据") |
| | | return [] |
| | | |
| | | if score_col == 'final_score': |
| | | logger.info("使用高级因子系统final_score作为排序依据") |
| | | |
| | | # 按股票分组去重,然后按得分排序选取前20只不同股票 |
| | | unique_stocks = df.drop_duplicates(subset=['stock_code']) |
| | | selected = unique_stocks.nlargest(20, score_col).copy() |
| | | |
| | | # 确保选出的股票不重复 |
| | | selected = selected.drop_duplicates(subset=['stock_code']) |
| | | |
| | | |
| | | selected = select_market_balanced_rows( |
| | | df.drop_duplicates(subset=['stock_code']), |
| | | score_col, |
| | | DEFAULT_CANDIDATE_COUNT, |
| | | ) |
| | | result = [] |
| | | for idx, (_, row) in enumerate(selected.iterrows()): |
| | | code = row.get('stock_code', '') |
| | | # 确保股票代码为字符串 |
| | | if not isinstance(code, str): |
| | | code = str(code) |
| | | |
| | | code = str(row.get('stock_code', '')).zfill(6) |
| | | try: |
| | | price = float(row.get('close', 0) or 0) |
| | | except (TypeError, ValueError): |
| | | price = 0.0 |
| | | result.append({ |
| | | 'rank': idx + 1, |
| | | 'stock_code': code, |
| | | 'stock_name': row.get('stock_name', row.get('股票名称', f'股票{idx+1}')), |
| | | 'score': round(float(row.get(score_col, 0)), 4), |
| | | 'industry': row.get('industry', row.get('行业', '未知')) |
| | | 'industry': row.get('industry', row.get('行业', '未知')), |
| | | 'market': row.get('market', infer_stock_market(code)), |
| | | 'price': round(price, 4) if np.isfinite(price) and price > 0 else 0.0, |
| | | }) |
| | | |
| | | # 去重结果 |
| | | seen_codes = set() |
| | | unique_result = [] |
| | | for item in result: |
| | | if item['stock_code'] not in seen_codes: |
| | | seen_codes.add(item['stock_code']) |
| | | unique_result.append(item) |
| | | |
| | | |
| | | bse_count = sum(stock['market'] == '北交所' for stock in result) |
| | | selection_metadata.update({ |
| | | 'score_method': score_col, |
| | | 'candidate_count': len(result), |
| | | 'candidate_bse_count': bse_count, |
| | | 'max_bse_ratio': DEFAULT_MAX_BSE_RATIO, |
| | | }) |
| | | self.latest_selection_metadata = selection_metadata |
| | | logger.info( |
| | | f"✓ 生成{len(result)}只候选,北交所{bse_count}只" |
| | | f"(上限{DEFAULT_MAX_BSE_RATIO:.0%})" |
| | | ) |
| | | return result |
| | | |
| | | def save_selection_result( |
| | | self, |
| | | selected_stocks: List[Dict], |
| | | candidate_stocks: Optional[List[Dict]] = None, |
| | | ) -> None: |
| | | """Persist final risk-approved selections as the primary result.""" |
| | | with open(self.selection_file, 'w', encoding='utf-8') as f: |
| | | json.dump({ |
| | | 'selected_stocks': unique_result, |
| | | 'selected_stocks': selected_stocks, |
| | | 'candidate_stocks': candidate_stocks or [], |
| | | 'timestamp': datetime.now().isoformat(), |
| | | 'selection_metadata': selection_metadata, |
| | | 'selection_metadata': self.latest_selection_metadata, |
| | | }, f, indent=2, ensure_ascii=False) |
| | | |
| | | logger.info(f"✓ 选股完成,选出{len(unique_result)}只股票") |
| | | return unique_result[:10] |
| | | |
| | | def optimize_with_ml(self, df: pd.DataFrame, selected_stocks: List[Dict]) -> List[Dict]: |
| | | """使用ML因子组合优化选股结果""" |
| | |
| | | return selected_stocks |
| | | |
| | | if not getattr(self.ml_combiner, 'is_fitted', False): |
| | | logger.warning("⚠️ ML模型尚未训练,跳过二次优化并保留final_score排序") |
| | | self.ml_optimization_status = '未应用(模型尚未训练)' |
| | | logger.warning("⚠️ 独立ML二次排序模型尚未训练,保留动态因子排序") |
| | | self.ml_optimization_status = '未应用(独立二次排序模型尚未训练)' |
| | | return selected_stocks |
| | | |
| | | logger.info("🤖 ML因子组合优化...") |
| | |
| | | """分析因子风险和暴露""" |
| | | if self.factor_risk_model is None: |
| | | logger.warning("⚠️ 因子风险模型不可用") |
| | | return {} |
| | | return {'status': 'unavailable'} |
| | | if not selected_stocks: |
| | | return {'status': 'no_selection'} |
| | | |
| | | logger.info("📊 分析因子风险暴露...") |
| | | |
| | | try: |
| | | selected_codes = [s['stock_code'] for s in selected_stocks] |
| | | |
| | | factor_cols = [col for col in df.columns if col in [ |
| | | 'pe_ratio', 'pb_ratio', 'roe', 'roa', 'debt_ratio', |
| | | 'current_ratio', 'gross_margin', 'net_margin', |
| | | 'revenue_growth', 'profit_growth', 'momentum_1m', |
| | | 'momentum_3m', 'volatility_20d', 'turnover_rate' |
| | | ]] |
| | | |
| | | if len(factor_cols) == 0: |
| | | selected_codes = [str(s['stock_code']).zfill(6) for s in selected_stocks] |
| | | factor_candidates = [ |
| | | 'momentum_20', 'momentum_60', 'volatility_20', |
| | | 'turnover_zscore', 'amount_zscore', 'amount_rank', |
| | | 'rel_strength_ma60', 'industry_strength', 'sharpe_proxy', |
| | | ] |
| | | factor_cols = [col for col in factor_candidates if col in df.columns] |
| | | if not factor_cols: |
| | | logger.warning("⚠️ 无可用因子数据") |
| | | return {} |
| | | |
| | | latest_df = df |
| | | return {'status': 'no_factors'} |
| | | |
| | | risk_columns = ['stock_code'] + factor_cols |
| | | if 'date' in df.columns: |
| | | latest_date = df['date'].max() |
| | | latest_df = df[df['date'] == latest_date] |
| | | |
| | | factor_data = latest_df[latest_df['stock_code'].isin(selected_codes)][factor_cols].fillna(0) |
| | | |
| | | if len(factor_data) == 0: |
| | | return {} |
| | | |
| | | portfolio_exposure = self.factor_risk_model.calculate_portfolio_exposure( |
| | | factor_data.values, |
| | | weights=None |
| | | normalized_dates = pd.to_datetime(df['date'], errors='coerce').dt.normalize() |
| | | selection_date = self.latest_selection_metadata.get('selection_date') |
| | | target_date = ( |
| | | pd.Timestamp(selection_date).normalize() |
| | | if selection_date |
| | | else normalized_dates.max() |
| | | ) |
| | | latest_df = df.loc[ |
| | | normalized_dates == target_date, |
| | | risk_columns, |
| | | ].copy() |
| | | else: |
| | | latest_df = df[risk_columns].copy() |
| | | |
| | | latest_df['stock_code'] = latest_df['stock_code'].astype(str).str.zfill(6) |
| | | latest_df = latest_df.drop_duplicates('stock_code').set_index('stock_code') |
| | | exposures = pd.DataFrame(index=latest_df.index) |
| | | for factor in factor_cols: |
| | | values = pd.to_numeric(latest_df[factor], errors='coerce') |
| | | std = values.std() |
| | | if pd.notna(std) and std > 0: |
| | | exposures[factor] = (values - values.mean()) / std |
| | | exposures = exposures.fillna(0.0) |
| | | |
| | | selected_codes = [code for code in selected_codes if code in exposures.index] |
| | | if not selected_codes or exposures.empty: |
| | | logger.warning("⚠️ 候选股票缺少风险暴露数据") |
| | | return {'status': 'no_exposure'} |
| | | |
| | | position_weight = 1.0 / len(selected_codes) |
| | | positions = {code: position_weight for code in selected_codes} |
| | | portfolio_exposure = self.factor_risk_model.calculate_portfolio_factor_exposure( |
| | | positions, |
| | | exposures, |
| | | ) |
| | | |
| | | exposure_alerts = self.factor_exposure_monitor.check_exposure( |
| | | portfolio_exposure |
| | | ) |
| | | |
| | | risk_attribution = self.factor_risk_model.risk_attribution( |
| | | factor_data.values, |
| | | weights=None |
| | | ) |
| | | |
| | | total_abs_exposure = float(portfolio_exposure.abs().sum()) |
| | | risk_attribution = { |
| | | factor: ( |
| | | abs(float(value)) / total_abs_exposure |
| | | if total_abs_exposure > 0 |
| | | else 0.0 |
| | | ) |
| | | for factor, value in portfolio_exposure.items() |
| | | } |
| | | result = { |
| | | 'portfolio_exposure': portfolio_exposure, |
| | | 'status': 'ok', |
| | | 'portfolio_exposure': { |
| | | factor: round(float(value), 4) |
| | | for factor, value in portfolio_exposure.items() |
| | | }, |
| | | 'exposure_alerts': exposure_alerts, |
| | | 'risk_attribution': risk_attribution, |
| | | 'factor_names': factor_cols |
| | | 'factor_names': list(exposures.columns), |
| | | } |
| | | |
| | | if exposure_alerts: |
| | |
| | | return result |
| | | |
| | | except Exception as e: |
| | | logger.error(f"❌ 因子风险分析失败: {e}") |
| | | return {} |
| | | logger.error(f"❌ 因子风险分析失败: {e}", exc_info=True) |
| | | return {'status': 'error', 'error': str(e)} |
| | | |
| | | def validate_stocks(self, df: pd.DataFrame, selected_stocks: List[Dict]) -> Tuple[Dict, List[Dict]]: |
| | | """回实验证选中的股票""" |
| | | logger.info("📊 回实验证选中股票...") |
| | | """Apply a recent-history risk screen to candidate stocks.""" |
| | | logger.info("📊 检查候选股票近60日风险...") |
| | | validator = StockBacktestValidator(df) |
| | | |
| | | results = {} |
| | |
| | | code = str(stock['stock_code']) |
| | | results[code] = validator.quick_backtest(code) |
| | | |
| | | # 风险过滤:排除回撤>-50%的股票 |
| | | filtered_stocks = [] |
| | | for stock in selected_stocks: |
| | | code = str(stock['stock_code']) |
| | | backtest = results.get(code, {}) |
| | | max_drawdown = backtest.get('max_drawdown_pct', 0) |
| | | |
| | | # 只保留回撤<=50%的股票 |
| | | if max_drawdown >= -50: |
| | | is_reliable = backtest.get('is_reliable', False) |
| | | if is_reliable and max_drawdown >= DEFAULT_MAX_DRAWDOWN_PCT: |
| | | filtered_stocks.append(stock) |
| | | elif not is_reliable: |
| | | logger.warning(f"⚠️ 股票{code}历史数据不足,已排除") |
| | | else: |
| | | logger.warning(f"⚠️ 股票{code}回撤过大({max_drawdown:.1f}%),已排除") |
| | | |
| | |
| | | if len(filtered_stocks) < len(selected_stocks): |
| | | logger.warning(f"⚠️ 风险过滤后剩余{len(filtered_stocks)}只股票(原{len(selected_stocks)}只)") |
| | | |
| | | logger.info("✓ 回实验证完成") |
| | | logger.info("✓ 历史风险检查完成") |
| | | return results, filtered_stocks |
| | | |
| | | def update_portfolio(self, df: pd.DataFrame, selected_stocks: List[Dict]): |
| | |
| | | |
| | | portfolio = self.portfolio_tracker.state |
| | | if not portfolio['positions']: |
| | | logger.info("📝 无持仓,推送将提供建仓建议") |
| | | logger.info("📝 无模拟持仓,报告仅提供研究候选") |
| | | |
| | | logger.info("✓ 持仓更新完成") |
| | | return portfolio, risk_signals |
| | | |
| | | def generate_and_save_report(self, selected_stocks, factor_evaluation, |
| | | dynamic_weights, portfolio, backtest_results, risk_signals): |
| | | def generate_and_save_report( |
| | | self, |
| | | selected_stocks, |
| | | factor_evaluation, |
| | | dynamic_weights, |
| | | portfolio, |
| | | backtest_results, |
| | | risk_signals, |
| | | factor_risk_analysis=None, |
| | | ): |
| | | """生成并保存报告""" |
| | | logger.info("📝 生成报告...") |
| | | try: |
| | | report = self.report_generator.generate_full_report( |
| | | selected_stocks, factor_evaluation, dynamic_weights, |
| | | portfolio, backtest_results, risk_signals |
| | | portfolio, backtest_results, risk_signals, |
| | | factor_risk_analysis=factor_risk_analysis, |
| | | ) |
| | | |
| | | os.makedirs('reports', exist_ok=True) |
| | |
| | | |
| | | # 运行高级因子系统改进因子 |
| | | df = self._run_advanced_factor_system(df) |
| | | if df is None: |
| | | logger.error( |
| | | "❌ 增强因子计算未完成,已停止本次选股," |
| | | "避免沿用旧final_score生成报告" |
| | | ) |
| | | return False |
| | | |
| | | factor_evaluation, dynamic_weights = self.evaluate_factors(df) |
| | | |
| | |
| | | logger.warning(f" 平均IC: {avg_ic:.4f}") |
| | | logger.warning(" 建议:检查数据质量或调整因子参数") |
| | | |
| | | dynamic_factor_weights = self.apply_dynamic_weights(df) |
| | | if dynamic_factor_weights: |
| | | logger.info(f" 动态权重: {list(dynamic_factor_weights.items())[:3]}...") |
| | | |
| | | selected_stocks = self.select_stocks(df) |
| | | candidate_stocks = self.select_stocks( |
| | | df, |
| | | dynamic_weights=dynamic_weights, |
| | | factor_evaluation=factor_evaluation, |
| | | ) |
| | | |
| | | if effective_count == 0: |
| | | logger.warning("⚠️ 因子无效,选股结果仅供参考") |
| | | |
| | | selected_stocks = self.optimize_with_ml(df, selected_stocks) |
| | | |
| | | factor_risk_analysis = self.analyze_factor_risk(df, selected_stocks) |
| | | |
| | | backtest_results, filtered_stocks = self.validate_stocks(df, selected_stocks) |
| | | |
| | | if len(filtered_stocks) == 0: |
| | | logger.warning("⚠️ 风险过滤后无股票可选,使用原始选股结果") |
| | | filtered_stocks = selected_stocks |
| | | |
| | | portfolio, risk_signals = self.update_portfolio(df, filtered_stocks) |
| | | report, report_file = self.generate_and_save_report( |
| | | filtered_stocks, factor_evaluation, dynamic_weights, |
| | | portfolio, backtest_results, risk_signals |
| | | candidate_stocks = self.optimize_with_ml(df, candidate_stocks) |
| | | backtest_results, risk_approved = self.validate_stocks(df, candidate_stocks) |
| | | |
| | | if risk_approved: |
| | | approved_df = pd.DataFrame(risk_approved) |
| | | ranking_col = ( |
| | | 'combined_score' |
| | | if 'combined_score' in approved_df.columns |
| | | else 'score' |
| | | ) |
| | | final_df = select_market_balanced_rows( |
| | | approved_df, |
| | | ranking_col, |
| | | DEFAULT_FINAL_SELECTION_COUNT, |
| | | ) |
| | | selected_stocks = final_df.to_dict('records') |
| | | else: |
| | | logger.warning("⚠️ 风险过滤后无股票可选,本次输出空候选") |
| | | selected_stocks = [] |
| | | |
| | | for rank, stock in enumerate(selected_stocks, start=1): |
| | | stock['rank'] = rank |
| | | final_bse_count = sum( |
| | | stock.get('market') == '北交所' for stock in selected_stocks |
| | | ) |
| | | self.latest_selection_metadata.update({ |
| | | 'risk_approved_count': len(risk_approved), |
| | | 'final_selection_count': len(selected_stocks), |
| | | 'final_bse_count': final_bse_count, |
| | | }) |
| | | self.save_selection_result(selected_stocks, candidate_stocks) |
| | | |
| | | factor_risk_analysis = self.analyze_factor_risk(df, selected_stocks) |
| | | portfolio, risk_signals = self.update_portfolio(df, selected_stocks) |
| | | applied_factor_names = set( |
| | | self.latest_selection_metadata.get('applied_dynamic_factors', []) |
| | | ) |
| | | report_weights = { |
| | | factor: weight |
| | | for factor, weight in dynamic_weights.items() |
| | | if factor in applied_factor_names |
| | | } |
| | | report_weight_total = sum(report_weights.values()) |
| | | if report_weight_total > 0: |
| | | report_weights = { |
| | | factor: weight / report_weight_total |
| | | for factor, weight in report_weights.items() |
| | | } |
| | | report, report_file = self.generate_and_save_report( |
| | | selected_stocks, factor_evaluation, report_weights, |
| | | portfolio, backtest_results, risk_signals, |
| | | factor_risk_analysis=factor_risk_analysis, |
| | | ) |
| | | if report is None: |
| | | return False |
| | | |
| | | logger.info("\n" + "="*70) |
| | | logger.info("✅ 每日主控流程完成") |
| | | logger.info(f" - 选股数量: {len(filtered_stocks)}") |
| | | logger.info(f" - ML优化: {self.ml_optimization_status}") |
| | | logger.info(f" - 动态权重: {'已启用' if self.dynamic_weight_system else '未启用'}") |
| | | logger.info(f" - 选股数量: {len(selected_stocks)}") |
| | | logger.info(f" - 增强因子: {self.enhanced_factor_status}") |
| | | logger.info(f" - ML二次排序: {self.ml_optimization_status}") |
| | | logger.info(f" - 动态权重: {self.dynamic_weight_status}") |
| | | logger.info( |
| | | f" - 因子风险: {factor_risk_analysis.get('status', 'unknown')}" |
| | | ) |
| | | logger.info("="*70) |
| | | |
| | | return True |
| | |
| | | df['excess_ret_industry'] = df['change_pct'] - df['industry_ret'] |
| | | |
| | | # ===== 3. 行业轮动 ===== |
| | | # 行业动量 |
| | | industry_mom = df.groupby(['date', 'industry'])['momentum_20'].mean().reset_index() |
| | | industry_mom.columns = ['date', 'industry', 'ind_mom_val'] |
| | | df = df.merge(industry_mom, on=['date', 'industry'], how='left') |
| | | # 行业动量。直接覆盖派生列,确保保存后的数据可重复计算。 |
| | | df['ind_mom_val'] = df.groupby( |
| | | ['date', 'industry'] |
| | | )['momentum_20'].transform('mean') |
| | | |
| | | # 行业强度 |
| | | df['industry_strength'] = df['ind_mom_val'] - df['market_ret'] |
| | |
| | | |
| | | # 过滤有效特征 |
| | | feature_cols = [c for c in feature_cols if c in df.columns] |
| | | if not feature_cols: |
| | | print("⚠️ 无可用ML特征") |
| | | return None, df, {} |
| | | |
| | | # 准备训练数据 |
| | | df_train = df[feature_cols + [target, 'date', 'stock_code']].dropna(subset=[target]) |
| | |
| | | print(f" 训练数据: {len(X_train)} 条") |
| | | print(f" 测试数据: {len(X_test)} 条") |
| | | |
| | | # 训练模型 |
| | | model = HistGradientBoostingRegressor( |
| | | max_iter=200, |
| | | max_depth=4, |
| | | learning_rate=0.05, |
| | | random_state=42, |
| | | l2_regularization=0.1 |
| | | ) |
| | | |
| | | model.fit(X_train, y_train) |
| | | def build_model(): |
| | | return HistGradientBoostingRegressor( |
| | | max_iter=200, |
| | | max_depth=4, |
| | | learning_rate=0.05, |
| | | random_state=42, |
| | | l2_regularization=0.1 |
| | | ) |
| | | |
| | | # 留出模型只用于严格样本外评估。 |
| | | evaluation_model = build_model() |
| | | evaluation_model.fit(X_train, y_train) |
| | | |
| | | # 预测 |
| | | y_pred = model.predict(X_test) |
| | | y_pred = evaluation_model.predict(X_test) |
| | | |
| | | # 计算IC |
| | | ic_values = [] |
| | |
| | | 'ic_mean': ic_mean, |
| | | 'ic_std': ic_std, |
| | | 'ir': ir, |
| | | 'ic_positive_rate': sum(1 for x in ic_values if x > 0) / len(ic_values) |
| | | 'ic_positive_rate': sum(1 for x in ic_values if x > 0) / len(ic_values), |
| | | 'evaluation_scope': 'out_of_sample', |
| | | 'train_end_date': str(pd.Timestamp(train_dates[-1]).date()), |
| | | 'test_start_date': str(pd.Timestamp(test_dates[0]).date()), |
| | | 'test_end_date': str(pd.Timestamp(test_dates[-1]).date()), |
| | | } |
| | | |
| | | print(f"\n ML模型测试集表现:") |
| | |
| | | print(f" IR: {ir:.2f}") |
| | | print(f" IC正向率: {metrics['ic_positive_rate']:.1%}") |
| | | |
| | | # 对全量数据预测 |
| | | X_all = df[feature_cols].values |
| | | df[f'ml_score_{target}'] = model.predict(X_all) |
| | | |
| | | return model, df, metrics |
| | | score_col = f'ml_score_{target}' |
| | | df[score_col] = np.nan |
| | | df.loc[test_df.index, score_col] = y_pred |
| | | |
| | | # 生产模型使用全部已有标签训练,只为尚无未来收益标签的近期数据评分。 |
| | | production_model = build_model() |
| | | production_model.fit(df_train[feature_cols].values, df_train[target].values) |
| | | live_mask = df[target].isna() |
| | | if live_mask.any(): |
| | | df.loc[live_mask, score_col] = production_model.predict( |
| | | df.loc[live_mask, feature_cols].values |
| | | ) |
| | | |
| | | print( |
| | | f" 样本外评分: {len(test_df)} 条; " |
| | | f"生产评分: {int(live_mask.sum())} 条" |
| | | ) |
| | | return production_model, df, metrics |
| | | |
| | | def evaluate_all_factors(self, df: pd.DataFrame, target: str = 'return_5d') -> dict: |
| | | """评估所有因子""" |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | """Safely reset generated stock data by moving it into a timestamped backup.""" |
| | | |
| | | import argparse |
| | | import json |
| | | import shutil |
| | | import sys |
| | | from datetime import datetime |
| | | from pathlib import Path |
| | | |
| | | |
| | | PROJECT_ROOT = Path(__file__).resolve().parents[1] |
| | | DATA_DIR = PROJECT_ROOT / "data" |
| | | BACKUP_ROOT = DATA_DIR / "backups" |
| | | RESET_FILES = ( |
| | | "akshare_real_data_fixed.pkl", |
| | | "akshare_real_data_fixed_metadata.json", |
| | | "enhanced_factors.pkl", |
| | | "selection_result.json", |
| | | ) |
| | | |
| | | |
| | | def parse_args(argv=None): |
| | | parser = argparse.ArgumentParser( |
| | | description="安全重置行情和派生结果;原文件会移动到 data/backups" |
| | | ) |
| | | parser.add_argument( |
| | | "--yes", |
| | | action="store_true", |
| | | help="确认执行;仅用于用户已经明确确认的自动化场景", |
| | | ) |
| | | return parser.parse_args(argv) |
| | | |
| | | |
| | | def safe_reset_data(data_dir=DATA_DIR, backup_root=BACKUP_ROOT, now=None): |
| | | data_dir = Path(data_dir) |
| | | backup_root = Path(backup_root) |
| | | candidates = [data_dir / name for name in RESET_FILES] |
| | | existing = [path for path in candidates if path.exists()] |
| | | if not existing: |
| | | return None, [] |
| | | |
| | | timestamp = (now or datetime.now()).strftime("%Y%m%d_%H%M%S") |
| | | backup_dir = backup_root / f"stock_data_{timestamp}" |
| | | backup_dir.mkdir(parents=True, exist_ok=False) |
| | | |
| | | moved = [] |
| | | try: |
| | | for source in existing: |
| | | destination = backup_dir / source.name |
| | | shutil.move(str(source), str(destination)) |
| | | moved.append(destination) |
| | | manifest = { |
| | | "created_at": (now or datetime.now()).isoformat(), |
| | | "files": [path.name for path in moved], |
| | | } |
| | | with (backup_dir / "manifest.json").open("w", encoding="utf-8") as handle: |
| | | json.dump(manifest, handle, ensure_ascii=False, indent=2) |
| | | except Exception: |
| | | for destination in reversed(moved): |
| | | if destination.exists(): |
| | | shutil.move(str(destination), str(data_dir / destination.name)) |
| | | raise |
| | | |
| | | return backup_dir, moved |
| | | |
| | | |
| | | def main(argv=None): |
| | | args = parse_args(argv) |
| | | if not args.yes: |
| | | print("此操作会重置正式行情、增强因子和选股结果。") |
| | | print("原文件不会永久删除,而会移动到 data/backups。") |
| | | confirmation = input("请输入 RESET 确认: ").strip() |
| | | if confirmation != "RESET": |
| | | print("已取消。") |
| | | return 1 |
| | | |
| | | backup_dir, moved = safe_reset_data() |
| | | if not moved: |
| | | print("没有找到需要重置的数据文件。") |
| | | return 0 |
| | | |
| | | print(f"已安全重置 {len(moved)} 个文件。") |
| | | print(f"备份目录: {backup_dir}") |
| | | print("下次运行 update_stock_data.py 将自动执行全量初始化。") |
| | | return 0 |
| | | |
| | | |
| | | if __name__ == "__main__": |
| | | sys.exit(main()) |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | """A-share data update dispatcher: incremental by default, full on request.""" |
| | | |
| | | import argparse |
| | | import json |
| | | import os |
| | | import pickle |
| | | import sys |
| | | from datetime import datetime |
| | | from pathlib import Path |
| | | |
| | | import numpy as np |
| | | import pandas as pd |
| | | |
| | | |
| | | PROJECT_ROOT = Path(__file__).resolve().parents[1] |
| | | sys.path.insert(0, str(PROJECT_ROOT)) |
| | | os.chdir(PROJECT_ROOT) |
| | | |
| | | from scripts import data_update_v2 as data_source |
| | | |
| | | |
| | | logger = data_source.logger |
| | | DATA_FILE = PROJECT_ROOT / "data" / "akshare_real_data_fixed.pkl" |
| | | METADATA_FILE = PROJECT_ROOT / "data" / "akshare_real_data_fixed_metadata.json" |
| | | DEFAULT_CONTEXT_DAYS = 70 |
| | | DEFAULT_OVERLAP_DAYS = 7 |
| | | DEFAULT_FULL_DAYS = 730 |
| | | DEFAULT_MIN_COVERAGE = 0.90 |
| | | |
| | | |
| | | def parse_args(argv=None): |
| | | parser = argparse.ArgumentParser( |
| | | description="更新A股行情;默认增量,使用 --full 执行全量重建" |
| | | ) |
| | | parser.add_argument( |
| | | "--full", |
| | | action="store_true", |
| | | help="忽略现有数据并执行全量重建", |
| | | ) |
| | | parser.add_argument( |
| | | "--n-stocks", |
| | | default="all", |
| | | type=data_source.parse_n_stocks, |
| | | help="股票数量,正整数或 all;默认 all", |
| | | ) |
| | | parser.add_argument( |
| | | "--days", |
| | | default=DEFAULT_FULL_DAYS, |
| | | type=int, |
| | | help=f"全量重建历史天数;默认 {DEFAULT_FULL_DAYS}", |
| | | ) |
| | | parser.add_argument( |
| | | "--context-days", |
| | | default=DEFAULT_CONTEXT_DAYS, |
| | | type=int, |
| | | help=f"增量下载的最小技术指标上下文;默认 {DEFAULT_CONTEXT_DAYS}", |
| | | ) |
| | | parser.add_argument( |
| | | "--overlap-days", |
| | | default=DEFAULT_OVERLAP_DAYS, |
| | | type=int, |
| | | help=f"增量合并重叠窗口;默认 {DEFAULT_OVERLAP_DAYS}", |
| | | ) |
| | | parser.add_argument( |
| | | "--min-coverage", |
| | | default=DEFAULT_MIN_COVERAGE, |
| | | type=float, |
| | | help=( |
| | | "允许写入的最低股票覆盖率;默认 " |
| | | f"{DEFAULT_MIN_COVERAGE:.0%}" |
| | | ).replace("%", "%%"), |
| | | ) |
| | | parser.add_argument( |
| | | "--force", |
| | | action="store_true", |
| | | help="与 --skip-if-current 同时使用时仍强制刷新(兼容旧命令)", |
| | | ) |
| | | parser.add_argument( |
| | | "--skip-if-current", |
| | | action="store_true", |
| | | help="本地已覆盖预期交易日时跳过网络请求;默认仍刷新最近窗口", |
| | | ) |
| | | return parser.parse_args(argv) |
| | | |
| | | |
| | | def latest_complete_market_date(df, coverage_ratio=0.8): |
| | | """Return the latest date whose stock coverage is broadly complete.""" |
| | | if df is None or len(df) == 0: |
| | | return None |
| | | if not {"date", "stock_code"}.issubset(df.columns): |
| | | return None |
| | | |
| | | dates = pd.to_datetime(df["date"], errors="coerce").dt.normalize() |
| | | valid = df.loc[dates.notna(), ["stock_code"]].copy() |
| | | valid["_date"] = dates[dates.notna()].values |
| | | counts = valid.groupby("_date")["stock_code"].nunique().sort_index() |
| | | if counts.empty: |
| | | return None |
| | | |
| | | minimum_count = max(1, int(np.ceil(counts.max() * coverage_ratio))) |
| | | complete = counts[counts >= minimum_count] |
| | | selected = complete.index.max() if not complete.empty else counts.index.max() |
| | | return pd.Timestamp(selected).normalize() |
| | | |
| | | |
| | | def latest_expected_business_date(now=None, market_close_hour=16): |
| | | """Approximate the latest completed trading day without an exchange calendar.""" |
| | | current = pd.Timestamp(now or datetime.now()) |
| | | day = current.normalize() |
| | | if day.weekday() < 5 and current.hour >= market_close_hour: |
| | | return day |
| | | |
| | | end = day - pd.Timedelta(days=1) if day.weekday() < 5 else day |
| | | return pd.bdate_range(end=end, periods=1)[0].normalize() |
| | | |
| | | |
| | | def market_date_coverage(df, date, expected_stock_count=None): |
| | | """Return stock count and coverage for one market date.""" |
| | | normalized_dates = pd.to_datetime(df["date"], errors="coerce").dt.normalize() |
| | | date = pd.Timestamp(date).normalize() |
| | | actual = int(df.loc[normalized_dates == date, "stock_code"].astype(str).nunique()) |
| | | expected = int( |
| | | expected_stock_count |
| | | if expected_stock_count is not None |
| | | else df["stock_code"].astype(str).nunique() |
| | | ) |
| | | coverage = actual / expected if expected > 0 else 0.0 |
| | | return expected, actual, coverage |
| | | |
| | | |
| | | def prepare_incremental_rows(existing, fetched, replace_start): |
| | | """Keep only overlap/new rows while retaining context for newly listed stocks.""" |
| | | existing_codes = set(existing["stock_code"].astype(str).str.zfill(6)) |
| | | updates = fetched.copy() |
| | | updates["stock_code"] = updates["stock_code"].astype(str).str.zfill(6) |
| | | updates["date"] = pd.to_datetime(updates["date"], errors="coerce") |
| | | updates = updates.dropna(subset=["date", "stock_code"]) |
| | | |
| | | is_new_stock = ~updates["stock_code"].isin(existing_codes) |
| | | updates = updates[is_new_stock | (updates["date"] >= replace_start)].copy() |
| | | return updates.drop_duplicates(["stock_code", "date"], keep="last") |
| | | |
| | | |
| | | def merge_incremental_data(existing, fetched, replace_start): |
| | | """Replace matching stock/date keys and append genuinely new observations.""" |
| | | current = existing |
| | | if not pd.api.types.is_datetime64_any_dtype(current["date"]): |
| | | current = current.copy() |
| | | current["date"] = pd.to_datetime(current["date"], errors="coerce") |
| | | if not pd.api.types.is_string_dtype(current["stock_code"]): |
| | | if current is existing: |
| | | current = current.copy() |
| | | current["stock_code"] = current["stock_code"].astype(str).str.zfill(6) |
| | | updates = prepare_incremental_rows(current, fetched, replace_start) |
| | | if len(updates) == 0: |
| | | return current, 0, 0 |
| | | |
| | | update_index = pd.MultiIndex.from_frame(updates[["stock_code", "date"]]) |
| | | current_index = pd.MultiIndex.from_frame(current[["stock_code", "date"]]) |
| | | retained = current.loc[~current_index.isin(update_index)] |
| | | merged = pd.concat([retained, updates], ignore_index=True, sort=False) |
| | | |
| | | new_rows = max(0, len(merged) - len(current)) |
| | | replaced_rows = len(updates) - new_rows |
| | | return merged, int(new_rows), int(replaced_rows) |
| | | |
| | | |
| | | def calculate_download_coverage(existing, fetched, requested_stock_count=None): |
| | | """Calculate coverage independently of optional data-source metadata.""" |
| | | expected = int( |
| | | requested_stock_count |
| | | if requested_stock_count is not None |
| | | else existing["stock_code"].astype(str).nunique() |
| | | ) |
| | | actual = int(fetched["stock_code"].astype(str).nunique()) |
| | | calculated = actual / expected if expected > 0 else 0.0 |
| | | reported = fetched.attrs.get("coverage_ratio") |
| | | coverage = ( |
| | | min(calculated, float(reported)) |
| | | if reported is not None |
| | | else calculated |
| | | ) |
| | | return expected, actual, coverage |
| | | |
| | | |
| | | def write_pickle_atomic(df, destination): |
| | | destination = Path(destination) |
| | | destination.parent.mkdir(parents=True, exist_ok=True) |
| | | temporary = destination.with_suffix(destination.suffix + ".tmp") |
| | | try: |
| | | with temporary.open("wb") as handle: |
| | | pickle.dump(df, handle, protocol=pickle.HIGHEST_PROTOCOL) |
| | | os.replace(temporary, destination) |
| | | finally: |
| | | if temporary.exists(): |
| | | temporary.unlink() |
| | | |
| | | |
| | | def write_json_atomic(payload, destination): |
| | | destination = Path(destination) |
| | | destination.parent.mkdir(parents=True, exist_ok=True) |
| | | temporary = destination.with_suffix(destination.suffix + ".tmp") |
| | | try: |
| | | with temporary.open("w", encoding="utf-8") as handle: |
| | | json.dump(payload, handle, ensure_ascii=False, indent=2) |
| | | os.replace(temporary, destination) |
| | | finally: |
| | | if temporary.exists(): |
| | | temporary.unlink() |
| | | |
| | | |
| | | def run_full_update(args): |
| | | count = "all" if args.n_stocks is None else str(args.n_stocks) |
| | | logger.info("更新模式: 全量重建") |
| | | return data_source.main([ |
| | | "--n-stocks", |
| | | count, |
| | | "--days", |
| | | str(args.days), |
| | | ]) |
| | | |
| | | |
| | | def run_incremental_update(args): |
| | | if not DATA_FILE.exists(): |
| | | logger.warning("未找到本地正式数据,自动执行首次全量初始化") |
| | | return run_full_update(args) |
| | | |
| | | logger.info("=" * 60) |
| | | logger.info("数据更新任务开始 - 默认增量模式") |
| | | logger.info("=" * 60) |
| | | with DATA_FILE.open("rb") as handle: |
| | | existing = pickle.load(handle) |
| | | |
| | | latest_before = latest_complete_market_date(existing) |
| | | if latest_before is None: |
| | | logger.error("无法识别本地完整交易日,请使用 --full 重建数据") |
| | | return 1 |
| | | |
| | | expected_date = latest_expected_business_date() |
| | | logger.info( |
| | | f"本地完整交易日: {latest_before:%Y-%m-%d}; " |
| | | f"预期最新交易日: {expected_date:%Y-%m-%d}" |
| | | ) |
| | | before_expected, before_actual, before_coverage = market_date_coverage( |
| | | existing, |
| | | latest_before, |
| | | ) |
| | | logger.info( |
| | | f"本地最新日覆盖: {before_actual}/{before_expected} " |
| | | f"({before_coverage:.2%})" |
| | | ) |
| | | if latest_before >= expected_date and args.skip_if_current and not args.force: |
| | | logger.info("本地行情已是最新,无需发起网络请求") |
| | | logger.info("✅ 增量数据更新完成(无新增)") |
| | | return 0 |
| | | if latest_before >= expected_date: |
| | | logger.info("日期已是最新,仍按默认策略刷新并覆盖最近行情窗口") |
| | | |
| | | stale_days = max(0, (expected_date - latest_before).days) |
| | | fetch_days = max(args.context_days, stale_days + args.overlap_days) |
| | | count_desc = "全部A股" if args.n_stocks is None else f"{args.n_stocks}只股票" |
| | | logger.info( |
| | | f"增量请求范围: {count_desc}; 上下文天数: {fetch_days}; " |
| | | f"重叠天数: {args.overlap_days}" |
| | | ) |
| | | |
| | | fetched = data_source.fetch_real_stock_data_from_akshare( |
| | | n_stocks=args.n_stocks, |
| | | days=fetch_days, |
| | | ) |
| | | if fetched is None or len(fetched) == 0: |
| | | logger.error("增量数据源未返回有效行情,保留原文件不变") |
| | | return 1 |
| | | |
| | | expected_stock_count, actual_stock_count, coverage = ( |
| | | calculate_download_coverage( |
| | | existing, |
| | | fetched, |
| | | requested_stock_count=args.n_stocks, |
| | | ) |
| | | ) |
| | | if coverage is not None and coverage < args.min_coverage: |
| | | logger.error( |
| | | f"增量股票覆盖率 {actual_stock_count}/{expected_stock_count} " |
| | | f"({coverage:.2%}) 低于最低要求 " |
| | | f"{args.min_coverage:.0%},保留原文件不变" |
| | | ) |
| | | return 1 |
| | | |
| | | replace_start = latest_before - pd.Timedelta(days=args.overlap_days) |
| | | merged, new_rows, replaced_rows = merge_incremental_data( |
| | | existing, |
| | | fetched, |
| | | replace_start, |
| | | ) |
| | | latest_after = latest_complete_market_date(merged) |
| | | if latest_after is None or latest_after < latest_before: |
| | | logger.error("合并后完整交易日倒退,拒绝写入并保留原文件") |
| | | return 1 |
| | | |
| | | latest_expected_count, latest_actual_count, latest_coverage = ( |
| | | market_date_coverage( |
| | | merged, |
| | | latest_after, |
| | | expected_stock_count=max( |
| | | expected_stock_count, |
| | | int(merged["stock_code"].astype(str).nunique()), |
| | | ), |
| | | ) |
| | | ) |
| | | |
| | | merged.attrs.update(getattr(existing, "attrs", {})) |
| | | merged.attrs.update({ |
| | | "source": f"incremental_{fetched.attrs.get('source', 'multi_source')}", |
| | | "update_mode": "incremental", |
| | | "factors_need_refresh": True, |
| | | "coverage_ratio": coverage, |
| | | }) |
| | | |
| | | logger.info( |
| | | f"增量合并: 下载 {len(fetched)} 条,新增 {new_rows} 条," |
| | | f"替换 {replaced_rows} 条" |
| | | ) |
| | | logger.info("正在原子写入正式数据文件...") |
| | | write_pickle_atomic(merged, DATA_FILE) |
| | | |
| | | metadata = { |
| | | "create_time": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), |
| | | "source": merged.attrs["source"], |
| | | "update_mode": "incremental", |
| | | "description": "AKShare/BaoStock/腾讯行情增量合并数据", |
| | | "requested_stock_count": ( |
| | | "all" if args.n_stocks is None else int(args.n_stocks) |
| | | ), |
| | | "context_days": int(fetch_days), |
| | | "overlap_days": int(args.overlap_days), |
| | | "previous_complete_date": latest_before.strftime("%Y-%m-%d"), |
| | | "latest_complete_date": latest_after.strftime("%Y-%m-%d"), |
| | | "latest_date_stock_count": latest_actual_count, |
| | | "latest_date_expected_stock_count": latest_expected_count, |
| | | "latest_date_coverage_ratio": latest_coverage, |
| | | "stock_count": int(merged["stock_code"].nunique()), |
| | | "total_records": int(len(merged)), |
| | | "downloaded_records": int(len(fetched)), |
| | | "new_records": new_rows, |
| | | "replaced_records": replaced_rows, |
| | | "coverage_ratio": coverage, |
| | | "expected_stock_count": expected_stock_count, |
| | | "downloaded_stock_count": actual_stock_count, |
| | | "factors_need_refresh": True, |
| | | "date_range": f"{merged['date'].min()} to {merged['date'].max()}", |
| | | } |
| | | write_json_atomic(metadata, METADATA_FILE) |
| | | |
| | | logger.info(f"✓ 最新完整交易日: {latest_after:%Y-%m-%d}") |
| | | logger.info( |
| | | f"✓ 最新日覆盖: {latest_actual_count}/{latest_expected_count} " |
| | | f"({latest_coverage:.2%})" |
| | | ) |
| | | logger.info(f"✓ 股票数量: {merged['stock_code'].nunique()}") |
| | | logger.info(f"✓ 总记录数: {len(merged)}") |
| | | logger.info("✅ 增量数据更新完成") |
| | | return 0 |
| | | |
| | | |
| | | def main(argv=None): |
| | | args = parse_args(argv) |
| | | for name in ("days", "context_days", "overlap_days"): |
| | | if getattr(args, name) <= 0: |
| | | raise SystemExit(f"--{name.replace('_', '-')} 必须为正整数") |
| | | if not 0 < args.min_coverage <= 1: |
| | | raise SystemExit("--min-coverage 必须在 0 和 1 之间") |
| | | return run_full_update(args) if args.full else run_incremental_update(args) |
| | | |
| | | |
| | | if __name__ == "__main__": |
| | | sys.exit(main()) |
| | |
| | | self.assertEqual(args, ["--n-stocks", "all"]) |
| | | self.assertIn("全量", description) |
| | | |
| | | def test_data_update_defaults_to_incremental_dispatcher(self): |
| | | with patch("builtins.input", return_value="1"), patch.object( |
| | | a_stock_manager, "run_script", return_value=True |
| | | ) as run, patch.object( |
| | | a_stock_manager, "run_enhanced_factor_system", return_value=True |
| | | ): |
| | | result = a_stock_manager.data_update() |
| | | |
| | | self.assertTrue(result) |
| | | run.assert_called_once_with( |
| | | "update_stock_data.py", |
| | | "增量更新全部A股", |
| | | ) |
| | | |
| | | def test_data_update_full_rebuild_is_explicit(self): |
| | | with patch("builtins.input", return_value="2"), patch.object( |
| | | a_stock_manager, "run_script", return_value=True |
| | | ) as run, patch.object( |
| | | a_stock_manager, "run_enhanced_factor_system", return_value=True |
| | | ): |
| | | result = a_stock_manager.data_update() |
| | | |
| | | self.assertTrue(result) |
| | | run.assert_called_once_with( |
| | | "update_stock_data.py", |
| | | "全量重建全部A股", |
| | | args=["--full", "--n-stocks", "all", "--days", "730"], |
| | | ) |
| | | |
| | | |
| | | if __name__ == "__main__": |
| | | unittest.main() |
| | |
| | | import importlib |
| | | import sys |
| | | import tempfile |
| | | import unittest |
| | | from pathlib import Path |
| | | from unittest.mock import Mock, patch |
| | | |
| | | import numpy as np |
| | | import pandas as pd |
| | | |
| | | |
| | |
| | | sys.path.insert(0, str(PROJECT_ROOT)) |
| | | |
| | | daily_master = importlib.import_module("scripts.daily_master") |
| | | enhanced_factors = importlib.import_module("scripts.enhanced_factor_system") |
| | | |
| | | |
| | | class LatestCompleteCrossSectionTests(unittest.TestCase): |
| | |
| | | |
| | | self.assertEqual(result, selected) |
| | | self.assertFalse(master.ml_optimization_applied) |
| | | self.assertEqual(master.ml_optimization_status, "未应用(模型尚未训练)") |
| | | self.assertEqual( |
| | | master.ml_optimization_status, |
| | | "未应用(独立二次排序模型尚未训练)", |
| | | ) |
| | | |
| | | |
| | | class EnhancedFactorPipelineTests(unittest.TestCase): |
| | | def test_cross_sectional_factors_can_be_recalculated(self): |
| | | dates = pd.bdate_range(end="2026-07-10", periods=25) |
| | | rows = [] |
| | | for code, price_step in (("600001", 0.1), ("600002", 0.2)): |
| | | rows.extend( |
| | | { |
| | | "date": date, |
| | | "stock_code": code, |
| | | "close": 10 + index * price_step, |
| | | "amount": 1_000_000 + index, |
| | | "change_pct": price_step, |
| | | "ind_mom_val": -999.0, |
| | | } |
| | | for index, date in enumerate(dates) |
| | | ) |
| | | |
| | | system = enhanced_factors.EnhancedFactorSystem() |
| | | calculated = system.calculate_cross_sectional_factors(pd.DataFrame(rows)) |
| | | recalculated = system.calculate_cross_sectional_factors(calculated) |
| | | |
| | | self.assertIn("ind_mom_val", recalculated.columns) |
| | | self.assertNotIn("ind_mom_val_x", recalculated.columns) |
| | | self.assertNotIn("ind_mom_val_y", recalculated.columns) |
| | | expected = recalculated.groupby(["date", "industry"])["momentum_20"].transform("mean") |
| | | pd.testing.assert_series_equal( |
| | | recalculated["ind_mom_val"], |
| | | expected, |
| | | check_names=False, |
| | | ) |
| | | |
| | | def test_daily_run_stops_when_enhanced_factors_fail(self): |
| | | master = daily_master.DailyMaster.__new__(daily_master.DailyMaster) |
| | | master.load_data = Mock(return_value=pd.DataFrame([{"stock_code": "600001"}])) |
| | | master._run_advanced_factor_system = Mock(return_value=None) |
| | | master.evaluate_factors = Mock() |
| | | |
| | | result = master.run() |
| | | |
| | | self.assertFalse(result) |
| | | master.evaluate_factors.assert_not_called() |
| | | |
| | | def test_ml_scores_use_oos_history_and_live_production_rows_only(self): |
| | | class FakeRegressor: |
| | | def __init__(self, **kwargs): |
| | | self.fitted_rows = 0 |
| | | |
| | | def fit(self, features, target): |
| | | self.fitted_rows = len(features) |
| | | return self |
| | | |
| | | def predict(self, features): |
| | | return np.asarray(features)[:, 0] |
| | | |
| | | dates = pd.bdate_range(end="2026-07-10", periods=12) |
| | | rows = [] |
| | | for date_index, date in enumerate(dates): |
| | | for stock_index in range(100): |
| | | target = float(stock_index) / 100 |
| | | if date_index == len(dates) - 1: |
| | | target = np.nan |
| | | rows.append({ |
| | | "date": date, |
| | | "stock_code": f"{stock_index:06d}", |
| | | "earnings_stability": float(stock_index), |
| | | "return_5d": target, |
| | | }) |
| | | data = pd.DataFrame(rows) |
| | | |
| | | with patch.object( |
| | | enhanced_factors, |
| | | "HistGradientBoostingRegressor", |
| | | FakeRegressor, |
| | | ): |
| | | _, scored, metrics = enhanced_factors.EnhancedFactorSystem().train_ml_model( |
| | | data, |
| | | target="return_5d", |
| | | ) |
| | | |
| | | score_col = "ml_score_return_5d" |
| | | train_cutoff = dates[int((len(dates) - 1) * 0.7) - 1] |
| | | historical_train = scored[ |
| | | (scored["date"] <= train_cutoff) & scored["return_5d"].notna() |
| | | ] |
| | | self.assertTrue(historical_train[score_col].isna().all()) |
| | | self.assertTrue(scored.loc[scored["date"] == dates[-1], score_col].notna().all()) |
| | | self.assertEqual(metrics["evaluation_scope"], "out_of_sample") |
| | | |
| | | |
| | | class SelectionPolicyTests(unittest.TestCase): |
| | | def test_tradable_filter_removes_st_delisting_and_bottom_liquidity(self): |
| | | rows = [] |
| | | for index in range(25): |
| | | name = f"股票{index}" |
| | | if index == 0: |
| | | name = "*ST样本" |
| | | elif index == 1: |
| | | name = "样本退" |
| | | rows.append({ |
| | | "stock_code": f"600{index:03d}", |
| | | "stock_name": name, |
| | | "close": 10.0, |
| | | "amount": float(index + 1), |
| | | }) |
| | | |
| | | filtered, metadata = daily_master.filter_tradable_universe(pd.DataFrame(rows)) |
| | | |
| | | self.assertNotIn("*ST样本", set(filtered["stock_name"])) |
| | | self.assertNotIn("样本退", set(filtered["stock_name"])) |
| | | self.assertGreater(metadata["excluded_low_liquidity"], 0) |
| | | self.assertTrue((filtered["amount"] >= metadata["liquidity_amount_threshold"]).all()) |
| | | |
| | | def test_dynamic_score_reverses_negative_ic_factor(self): |
| | | data = pd.DataFrame({ |
| | | "stock_code": ["600001", "600002", "600003"], |
| | | "negative_factor": [1.0, 2.0, 3.0], |
| | | }) |
| | | score, applied = daily_master.calculate_dynamic_cross_section_score( |
| | | data, |
| | | {"negative_factor": 1.0}, |
| | | {"negative_factor": {"ic_mean": -0.1}}, |
| | | ) |
| | | |
| | | self.assertEqual(applied, ["negative_factor"]) |
| | | self.assertGreater(score.iloc[0], score.iloc[-1]) |
| | | |
| | | def test_market_balance_caps_bse_in_every_prefix(self): |
| | | rows = [] |
| | | for index in range(10): |
| | | rows.append({ |
| | | "stock_code": f"920{index:03d}", |
| | | "market": "北交所", |
| | | "score": 100 - index, |
| | | }) |
| | | rows.append({ |
| | | "stock_code": f"600{index:03d}", |
| | | "market": "上交所", |
| | | "score": 50 - index, |
| | | }) |
| | | |
| | | selected = daily_master.select_market_balanced_rows( |
| | | pd.DataFrame(rows), |
| | | "score", |
| | | limit=10, |
| | | max_bse_ratio=0.3, |
| | | ) |
| | | |
| | | for prefix_size in range(1, len(selected) + 1): |
| | | prefix = selected.head(prefix_size) |
| | | self.assertLessEqual( |
| | | int((prefix["market"] == "北交所").sum()), |
| | | int(np.ceil(prefix_size * 0.3)), |
| | | ) |
| | | |
| | | def test_dynamic_weights_only_include_effective_factors(self): |
| | | evaluator = daily_master.EnhancedFactorEvaluator.__new__( |
| | | daily_master.EnhancedFactorEvaluator |
| | | ) |
| | | with tempfile.TemporaryDirectory() as temp_dir: |
| | | evaluator.factor_weights_file = str(Path(temp_dir) / "weights.json") |
| | | weights = evaluator.update_dynamic_weights({ |
| | | "effective_a": {"ic_mean": 0.10, "effective": True}, |
| | | "effective_b": {"ic_mean": -0.05, "effective": True}, |
| | | "ineffective": {"ic_mean": 0.20, "effective": False}, |
| | | }) |
| | | |
| | | self.assertEqual(set(weights), {"effective_a", "effective_b"}) |
| | | self.assertAlmostEqual(sum(weights.values()), 1.0) |
| | | |
| | | def test_select_stocks_applies_filters_dynamic_score_and_market_cap(self): |
| | | dates = pd.bdate_range(end="2026-07-10", periods=60) |
| | | rows = [] |
| | | for stock_index in range(40): |
| | | is_bse = stock_index < 20 |
| | | code = ( |
| | | f"920{stock_index:03d}" |
| | | if is_bse |
| | | else f"600{stock_index:03d}" |
| | | ) |
| | | name = "ST测试" if stock_index == 0 else f"测试{stock_index}" |
| | | factor_value = 100 - stock_index if is_bse else 40 - stock_index |
| | | rows.extend( |
| | | { |
| | | "date": date, |
| | | "stock_code": code, |
| | | "stock_name": name, |
| | | "close": 10.0 + stock_index, |
| | | "amount": float(stock_index + 1) * 1_000_000, |
| | | "test_factor": float(factor_value), |
| | | } |
| | | for date in dates |
| | | ) |
| | | |
| | | master = daily_master.DailyMaster.__new__(daily_master.DailyMaster) |
| | | master.dynamic_weight_status = "未应用" |
| | | master.latest_selection_metadata = {} |
| | | selected = master.select_stocks( |
| | | pd.DataFrame(rows), |
| | | dynamic_weights={"test_factor": 1.0}, |
| | | factor_evaluation={"test_factor": {"ic_mean": 0.1}}, |
| | | ) |
| | | |
| | | self.assertEqual(len(selected), daily_master.DEFAULT_CANDIDATE_COUNT) |
| | | self.assertFalse(any("ST" in stock["stock_name"] for stock in selected)) |
| | | self.assertLessEqual( |
| | | sum(stock["market"] == "北交所" for stock in selected), |
| | | 6, |
| | | ) |
| | | self.assertTrue(all(stock["price"] > 0 for stock in selected)) |
| | | self.assertEqual(master.dynamic_weight_status, "已应用(1个因子)") |
| | | |
| | | |
| | | class RiskAndReportTests(unittest.TestCase): |
| | | def test_factor_risk_uses_current_factor_columns(self): |
| | | master = daily_master.DailyMaster.__new__(daily_master.DailyMaster) |
| | | master.factor_risk_model = daily_master.FactorRiskModel() |
| | | master.factor_exposure_monitor = daily_master.FactorExposureMonitor() |
| | | master.latest_selection_metadata = {"selection_date": "2026-07-10"} |
| | | data = pd.DataFrame([ |
| | | { |
| | | "date": "2026-07-10", |
| | | "stock_code": f"60000{index}", |
| | | "momentum_20": float(index), |
| | | "volatility_20": float(5 - index), |
| | | "amount_rank": float(index) / 5, |
| | | } |
| | | for index in range(1, 6) |
| | | ]) |
| | | selected = [ |
| | | {"stock_code": "600001"}, |
| | | {"stock_code": "600002"}, |
| | | ] |
| | | |
| | | result = master.analyze_factor_risk(data, selected) |
| | | |
| | | self.assertEqual(result["status"], "ok") |
| | | self.assertIn("momentum_20", result["portfolio_exposure"]) |
| | | |
| | | def test_report_uses_selected_price_and_research_label(self): |
| | | generator = daily_master.EnhancedReportGenerator.__new__( |
| | | daily_master.EnhancedReportGenerator |
| | | ) |
| | | generator.stock_prices = {} |
| | | report = generator.generate_full_report( |
| | | selected_stocks=[{ |
| | | "stock_code": "600001", |
| | | "stock_name": "测试股份", |
| | | "score": 0.8, |
| | | "price": 12.34, |
| | | "market": "上交所", |
| | | }], |
| | | factor_evaluation={}, |
| | | dynamic_weights={}, |
| | | portfolio={"positions": []}, |
| | | backtest_results={}, |
| | | risk_signals=[], |
| | | factor_risk_analysis={"status": "no_selection"}, |
| | | ) |
| | | |
| | | self.assertIn("量化研究候选(非交易指令)", report) |
| | | self.assertIn("¥12.34", report) |
| | | self.assertNotIn("建议按今日推荐建仓", report) |
| | | |
| | | def test_daily_run_does_not_restore_candidates_when_risk_rejects_all(self): |
| | | master = daily_master.DailyMaster.__new__(daily_master.DailyMaster) |
| | | data = pd.DataFrame([{"stock_code": "600001"}]) |
| | | candidates = [{ |
| | | "stock_code": "600001", |
| | | "stock_name": "测试股份", |
| | | "score": 0.9, |
| | | "market": "上交所", |
| | | }] |
| | | master.load_data = Mock(return_value=data) |
| | | master._run_advanced_factor_system = Mock(return_value=data) |
| | | master.evaluate_factors = Mock(return_value=( |
| | | {"factor": {"effective": True, "ic_mean": 0.1}}, |
| | | {"factor": 1.0}, |
| | | )) |
| | | master.select_stocks = Mock(return_value=candidates) |
| | | master.optimize_with_ml = Mock(return_value=candidates) |
| | | master.validate_stocks = Mock(return_value=({}, [])) |
| | | master.save_selection_result = Mock() |
| | | master.analyze_factor_risk = Mock(return_value={"status": "no_selection"}) |
| | | master.update_portfolio = Mock(return_value=({"positions": []}, [])) |
| | | master.generate_and_save_report = Mock(return_value=("report", "report.md")) |
| | | master.latest_selection_metadata = {} |
| | | master.enhanced_factor_status = "已完成" |
| | | master.ml_optimization_status = "未应用" |
| | | master.dynamic_weight_status = "已应用" |
| | | |
| | | result = master.run() |
| | | |
| | | self.assertTrue(result) |
| | | master.save_selection_result.assert_called_once_with([], candidates) |
| | | master.analyze_factor_risk.assert_called_once_with(data, []) |
| | | |
| | | |
| | | if __name__ == "__main__": |
| New file |
| | |
| | | import importlib |
| | | import pickle |
| | | import sys |
| | | import tempfile |
| | | import unittest |
| | | from datetime import datetime |
| | | from pathlib import Path |
| | | from unittest.mock import patch |
| | | |
| | | import pandas as pd |
| | | |
| | | |
| | | PROJECT_ROOT = Path(__file__).resolve().parents[1] |
| | | sys.path.insert(0, str(PROJECT_ROOT)) |
| | | |
| | | incremental = importlib.import_module("scripts.update_stock_data") |
| | | reset_data = importlib.import_module("scripts.reset_stock_data") |
| | | |
| | | |
| | | class IncrementalUpdateTests(unittest.TestCase): |
| | | def test_default_mode_is_full_universe_incremental(self): |
| | | args = incremental.parse_args([]) |
| | | |
| | | self.assertFalse(args.full) |
| | | self.assertIsNone(args.n_stocks) |
| | | self.assertFalse(args.skip_if_current) |
| | | self.assertEqual(args.context_days, 70) |
| | | self.assertEqual(args.overlap_days, 7) |
| | | |
| | | def test_latest_complete_date_ignores_partial_newer_market(self): |
| | | rows = [] |
| | | for code in ["600001", "000001", "300001", "688001"]: |
| | | rows.append({"date": "2026-07-09", "stock_code": code}) |
| | | rows.append({"date": "2026-07-10", "stock_code": "920001"}) |
| | | |
| | | result = incremental.latest_complete_market_date(pd.DataFrame(rows)) |
| | | |
| | | self.assertEqual(result, pd.Timestamp("2026-07-09")) |
| | | |
| | | def test_expected_business_date_handles_weekend_and_preclose(self): |
| | | self.assertEqual( |
| | | incremental.latest_expected_business_date( |
| | | datetime(2026, 7, 11, 12, 0) |
| | | ), |
| | | pd.Timestamp("2026-07-10"), |
| | | ) |
| | | self.assertEqual( |
| | | incremental.latest_expected_business_date( |
| | | datetime(2026, 7, 13, 10, 0) |
| | | ), |
| | | pd.Timestamp("2026-07-10"), |
| | | ) |
| | | |
| | | def test_merge_replaces_duplicate_keys_and_keeps_new_stock_context(self): |
| | | existing = pd.DataFrame([ |
| | | { |
| | | "date": "2026-07-08", |
| | | "stock_code": "600001", |
| | | "close": 10.0, |
| | | "final_score": 0.8, |
| | | }, |
| | | { |
| | | "date": "2026-07-09", |
| | | "stock_code": "600001", |
| | | "close": 10.5, |
| | | "final_score": 0.9, |
| | | }, |
| | | ]) |
| | | fetched = pd.DataFrame([ |
| | | {"date": "2026-07-01", "stock_code": "600001", "close": 9.0}, |
| | | {"date": "2026-07-09", "stock_code": "600001", "close": 10.6}, |
| | | {"date": "2026-07-10", "stock_code": "600001", "close": 10.8}, |
| | | {"date": "2026-06-01", "stock_code": "920001", "close": 20.0}, |
| | | {"date": "2026-07-10", "stock_code": "920001", "close": 21.0}, |
| | | ]) |
| | | |
| | | result, new_rows, replaced_rows = incremental.merge_incremental_data( |
| | | existing, |
| | | fetched, |
| | | pd.Timestamp("2026-07-03"), |
| | | ) |
| | | |
| | | self.assertEqual(len(result), 5) |
| | | self.assertEqual(new_rows, 3) |
| | | self.assertEqual(replaced_rows, 1) |
| | | replaced = result[ |
| | | (result["stock_code"] == "600001") |
| | | & (result["date"] == pd.Timestamp("2026-07-09")) |
| | | ] |
| | | self.assertEqual(replaced["close"].tolist(), [10.6]) |
| | | self.assertIn(pd.Timestamp("2026-06-01"), set(result["date"])) |
| | | self.assertNotIn(pd.Timestamp("2026-07-01"), set(result["date"])) |
| | | |
| | | def test_coverage_uses_existing_universe_when_upstream_has_no_metadata(self): |
| | | existing = pd.DataFrame({ |
| | | "stock_code": [f"{index:06d}" for index in range(100)] |
| | | }) |
| | | fetched = pd.DataFrame({ |
| | | "stock_code": [f"{index:06d}" for index in range(20)] |
| | | }) |
| | | |
| | | expected, actual, coverage = incremental.calculate_download_coverage( |
| | | existing, |
| | | fetched, |
| | | ) |
| | | |
| | | self.assertEqual(expected, 100) |
| | | self.assertEqual(actual, 20) |
| | | self.assertEqual(coverage, 0.2) |
| | | |
| | | def test_market_date_coverage_reports_incomplete_latest_day(self): |
| | | data = pd.DataFrame([ |
| | | {"date": "2026-07-10", "stock_code": "600001"}, |
| | | {"date": "2026-07-10", "stock_code": "000001"}, |
| | | {"date": "2026-07-09", "stock_code": "300001"}, |
| | | ]) |
| | | |
| | | expected, actual, coverage = incremental.market_date_coverage( |
| | | data, |
| | | pd.Timestamp("2026-07-10"), |
| | | ) |
| | | |
| | | self.assertEqual(expected, 3) |
| | | self.assertEqual(actual, 2) |
| | | self.assertAlmostEqual(coverage, 2 / 3) |
| | | |
| | | def test_skip_if_current_avoids_network_fetch(self): |
| | | data = pd.DataFrame([ |
| | | {"date": "2026-07-10", "stock_code": "600001", "close": 10.0}, |
| | | {"date": "2026-07-10", "stock_code": "000001", "close": 11.0}, |
| | | ]) |
| | | with tempfile.TemporaryDirectory() as temp_dir: |
| | | data_file = Path(temp_dir) / "stock.pkl" |
| | | with data_file.open("wb") as handle: |
| | | pickle.dump(data, handle) |
| | | |
| | | args = incremental.parse_args(["--skip-if-current"]) |
| | | with patch.object(incremental, "DATA_FILE", data_file), patch.object( |
| | | incremental, |
| | | "latest_expected_business_date", |
| | | return_value=pd.Timestamp("2026-07-10"), |
| | | ), patch.object( |
| | | incremental.data_source, |
| | | "fetch_real_stock_data_from_akshare", |
| | | ) as fetch: |
| | | result = incremental.run_incremental_update(args) |
| | | |
| | | self.assertEqual(result, 0) |
| | | fetch.assert_not_called() |
| | | |
| | | def test_current_date_is_refreshed_by_default(self): |
| | | data = pd.DataFrame([ |
| | | {"date": "2026-07-10", "stock_code": "600001", "close": 10.0}, |
| | | {"date": "2026-07-10", "stock_code": "000001", "close": 11.0}, |
| | | ]) |
| | | fetched = data.copy() |
| | | with tempfile.TemporaryDirectory() as temp_dir: |
| | | data_file = Path(temp_dir) / "stock.pkl" |
| | | with data_file.open("wb") as handle: |
| | | pickle.dump(data, handle) |
| | | |
| | | args = incremental.parse_args([]) |
| | | with patch.object(incremental, "DATA_FILE", data_file), patch.object( |
| | | incremental, |
| | | "latest_expected_business_date", |
| | | return_value=pd.Timestamp("2026-07-10"), |
| | | ), patch.object( |
| | | incremental.data_source, |
| | | "fetch_real_stock_data_from_akshare", |
| | | return_value=fetched, |
| | | ) as fetch, patch.object( |
| | | incremental, "write_pickle_atomic" |
| | | ) as write_pickle, patch.object( |
| | | incremental, "write_json_atomic" |
| | | ): |
| | | result = incremental.run_incremental_update(args) |
| | | |
| | | self.assertEqual(result, 0) |
| | | fetch.assert_called_once() |
| | | write_pickle.assert_called_once() |
| | | |
| | | |
| | | class SafeResetTests(unittest.TestCase): |
| | | def test_reset_moves_generated_files_to_timestamped_backup(self): |
| | | with tempfile.TemporaryDirectory() as temp_dir: |
| | | data_dir = Path(temp_dir) / "data" |
| | | backup_root = data_dir / "backups" |
| | | data_dir.mkdir() |
| | | source = data_dir / "akshare_real_data_fixed.pkl" |
| | | source.write_bytes(b"stock-data") |
| | | |
| | | backup_dir, moved = reset_data.safe_reset_data( |
| | | data_dir=data_dir, |
| | | backup_root=backup_root, |
| | | now=datetime(2026, 7, 11, 9, 30), |
| | | ) |
| | | |
| | | self.assertFalse(source.exists()) |
| | | self.assertEqual( |
| | | backup_dir.name, |
| | | "stock_data_20260711_093000", |
| | | ) |
| | | self.assertEqual([path.name for path in moved], [source.name]) |
| | | self.assertEqual((backup_dir / source.name).read_bytes(), b"stock-data") |
| | | self.assertTrue((backup_dir / "manifest.json").exists()) |
| | | |
| | | |
| | | if __name__ == "__main__": |
| | | unittest.main() |