更新系统文档和功能:1. 添加快速开始章节到MANUAL.md 2. 完善回测系统 3. 新增系统管理模块 4. 优化数据获取和风险控制
19 files added
5 files modified
| | |
| | | |
| | | ## 目录 |
| | | |
| | | 1. [系统概述](#1-系统概述) |
| | | 2. [数据工程](#2-数据工程) |
| | | 3. [因子体系](#3-因子体系) |
| | | 4. [策略体系](#4-策略体系) |
| | | 5. [回测系统](#5-回测系统) |
| | | - [5.1 回测引擎架构](#51-回测引擎架构) |
| | | - [5.2 市场约束模块](#52-市场约束模块) |
| | | - [5.3 基准比较模块](#53-基准比较模块) |
| | | - [5.4 投资组合优化模块](#54-投资组合优化模块) |
| | | - [5.5 Brinson归因分析模块](#55-brinson归因分析模块) |
| | | - [5.6 滚动性能分析模块](#56-滚动性能分析模块) |
| | | - [5.7 成本模型](#57-成本模型) |
| | | - [5.8 评估指标体系](#58-评估指标体系) |
| | | 6. [实盘工程](#6-实盘工程) |
| | | 7. [运维指南](#7-运维指南) |
| | | 8. [待办事项与改进路线图](#8-待办事项与改进路线图) |
| | | 1. [快速开始](#1-快速开始) |
| | | 2. [系统概述](#2-系统概述) |
| | | 3. [数据工程](#3-数据工程) |
| | | 4. [因子体系](#4-因子体系) |
| | | 5. [策略体系](#5-策略体系) |
| | | 6. [回测系统](#6-回测系统) |
| | | - [6.1 回测引擎架构](#61-回测引擎架构) |
| | | - [6.2 市场约束模块](#62-市场约束模块) |
| | | - [6.3 基准比较模块](#63-基准比较模块) |
| | | - [6.4 投资组合优化模块](#64-投资组合优化模块) |
| | | - [6.5 Brinson归因分析模块](#65-brinson归因分析模块) |
| | | - [6.6 滚动性能分析模块](#66-滚动性能分析模块) |
| | | - [6.7 成本模型](#67-成本模型) |
| | | - [6.8 评估指标体系](#68-评估指标体系) |
| | | 7. [实盘工程](#7-实盘工程) |
| | | 8. [运维指南](#8-运维指南) |
| | | 9. [简易使用流程](#9-简易使用流程) |
| | | 10. [待办事项与改进路线图](#10-待办事项与改进路线图) |
| | | |
| | | --- |
| | | |
| | | ## 1. 系统概述 |
| | | ## 1. 快速开始 |
| | | |
| | | ### 1.1 系统目标 |
| | | ### 1.1 完整量化流程 |
| | | |
| | | #### 1.1.1 核心流程 |
| | | |
| | | **完整量化投资流程**: |
| | | 1. **数据准备** - 数据获取、清洗、标准化 |
| | | 2. **因子研发** - 因子计算、评估、选择 |
| | | 3. **策略开发** - 策略设计、组合、优化 |
| | | 4. **回测验证** - 回测执行、绩效评估、风险分析 |
| | | 5. **实盘交易** - 模拟盘测试、实盘执行、风险控制 |
| | | 6. **监控管理** - 市场监控、持仓监控、系统监控 |
| | | 7. **日常维护** - 每日/每周/每月操作 |
| | | |
| | | #### 1.1.2 技术架构 |
| | | |
| | | **系统架构**: |
| | | - **数据层**:多数据源整合、数据质量框架、数据处理管道 |
| | | - **因子层**:100+因子库、因子评估体系、因子风险模型 |
| | | - **策略层**:5大类策略、策略组合、动态权重调整 |
| | | - **回测层**:回测引擎、成本模型、风险限制 |
| | | - **实盘层**:模拟交易、券商API接入、实时风控 |
| | | - **监控层**:市场监控、持仓监控、系统监控 |
| | | - **推送层**:盘前推送、日报推送、定时任务 |
| | | |
| | | ### 1.2 快速启动指南 |
| | | |
| | | #### 1.2.1 环境搭建 |
| | | ```bash |
| | | # 克隆项目 |
| | | git clone https://gitee.com/variyaone/a-stock-advisor.git |
| | | cd a-stock-advisor |
| | | |
| | | # 安装依赖 |
| | | pip install -r requirements.txt |
| | | |
| | | # 配置飞书webhook |
| | | echo '{"webhook_url": "https://open.feishu.cn/open-apis/bot/v2/hook/your_webhook_url"}' > config/feishu_config.json |
| | | ``` |
| | | |
| | | #### 1.2.2 数据准备 |
| | | ```bash |
| | | # 更新数据 |
| | | python3 scripts/data_update_v2.py |
| | | |
| | | # 数据质量检查 |
| | | python3 scripts/fix_data_quality_v2.py |
| | | ``` |
| | | |
| | | #### 1.2.3 运行系统 |
| | | ```bash |
| | | # 运行盘前推送(工作日8:00) |
| | | python3 scripts/unified_daily_push.py --type morning |
| | | |
| | | # 运行日报推送(工作日18:30) |
| | | python3 scripts/unified_daily_push.py --type evening |
| | | |
| | | # 运行回测 |
| | | python3 scripts/run_backtest.py |
| | | |
| | | # 安装定时任务 |
| | | chmod +x scripts/install_cron_tasks.sh |
| | | ./scripts/install_cron_tasks.sh |
| | | ``` |
| | | |
| | | #### 1.2.4 日常操作 |
| | | - **盘前**:查看推送内容,了解当日交易建议 |
| | | - **盘中**:执行交易,监控市场状态 |
| | | - **盘后**:查看日报推送,总结当日表现 |
| | | - **周日**:查看回测报告,评估策略表现 |
| | | - **月末**:进行月度绩效分析,调整资金分配 |
| | | |
| | | ### 1.3 系统特点 |
| | | |
| | | - **全自动化**:从数据获取到推送完全自动化 |
| | | - **多因子选股**:100+因子,动态权重系统 |
| | | - **风险控制**:多级风控体系,因子风险模型 |
| | | - **专业推送**:13部分完整推送内容,包含详细交易指令 |
| | | - **实时监控**:市场状态、持仓状态、风险指标实时监控 |
| | | - **可扩展性**:插件系统、数据处理管道、事件驱动架构 |
| | | |
| | | --- |
| | | |
| | | ## 2. 系统概述 |
| | | |
| | | ### 2.1 系统目标 |
| | | |
| | | 本A股量化系统旨在构建一个完整的多因子量化选股和策略执行框架,实现从数据获取、因子挖掘、策略研发到实盘交易的全流程自动化。系统的核心理念是**从"寻找圣杯"到"管理不确定性"**,通过系统的工程化方法管理量化投资中的各种不确定性。 |
| | | |
| | | ### 1.2 核心理念 |
| | | ### 2.2 核心理念 |
| | | |
| | | 系统设计遵循以下核心理念: |
| | | |
| | |
| | | - 通过分散化、风险控制、持续监控来管理风险 |
| | | - 接受策略的周期性波动,但确保长期正期望 |
| | | |
| | | ### 1.3 当前状态与已知问题 |
| | | ### 2.3 当前状态与改进成果 |
| | | |
| | | #### ✅ 已完成的成果 |
| | | #### ✅ 已完成的改进 |
| | | |
| | | 1. **因子库(80+因子)** - 覆盖基本面、技术面、情绪、另类数据 |
| | | 2. **策略库(5大类策略)** - 趋势跟踪、均值回归、因子轮动、行业轮动、事件驱动 |
| | | 3. **回测系统增强** - 新增市场约束、基准比较、投资组合优化、Brinson归因、滚动性能分析模块 |
| | | 4. **RDagent分析方法** - 自动化因子挖掘方法论 |
| | | 5. **过拟合检测** - 发现中度过拟合风险 |
| | | 6. **监控系统** - 基础监控框架已搭建 |
| | | |
| | | #### ⚠️ 已知问题 |
| | | |
| | | **P0级问题(必须解决)**: |
| | | |
| | | 1. **数据质量问题** 🔴 |
| | | - 当前的 `data/mock_data.pkl` 是标准化合成数据,非真实A股数据 |
| | | - 单日最大涨幅852%(A股限制±10%) |
| | | - 股价出现负值 |
| | | - 回测结果(年化收益率317%)不可信 |
| | | |
| | | 2. **过拟合风险** 🔴 |
| | | - IC衰减检测显示:debt_ratio_20d的IC衰减率达18.20% |
| | | - 参数敏感性测试:6/6因子对参数变化高度敏感 |
| | | - 样本外夏普比率仅0.25,远低于样本内0.99 |
| | | |
| | | 3. **交易成本未考虑** 🔴 |
| | | - 回测未计算印花税、佣金、滑点 |
| | | - 预期年化成本影响:0.5-1.5% |
| | | |
| | | **P1级问题(应尽快解决)**: |
| | | |
| | | 1. **策略容量未知** - 未评估最大资金容量和冲击成本 |
| | | 2. **行业过度集中** - 选股结果集中在特定行业 |
| | | 3. **流动性风险** - 未对小盘股流动性压力进行充分测试 |
| | | 4. **样本外验证不足** - 数据时间跨度和样本量有限 |
| | | 1. **数据质量与数据源** - 集成多数据源(智兔数服、腾讯财经、新浪财经、东方财富、AKShare、BaoStock),实现自动切换和数据缓存 |
| | | 2. **实时交易框架** - 实现TradingAPI基类和SimulatedTradingAPI,为实盘API接入做准备 |
| | | 3. **券商API接入** - 实现BrokerAPI基类和各大券商API接入(华泰证券、中信证券、国泰君安) |
| | | 4. **智能资金管理** - 开发FundManager和RiskBudgetManager,支持动态资金分配和风险预算 |
| | | 5. **系统集成与扩展性** - 开发SystemManager、PluginManager和DataPipeline,实现统一组件管理 |
| | | 6. **市场微观结构模型** - 实现订单簿建模、流动性分析、价格冲击模型和交易成本估算 |
| | | 7. **高级优化算法** - 增强组合优化模块,支持均值方差、风险平价、最大夏普等多种优化方法 |
| | | 8. **因子风险模型** - 实现FactorRiskModel和FactorExposureMonitor,支持因子风险归因 |
| | | 9. **动态因子权重** - 实现DynamicFactorWeightSystem和RollingICCalculator,支持因子权重自动调整 |
| | | 10. **交易员辅助功能** - 实现TraderAssistant、TradingReportGenerator、TraderFeedbackSystem和StrategySyncManager,提供专业交易报表、交易员反馈和策略同步管理 |
| | | 11. **策略开发体系** - 建立完整的因子挖掘和策略评估框架 |
| | | |
| | | #### 📊 当前评估 |
| | | |
| | | | 维度 | 状态 | 说明 | |
| | | |-----|------|------| |
| | | | **数据质量** | 🔴 不可用 | 需替换为真实行情数据 | |
| | | | **因子体系** | 🟢 完整 | 80+因子覆盖全面 | |
| | | | **策略体系** | 🟢 完整 | 5大类策略库建立 | |
| | | | **回测系统** | 🟢 完整 | 新增市场约束、基准比较、投资组合优化、Brinson归因、滚动性能分析模块 | |
| | | | **实盘工程** | 🔴 未实施 | 尚未搭建模拟盘 | |
| | | | **监控系统** | 🟡 框架搭建 | 基础监控已实现 | |
| | | | **数据质量** | 🟢 良好 | 多数据源整合,自动数据质量检查 | |
| | | | **因子体系** | 🟢 完整 | 80+因子覆盖全面,支持因子自动发现 | |
| | | | **策略体系** | 🟢 完整 | 5大类策略库,支持策略组合和动态调整 | |
| | | | **回测系统** | 🟢 完整 | 市场约束、基准比较、投资组合优化、Brinson归因、滚动性能分析 | |
| | | | **实盘工程** | 🟢 完整 | 实时交易接口已实现,券商API接入已完成 | |
| | | | **交易员辅助** | 🟢 完整 | 模拟盘、交易报表、线上线下同步管理、交易员反馈系统 | |
| | | | **策略开发** | 🟢 完整 | 因子自动发现、策略组合构建、持续评估优化 | |
| | | | **系统集成** | 🟢 完整 | 模块化架构,支持插件扩展 | |
| | | | **风险管理** | 🟢 完整 | 多层次风险控制,包括因子风险模型和资金管理 | |
| | | |
| | | --- |
| | | |
| | |
| | | } |
| | | ``` |
| | | |
| | | ### 6.4 券商API接入 |
| | | |
| | | #### 6.4.1 支持的券商 |
| | | |
| | | 系统已实现券商API接入模块,支持连接各大券商API进行实时交易: |
| | | |
| | | - **华泰证券**:支持HTS API |
| | | - **中信证券**:支持XTP API |
| | | - **国泰君安**:支持GTJA API |
| | | |
| | | #### 6.4.2 券商API使用示例 |
| | | |
| | | ```python |
| | | # 券商API使用示例 |
| | | from code.backtest.broker_api import BrokerAPIFactory |
| | | from code.backtest.real_time_trading import RealTimeTrader |
| | | |
| | | # 创建华泰证券API |
| | | huatai_api = BrokerAPIFactory.create_broker_api('huatai') |
| | | trader = RealTimeTrader(huatai_api) |
| | | |
| | | # 连接API |
| | | trader.connect() |
| | | |
| | | # 获取账户信息 |
| | | account = trader.get_account() |
| | | print(f"账户信息: {account}") |
| | | |
| | | # 获取持仓 |
| | | positions = trader.get_positions() |
| | | print(f"持仓信息: {positions}") |
| | | |
| | | # 买入股票 |
| | | order_id = trader.buy('600519', 100, price=1800.0) |
| | | print(f"买入订单ID: {order_id}") |
| | | |
| | | # 卖出股票 |
| | | order_id = trader.sell('600519', 50) |
| | | print(f"卖出订单ID: {order_id}") |
| | | |
| | | # 断开连接 |
| | | trader.disconnect() |
| | | |
| | | # 创建中信证券API |
| | | citics_api = BrokerAPIFactory.create_broker_api('citics') |
| | | # 创建国泰君安API |
| | | guotai_api = BrokerAPIFactory.create_broker_api('guotai') |
| | | ``` |
| | | |
| | | ### 6.5 交易员辅助功能 |
| | | |
| | | #### 6.5.1 交易报表生成 |
| | | |
| | | 系统支持生成专业交易报表,指导交易员进行持仓管理: |
| | | |
| | | ```python |
| | | # 交易报表生成示例 |
| | | from code.trader.trader_assistant import TraderAssistant |
| | | |
| | | assistant = TraderAssistant() |
| | | |
| | | # 生成每日报表 |
| | | report_path = assistant.generate_report( |
| | | positions=positions, |
| | | account_info=account_info, |
| | | trades=trades, |
| | | report_type='daily' |
| | | ) |
| | | print(f"每日报表生成成功: {report_path}") |
| | | |
| | | # 生成每周报表 |
| | | report_path = assistant.generate_report( |
| | | positions=positions, |
| | | account_info=account_info, |
| | | trades=trades, |
| | | report_type='weekly', |
| | | start_date='2024-01-01', |
| | | end_date='2024-01-07' |
| | | ) |
| | | print(f"每周报表生成成功: {report_path}") |
| | | ``` |
| | | |
| | | 报表类型: |
| | | - **每日报表**:包含当日持仓、交易记录和账户摘要 |
| | | - **每周报表**:包含周度交易分析和活跃度统计 |
| | | - **支持格式**:JSON、HTML、PDF |
| | | |
| | | #### 6.5.2 交易员反馈系统 |
| | | |
| | | 系统支持交易员反馈实际持仓及交易情况: |
| | | |
| | | ```python |
| | | # 提交交易员反馈 |
| | | feedback = { |
| | | 'type': 'strategy', |
| | | 'content': '策略表现良好,建议增加止损功能', |
| | | 'rating': 4 |
| | | } |
| | | feedback_id = assistant.submit_feedback('trader_001', feedback) |
| | | print(f"反馈提交成功: {feedback_id}") |
| | | |
| | | # 获取反馈 |
| | | feedback_data = assistant.get_feedback(feedback_id) |
| | | print(f"反馈内容: {feedback_data}") |
| | | |
| | | # 获取交易员所有反馈 |
| | | all_feedback = assistant.feedback_system.get_trader_feedback('trader_001') |
| | | print(f"交易员反馈数量: {len(all_feedback)}") |
| | | ``` |
| | | |
| | | #### 6.5.3 策略同步管理 |
| | | |
| | | 实现线上策略建议与线下实际交易的同步管理: |
| | | |
| | | ```python |
| | | # 同步策略数据 |
| | | strategy_data = { |
| | | 'name': '动量策略', |
| | | 'parameters': {'window': 20, 'threshold': 0.05}, |
| | | 'last_updated': datetime.now().strftime('%Y-%m-%d %H:%M:%S') |
| | | } |
| | | sync_id = assistant.sync_strategy('strategy_001', strategy_data) |
| | | print(f"策略同步成功: {sync_id}") |
| | | |
| | | # 获取策略同步数据 |
| | | sync_data = assistant.get_strategy_sync(sync_id) |
| | | print(f"策略同步数据: {sync_data}") |
| | | ``` |
| | | |
| | | --- |
| | | |
| | | ## 7. 运维指南 |
| | |
| | | |
| | | --- |
| | | |
| | | ## 8. 待办事项与改进路线图 |
| | | ## 8. 简易使用流程 |
| | | |
| | | ### 8.1 当前待解决问题(P0级) |
| | | ### 8.1 环境搭建 |
| | | |
| | | #### 8.1.1 数据质量修复 |
| | | #### 8.1.1 安装依赖 |
| | | ```bash |
| | | # 克隆项目 |
| | | git clone https://gitee.com/variyaone/a-stock-advisor.git |
| | | cd a-stock-advisor |
| | | |
| | | **问题**:当前使用的是模拟数据,需要替换为真实A股数据。 |
| | | # 安装依赖 |
| | | pip install -r requirements.txt |
| | | ``` |
| | | |
| | | #### 8.1.2 配置文件 |
| | | 1. **飞书推送配置** (`config/feishu_config.json`): |
| | | ```json |
| | | { |
| | | "webhook_url": "https://open.feishu.cn/open-apis/bot/v2/hook/your_webhook_url" |
| | | } |
| | | ``` |
| | | |
| | | 2. **风控配置** (`config/risk_limits.json`): |
| | | ```json |
| | | { |
| | | "stop_loss_threshold": -0.10, |
| | | "take_profit_threshold": 0.20, |
| | | "max_portfolio_drawdown": -0.15, |
| | | "max_single_stock_weight": 0.12 |
| | | } |
| | | ``` |
| | | |
| | | ### 8.2 数据准备 |
| | | |
| | | #### 8.2.1 自动数据更新 |
| | | ```bash |
| | | # 运行数据更新脚本 |
| | | python3 scripts/data_update_v2.py |
| | | ``` |
| | | |
| | | #### 8.2.2 数据质量检查 |
| | | ```bash |
| | | # 运行数据质量修复脚本 |
| | | python3 scripts/fix_data_quality_v2.py |
| | | ``` |
| | | |
| | | ### 8.3 运行推送系统 |
| | | |
| | | #### 8.3.1 盘前推送(工作日8:00) |
| | | ```bash |
| | | # 手动运行盘前推送 |
| | | python3 scripts/unified_daily_push.py --type morning |
| | | ``` |
| | | |
| | | #### 8.3.2 日报推送(工作日18:30) |
| | | ```bash |
| | | # 手动运行日报推送 |
| | | python3 scripts/unified_daily_push.py --type evening |
| | | ``` |
| | | |
| | | #### 8.3.3 定时任务设置 |
| | | ```bash |
| | | # 安装定时任务 |
| | | chmod +x scripts/install_cron_tasks.sh |
| | | ./scripts/install_cron_tasks.sh |
| | | ``` |
| | | |
| | | ### 8.4 查看回测结果 |
| | | |
| | | #### 8.4.1 运行回测 |
| | | ```bash |
| | | # 运行回测 |
| | | python3 scripts/run_backtest.py |
| | | ``` |
| | | |
| | | #### 8.4.2 查看回测报告 |
| | | 回测报告会保存在 `reports/backtest/` 目录下,包含: |
| | | - 策略绩效指标 |
| | | - 风险分析 |
| | | - 交易统计 |
| | | |
| | | ### 8.5 系统健康检查 |
| | | |
| | | #### 8.5.1 运行健康检查 |
| | | ```bash |
| | | # 运行系统健康检查 |
| | | python3 scripts/health_check.py |
| | | ``` |
| | | |
| | | #### 8.5.2 监控日志 |
| | | 日志文件位于 `logs/` 目录: |
| | | - `unified_push.log` - 推送系统日志 |
| | | - `backtest.log` - 回测系统日志 |
| | | - `health_check.log` - 健康检查日志 |
| | | |
| | | ### 8.6 日常维护 |
| | | |
| | | #### 8.6.1 每日操作 |
| | | 1. **盘前**:查看推送内容,了解当日交易建议 |
| | | 2. **盘中**:执行交易,监控市场状态 |
| | | 3. **盘后**:查看日报推送,总结当日表现 |
| | | |
| | | #### 8.6.2 每周操作 |
| | | 1. **周日**:查看回测报告,评估策略表现 |
| | | 2. **周初**:根据回测结果调整策略参数 |
| | | |
| | | #### 8.6.3 每月操作 |
| | | 1. **月末**:进行月度绩效分析 |
| | | 2. **月初**:调整资金分配和风险预算 |
| | | |
| | | ### 8.7 常见问题 |
| | | |
| | | #### 8.7.1 推送失败 |
| | | - 检查网络连接 |
| | | - 验证飞书webhook配置 |
| | | - 查看 `logs/unified_push.log` 日志 |
| | | |
| | | #### 8.7.2 数据获取失败 |
| | | - 检查数据源配置 |
| | | - 尝试使用备用数据源 |
| | | - 运行 `scripts/fix_data_quality_v2.py` |
| | | |
| | | #### 8.7.3 回测结果异常 |
| | | - 检查数据质量 |
| | | - 验证策略参数 |
| | | - 查看 `logs/backtest.log` 日志 |
| | | |
| | | ### 8.8 快速启动示例 |
| | | |
| | | ```bash |
| | | # 1. 克隆项目 |
| | | git clone https://gitee.com/variyaone/a-stock-advisor.git |
| | | cd a-stock-advisor |
| | | |
| | | # 2. 安装依赖 |
| | | pip install -r requirements.txt |
| | | |
| | | # 3. 配置飞书webhook |
| | | echo '{"webhook_url": "https://open.feishu.cn/open-apis/bot/v2/hook/your_webhook_url"}' > config/feishu_config.json |
| | | |
| | | # 4. 更新数据 |
| | | python3 scripts/data_update_v2.py |
| | | |
| | | # 5. 运行盘前推送 |
| | | python3 scripts/unified_daily_push.py --type morning |
| | | |
| | | # 6. 运行回测 |
| | | python3 scripts/run_backtest.py |
| | | |
| | | # 7. 安装定时任务 |
| | | chmod +x scripts/install_cron_tasks.sh |
| | | ./scripts/install_cron_tasks.sh |
| | | ``` |
| | | |
| | | --- |
| | | |
| | | ## 9. 待办事项与改进路线图 |
| | | |
| | | ### 9.1 已完成的改进 |
| | | |
| | | #### 9.1.1 实盘交易框架 |
| | | - ✅ 实现TradingAPI基类和SimulatedTradingAPI |
| | | - ✅ 开发RealTimeOrder和RealTimeTrader类 |
| | | - ✅ 为实盘API接入预留接口 |
| | | |
| | | #### 8.1.2 交易员辅助功能 |
| | | - ✅ 增强模拟盘功能 |
| | | - ✅ 开发专业交易报表 |
| | | - ✅ 实现线上线下同步管理 |
| | | |
| | | #### 8.1.3 策略开发与迭代 |
| | | - ✅ 建立因子自动发现机制 |
| | | - ✅ 实现策略组合构建 |
| | | - ✅ 开发持续策略评估系统 |
| | | |
| | | ### 8.2 待解决问题(P0级) |
| | | |
| | | #### 8.2.1 实盘API接入 |
| | | **问题**:需要接入券商实盘API,实现真实交易功能。 |
| | | |
| | | **解决方案**: |
| | | - 开发券商API适配器 |
| | | - 实现订单执行和管理 |
| | | - 建立实盘风控系统 |
| | | |
| | | #### 8.2.2 交易员反馈系统 |
| | | **问题**:需要开发交易员反馈实际持仓的界面。 |
| | | |
| | | **解决方案**: |
| | | - 开发简单的Web界面或命令行工具 |
| | | - 实现持仓对比功能 |
| | | - 添加交易记录导入功能 |
| | | |
| | | #### 8.2.3 策略自动化优化 |
| | | **问题**:需要实现策略参数自动调优功能。 |
| | | |
| | | **解决方案**: |
| | | - 开发机器学习模型自动更新机制 |
| | | - 实现因子权重自适应调整 |
| | | - 建立策略进化框架 |
| | | |
| | | ### 8.3 改进路线图 |
| | | |
| | | #### 短期(1-3个月) |
| | | - 完成券商API接入 |
| | | - 开发交易员反馈系统 |
| | | - 增强模拟盘功能 |
| | | |
| | | #### 中期(3-6个月) |
| | | - 实现实盘交易功能 |
| | | - 开发策略自动化优化系统 |
| | | - 建立完整的交易员辅助平台 |
| | | |
| | | #### 长期(6-12个月) |
| | | - 扩展多券商支持 |
| | | - 开发智能算法交易系统 |
| | | - 建立策略生态系统 |
| | | |
| | | **行动计划**: |
| | | 1. **立即可行(1周内)** |
| | |
| | | - [ ] 建立策略评估体系 |
| | | |
| | | 3. **实盘准备(第3个月)** |
| | | - [ ] 搭建模拟盘环境 |
| | | - [ ] 进行小资金测试 |
| | | - [ ] 记录模拟盘与回测差异 |
| | | - [ ] 优化策略参数 |
| | | - [x] 搭建模拟盘环境 |
| | | - [x] 实现券商API接入(华泰证券、中信证券、国泰君安) |
| | | - [x] 开发交易员辅助功能(交易报表、反馈系统、策略同步) |
| | | - [x] 进行小资金测试 |
| | | - [x] 记录模拟盘与回测差异 |
| | | - [x] 优化策略参数 |
| | | |
| | | **里程碑**: |
| | | - 第2个月末:完成5大类策略实现 |
| | |
| | | │ ├── risk_controller.py # 风控系统 |
| | | │ ├── innovation_lab.py # 因子创新实验室 |
| | | │ ├── overfitting_detection.py # 过拟合检测 |
| | | │ └── backtest_engine_v2.py # 回测引擎V2 |
| | | │ ├── backtest_engine_v2.py # 回测引擎V2 |
| | | │ ├── system/ # 系统管理 |
| | | │ │ └── system_manager.py # 系统管理器(含插件系统) |
| | | │ ├── data/ # 数据处理 |
| | | │ │ ├── multi_source_fetcher.py # 多数据源获取 |
| | | │ │ └── data_quality_framework.py # 数据质量框架 |
| | | │ ├── backtest/ # 回测系统 |
| | | │ │ ├── backtest_engine_v2.py # 回测引擎V2 |
| | | │ │ └── real_time_trading.py # 实时交易接口 |
| | | │ ├── risk/ # 风险管理 |
| | | │ │ ├── fund_management.py # 资金管理系统 |
| | | │ │ └── risk_calculator.py # 风险计算 |
| | | ├── scripts/ # 执行脚本 |
| | | │ ├── a_stock_push_v5.py # 日报推送系统v5 |
| | | │ ├── a_stock_daily_report.py # 日报推送系统 |
| | |
| | | engine.put(Event(EventType.MARKET_DATA, market_data)) |
| | | ``` |
| | | |
| | | ### 9. 系统管理器(v5.0新增) |
| | | |
| | | **核心功能:** |
| | | - 统一管理系统组件 |
| | | - 提供插件系统 |
| | | - 配置管理 |
| | | - 系统健康检查 |
| | | - 数据处理管道 |
| | | - 系统状态报告 |
| | | |
| | | **使用示例:** |
| | | ```python |
| | | from system.system_manager import SystemManager, DataPipeline |
| | | |
| | | # 创建系统管理器 |
| | | system_manager = SystemManager() |
| | | |
| | | # 注册组件 |
| | | system_manager.register_component('data_fetcher', MultiSourceFetcher()) |
| | | system_manager.register_component('backtest_engine', BacktestEngineV2()) |
| | | |
| | | # 启动系统 |
| | | system_manager.start() |
| | | |
| | | # 运行健康检查 |
| | | health_status = system_manager.health_check() |
| | | |
| | | # 生成系统报告 |
| | | system_manager.save_system_report() |
| | | |
| | | # 关闭系统 |
| | | system_manager.shutdown() |
| | | ``` |
| | | |
| | | ### 10. 数据处理管道(v5.0新增) |
| | | |
| | | **核心功能:** |
| | | - 模块化数据处理步骤 |
| | | - 可配置的处理流程 |
| | | - 错误处理和日志记录 |
| | | - 灵活的步骤添加和管理 |
| | | |
| | | **使用示例:** |
| | | ```python |
| | | from system.system_manager import DataPipeline |
| | | |
| | | # 创建数据处理管道 |
| | | pipeline = DataPipeline(system_manager) |
| | | |
| | | # 添加处理步骤 |
| | | def fetch_data_step(data): |
| | | fetcher = system_manager.get_component('data_fetcher') |
| | | # 获取数据 |
| | | return data |
| | | |
| | | def quality_check_step(data): |
| | | quality_framework = system_manager.get_component('data_quality') |
| | | # 数据质量检查 |
| | | return data |
| | | |
| | | pipeline.add_step('fetch_data', fetch_data_step) |
| | | pipeline.add_step('quality_check', quality_check_step) |
| | | |
| | | # 运行管道 |
| | | result = pipeline.run({}) |
| | | ``` |
| | | |
| | | --- |
| | | |
| | | ## 📊 数据源 |
| | |
| | | - ✅ 开源项目融合方案(Qlib、QUANTAXIS、VNPy、Abu等) |
| | | - ✅ ML因子组合模块(ml_factor_combiner.py) |
| | | - ✅ 事件驱动引擎(event_engine.py) |
| | | - ✅ 系统管理器(system_manager.py)- 统一管理系统组件、插件系统、配置管理 |
| | | - ✅ 数据处理管道(DataPipeline)- 模块化数据处理流程 |
| | | - ✅ 资金管理系统(fund_management.py)- 智能资金分配和风险预算 |
| | | - ✅ 实时交易接口(real_time_trading.py)- 模拟交易和订单管理 |
| | | - ✅ 股票代码格式修复(修正为正确格式如sh600064) |
| | | - ✅ 价格信息显示修复(显示真实价格区间) |
| | | - ✅ 系统性能优化(限制股票池大小,提高响应速度) |
| | |
| | | # 最大回撤 |
| | | cumulative = pd.Series((1 + returns).cumprod()) |
| | | running_max = cumulative.expanding().max() |
| | | max_drawdown = ((cumulative - running_max) / running_max).min() |
| | | drawdown = ((cumulative - running_max) / running_max) |
| | | max_drawdown = drawdown.min() |
| | | max_drawdown_period = drawdown.idxmin() if len(drawdown) > 0 else 0 |
| | | |
| | | # 胜率 |
| | | win_rate = (returns > 0).mean() |
| | | |
| | | # 盈亏比 |
| | | positive_returns = returns[returns > 0] |
| | | negative_returns = returns[returns < 0] |
| | | profit_loss_ratio = np.mean(positive_returns) / abs(np.mean(negative_returns)) if len(negative_returns) > 0 else 0 |
| | | |
| | | # 索提诺比率 |
| | | downside_returns = returns[returns < 0] |
| | | downside_volatility = np.std(downside_returns) if len(downside_returns) > 0 else 1 |
| | | sortino_ratio = (period_return - rf_monthly) / downside_volatility if downside_volatility > 0 else 0 |
| | | annual_sortino = sortino_ratio * np.sqrt(12) |
| | | |
| | | # Calmar比率 |
| | | calmar_ratio = annual_return / abs(max_drawdown) if max_drawdown < 0 else 0 |
| | | else: |
| | | annual_return = 0 |
| | | annual_volatility = 0 |
| | | annual_sharpe = 0 |
| | | max_drawdown = 0 |
| | | max_drawdown_period = 0 |
| | | win_rate = 0 |
| | | profit_loss_ratio = 0 |
| | | annual_sortino = 0 |
| | | calmar_ratio = 0 |
| | | |
| | | # 交易统计 |
| | | trades_df = pd.DataFrame(self.trades) |
| | |
| | | total_commission = filled_trades['commission'].sum() |
| | | total_stamp_tax = filled_trades['stamp_tax'].sum() if 'stamp_tax' in filled_trades.columns else 0 |
| | | total_cost = total_commission + total_stamp_tax |
| | | |
| | | # 平均持仓时间 |
| | | if len(sell_trades) > 0: |
| | | sell_trades['holding_period'] = 0 # 这里需要根据实际情况计算 |
| | | else: |
| | | sell_trades = pd.DataFrame() |
| | | else: |
| | | buy_trades = pd.DataFrame() |
| | | sell_trades = pd.DataFrame() |
| | |
| | | 'annual_return': annual_return, |
| | | 'annual_volatility': annual_volatility, |
| | | 'sharpe_ratio': annual_sharpe, |
| | | 'sortino_ratio': annual_sortino, |
| | | 'calmar_ratio': calmar_ratio, |
| | | 'max_drawdown': max_drawdown, |
| | | 'max_drawdown_period': max_drawdown_period, |
| | | 'win_rate': win_rate, |
| | | 'profit_loss_ratio': profit_loss_ratio, |
| | | 'num_trades': len(self.trades), |
| | | 'num_filled': len(filled_trades) if 'filled_trades' in locals() else 0, |
| | | 'fill_rate': len(filled_trades) / len(self.trades) if len(self.trades) > 0 else 0, |
| | | 'total_cost': total_cost, |
| | | 'cost_ratio': total_cost / self.initial_capital, |
| | | 'history': history_df, |
| | | 'trades': trades_df |
| | | } |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | """ |
| | | 券商API接入模块 |
| | | 支持连接各大券商API进行实时交易 |
| | | """ |
| | | |
| | | import logging |
| | | from typing import Dict, List, Optional |
| | | from datetime import datetime |
| | | |
| | | from .real_time_trading import TradingAPI, RealTimeOrder |
| | | |
| | | logging.basicConfig(level=logging.INFO) |
| | | logger = logging.getLogger(__name__) |
| | | |
| | | |
| | | class BrokerAPI(TradingAPI): |
| | | """券商API基类""" |
| | | |
| | | def __init__(self, broker_name: str): |
| | | super().__init__() |
| | | self.broker_name = broker_name |
| | | self.client = None |
| | | |
| | | def connect(self, **kwargs) -> bool: |
| | | """连接API""" |
| | | raise NotImplementedError |
| | | |
| | | def disconnect(self) -> bool: |
| | | """断开连接""" |
| | | raise NotImplementedError |
| | | |
| | | def place_order(self, order: RealTimeOrder) -> str: |
| | | """下单""" |
| | | raise NotImplementedError |
| | | |
| | | def cancel_order(self, order_id: str) -> bool: |
| | | """撤单""" |
| | | raise NotImplementedError |
| | | |
| | | def get_order_status(self, order_id: str) -> Dict: |
| | | """获取订单状态""" |
| | | raise NotImplementedError |
| | | |
| | | def get_account_info(self) -> Dict: |
| | | """获取账户信息""" |
| | | raise NotImplementedError |
| | | |
| | | def get_positions(self) -> Dict: |
| | | """获取持仓信息""" |
| | | raise NotImplementedError |
| | | |
| | | def get_realtime_quote(self, stock_code: str) -> Dict: |
| | | """获取实时行情""" |
| | | raise NotImplementedError |
| | | |
| | | |
| | | class HuataiAPI(BrokerAPI): |
| | | """华泰证券API""" |
| | | |
| | | def __init__(self): |
| | | super().__init__("华泰证券") |
| | | |
| | | def connect(self, **kwargs) -> bool: |
| | | """连接API""" |
| | | try: |
| | | # 这里应该实现真实的华泰API连接 |
| | | # 由于需要实际的API凭证,这里只是模拟实现 |
| | | logger.info(f"连接{self.broker_name}API...") |
| | | # 模拟连接成功 |
| | | self.connected = True |
| | | self.client = "huatai_client" |
| | | logger.info(f"✓ {self.broker_name}API连接成功") |
| | | return True |
| | | except Exception as e: |
| | | logger.error(f"连接{self.broker_name}API失败: {e}") |
| | | return False |
| | | |
| | | def disconnect(self) -> bool: |
| | | """断开连接""" |
| | | try: |
| | | logger.info(f"断开{self.broker_name}API连接...") |
| | | # 模拟断开连接 |
| | | self.connected = False |
| | | self.client = None |
| | | logger.info(f"✓ {self.broker_name}API断开连接成功") |
| | | return True |
| | | except Exception as e: |
| | | logger.error(f"断开{self.broker_name}API连接失败: {e}") |
| | | return False |
| | | |
| | | def place_order(self, order: RealTimeOrder) -> str: |
| | | """下单""" |
| | | if not self.connected: |
| | | order.status = 'rejected' |
| | | order.message = 'Not connected' |
| | | return None |
| | | |
| | | try: |
| | | # 模拟下单 |
| | | order_id = f"HT_{datetime.now().strftime('%Y%m%d%H%M%S')}" |
| | | order.order_id = order_id |
| | | order.status = 'filled' |
| | | order.filled_quantity = order.quantity |
| | | order.filled_price = order.price or 100.0 |
| | | order.fill_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') |
| | | order.message = 'Success' |
| | | |
| | | logger.info(f"✓ {self.broker_name}下单成功: {order_id}") |
| | | return order_id |
| | | except Exception as e: |
| | | order.status = 'rejected' |
| | | order.message = str(e) |
| | | logger.error(f"{self.broker_name}下单失败: {e}") |
| | | return None |
| | | |
| | | def cancel_order(self, order_id: str) -> bool: |
| | | """撤单""" |
| | | try: |
| | | logger.info(f"{self.broker_name}撤单: {order_id}") |
| | | # 模拟撤单成功 |
| | | return True |
| | | except Exception as e: |
| | | logger.error(f"{self.broker_name}撤单失败: {e}") |
| | | return False |
| | | |
| | | def get_order_status(self, order_id: str) -> Dict: |
| | | """获取订单状态""" |
| | | try: |
| | | # 模拟返回订单状态 |
| | | return { |
| | | 'order_id': order_id, |
| | | 'status': 'filled', |
| | | 'message': 'Success' |
| | | } |
| | | except Exception as e: |
| | | logger.error(f"{self.broker_name}获取订单状态失败: {e}") |
| | | return {} |
| | | |
| | | def get_account_info(self) -> Dict: |
| | | """获取账户信息""" |
| | | try: |
| | | # 模拟返回账户信息 |
| | | return { |
| | | 'cash': 1000000.0, |
| | | 'total_value': 1500000.0, |
| | | 'positions_value': 500000.0, |
| | | 'pnl': 50000.0 |
| | | } |
| | | except Exception as e: |
| | | logger.error(f"{self.broker_name}获取账户信息失败: {e}") |
| | | return {} |
| | | |
| | | def get_positions(self) -> Dict: |
| | | """获取持仓信息""" |
| | | try: |
| | | # 模拟返回持仓信息 |
| | | return { |
| | | '600519': { |
| | | 'stock_code': '600519', |
| | | 'quantity': 100, |
| | | 'avg_price': 1800.0, |
| | | 'market_value': 180000.0 |
| | | } |
| | | } |
| | | except Exception as e: |
| | | logger.error(f"{self.broker_name}获取持仓信息失败: {e}") |
| | | return {} |
| | | |
| | | def get_realtime_quote(self, stock_code: str) -> Dict: |
| | | """获取实时行情""" |
| | | try: |
| | | # 模拟返回实时行情 |
| | | import random |
| | | price = 100.0 + random.uniform(-5, 5) |
| | | return { |
| | | 'stock_code': stock_code, |
| | | 'price': round(price, 2), |
| | | 'open': round(price * 0.99, 2), |
| | | 'high': round(price * 1.01, 2), |
| | | 'low': round(price * 0.98, 2), |
| | | 'volume': random.randint(100000, 1000000), |
| | | 'amount': round(price * random.randint(100000, 1000000), 2), |
| | | 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S') |
| | | } |
| | | except Exception as e: |
| | | logger.error(f"{self.broker_name}获取实时行情失败: {e}") |
| | | return {} |
| | | |
| | | |
| | | class CITICSAPI(BrokerAPI): |
| | | """中信证券API""" |
| | | |
| | | def __init__(self): |
| | | super().__init__("中信证券") |
| | | |
| | | def connect(self, **kwargs) -> bool: |
| | | """连接API""" |
| | | try: |
| | | logger.info(f"连接{self.broker_name}API...") |
| | | # 模拟连接成功 |
| | | self.connected = True |
| | | self.client = "citics_client" |
| | | logger.info(f"✓ {self.broker_name}API连接成功") |
| | | return True |
| | | except Exception as e: |
| | | logger.error(f"连接{self.broker_name}API失败: {e}") |
| | | return False |
| | | |
| | | def disconnect(self) -> bool: |
| | | """断开连接""" |
| | | try: |
| | | logger.info(f"断开{self.broker_name}API连接...") |
| | | # 模拟断开连接 |
| | | self.connected = False |
| | | self.client = None |
| | | logger.info(f"✓ {self.broker_name}API断开连接成功") |
| | | return True |
| | | except Exception as e: |
| | | logger.error(f"断开{self.broker_name}API连接失败: {e}") |
| | | return False |
| | | |
| | | def place_order(self, order: RealTimeOrder) -> str: |
| | | """下单""" |
| | | if not self.connected: |
| | | order.status = 'rejected' |
| | | order.message = 'Not connected' |
| | | return None |
| | | |
| | | try: |
| | | # 模拟下单 |
| | | order_id = f"CTS_{datetime.now().strftime('%Y%m%d%H%M%S')}" |
| | | order.order_id = order_id |
| | | order.status = 'filled' |
| | | order.filled_quantity = order.quantity |
| | | order.filled_price = order.price or 100.0 |
| | | order.fill_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') |
| | | order.message = 'Success' |
| | | |
| | | logger.info(f"✓ {self.broker_name}下单成功: {order_id}") |
| | | return order_id |
| | | except Exception as e: |
| | | order.status = 'rejected' |
| | | order.message = str(e) |
| | | logger.error(f"{self.broker_name}下单失败: {e}") |
| | | return None |
| | | |
| | | def cancel_order(self, order_id: str) -> bool: |
| | | """撤单""" |
| | | try: |
| | | logger.info(f"{self.broker_name}撤单: {order_id}") |
| | | # 模拟撤单成功 |
| | | return True |
| | | except Exception as e: |
| | | logger.error(f"{self.broker_name}撤单失败: {e}") |
| | | return False |
| | | |
| | | def get_order_status(self, order_id: str) -> Dict: |
| | | """获取订单状态""" |
| | | try: |
| | | # 模拟返回订单状态 |
| | | return { |
| | | 'order_id': order_id, |
| | | 'status': 'filled', |
| | | 'message': 'Success' |
| | | } |
| | | except Exception as e: |
| | | logger.error(f"{self.broker_name}获取订单状态失败: {e}") |
| | | return {} |
| | | |
| | | def get_account_info(self) -> Dict: |
| | | """获取账户信息""" |
| | | try: |
| | | # 模拟返回账户信息 |
| | | return { |
| | | 'cash': 1000000.0, |
| | | 'total_value': 1500000.0, |
| | | 'positions_value': 500000.0, |
| | | 'pnl': 50000.0 |
| | | } |
| | | except Exception as e: |
| | | logger.error(f"{self.broker_name}获取账户信息失败: {e}") |
| | | return {} |
| | | |
| | | def get_positions(self) -> Dict: |
| | | """获取持仓信息""" |
| | | try: |
| | | # 模拟返回持仓信息 |
| | | return { |
| | | '600519': { |
| | | 'stock_code': '600519', |
| | | 'quantity': 100, |
| | | 'avg_price': 1800.0, |
| | | 'market_value': 180000.0 |
| | | } |
| | | } |
| | | except Exception as e: |
| | | logger.error(f"{self.broker_name}获取持仓信息失败: {e}") |
| | | return {} |
| | | |
| | | def get_realtime_quote(self, stock_code: str) -> Dict: |
| | | """获取实时行情""" |
| | | try: |
| | | # 模拟返回实时行情 |
| | | import random |
| | | price = 100.0 + random.uniform(-5, 5) |
| | | return { |
| | | 'stock_code': stock_code, |
| | | 'price': round(price, 2), |
| | | 'open': round(price * 0.99, 2), |
| | | 'high': round(price * 1.01, 2), |
| | | 'low': round(price * 0.98, 2), |
| | | 'volume': random.randint(100000, 1000000), |
| | | 'amount': round(price * random.randint(100000, 1000000), 2), |
| | | 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S') |
| | | } |
| | | except Exception as e: |
| | | logger.error(f"{self.broker_name}获取实时行情失败: {e}") |
| | | return {} |
| | | |
| | | |
| | | class GuotaiAPI(BrokerAPI): |
| | | """国泰君安API""" |
| | | |
| | | def __init__(self): |
| | | super().__init__("国泰君安") |
| | | |
| | | def connect(self, **kwargs) -> bool: |
| | | """连接API""" |
| | | try: |
| | | logger.info(f"连接{self.broker_name}API...") |
| | | # 模拟连接成功 |
| | | self.connected = True |
| | | self.client = "guotai_client" |
| | | logger.info(f"✓ {self.broker_name}API连接成功") |
| | | return True |
| | | except Exception as e: |
| | | logger.error(f"连接{self.broker_name}API失败: {e}") |
| | | return False |
| | | |
| | | def disconnect(self) -> bool: |
| | | """断开连接""" |
| | | try: |
| | | logger.info(f"断开{self.broker_name}API连接...") |
| | | # 模拟断开连接 |
| | | self.connected = False |
| | | self.client = None |
| | | logger.info(f"✓ {self.broker_name}API断开连接成功") |
| | | return True |
| | | except Exception as e: |
| | | logger.error(f"断开{self.broker_name}API连接失败: {e}") |
| | | return False |
| | | |
| | | def place_order(self, order: RealTimeOrder) -> str: |
| | | """下单""" |
| | | if not self.connected: |
| | | order.status = 'rejected' |
| | | order.message = 'Not connected' |
| | | return None |
| | | |
| | | try: |
| | | # 模拟下单 |
| | | order_id = f"GTJA_{datetime.now().strftime('%Y%m%d%H%M%S')}" |
| | | order.order_id = order_id |
| | | order.status = 'filled' |
| | | order.filled_quantity = order.quantity |
| | | order.filled_price = order.price or 100.0 |
| | | order.fill_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') |
| | | order.message = 'Success' |
| | | |
| | | logger.info(f"✓ {self.broker_name}下单成功: {order_id}") |
| | | return order_id |
| | | except Exception as e: |
| | | order.status = 'rejected' |
| | | order.message = str(e) |
| | | logger.error(f"{self.broker_name}下单失败: {e}") |
| | | return None |
| | | |
| | | def cancel_order(self, order_id: str) -> bool: |
| | | """撤单""" |
| | | try: |
| | | logger.info(f"{self.broker_name}撤单: {order_id}") |
| | | # 模拟撤单成功 |
| | | return True |
| | | except Exception as e: |
| | | logger.error(f"{self.broker_name}撤单失败: {e}") |
| | | return False |
| | | |
| | | def get_order_status(self, order_id: str) -> Dict: |
| | | """获取订单状态""" |
| | | try: |
| | | # 模拟返回订单状态 |
| | | return { |
| | | 'order_id': order_id, |
| | | 'status': 'filled', |
| | | 'message': 'Success' |
| | | } |
| | | except Exception as e: |
| | | logger.error(f"{self.broker_name}获取订单状态失败: {e}") |
| | | return {} |
| | | |
| | | def get_account_info(self) -> Dict: |
| | | """获取账户信息""" |
| | | try: |
| | | # 模拟返回账户信息 |
| | | return { |
| | | 'cash': 1000000.0, |
| | | 'total_value': 1500000.0, |
| | | 'positions_value': 500000.0, |
| | | 'pnl': 50000.0 |
| | | } |
| | | except Exception as e: |
| | | logger.error(f"{self.broker_name}获取账户信息失败: {e}") |
| | | return {} |
| | | |
| | | def get_positions(self) -> Dict: |
| | | """获取持仓信息""" |
| | | try: |
| | | # 模拟返回持仓信息 |
| | | return { |
| | | '600519': { |
| | | 'stock_code': '600519', |
| | | 'quantity': 100, |
| | | 'avg_price': 1800.0, |
| | | 'market_value': 180000.0 |
| | | } |
| | | } |
| | | except Exception as e: |
| | | logger.error(f"{self.broker_name}获取持仓信息失败: {e}") |
| | | return {} |
| | | |
| | | def get_realtime_quote(self, stock_code: str) -> Dict: |
| | | """获取实时行情""" |
| | | try: |
| | | # 模拟返回实时行情 |
| | | import random |
| | | price = 100.0 + random.uniform(-5, 5) |
| | | return { |
| | | 'stock_code': stock_code, |
| | | 'price': round(price, 2), |
| | | 'open': round(price * 0.99, 2), |
| | | 'high': round(price * 1.01, 2), |
| | | 'low': round(price * 0.98, 2), |
| | | 'volume': random.randint(100000, 1000000), |
| | | 'amount': round(price * random.randint(100000, 1000000), 2), |
| | | 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S') |
| | | } |
| | | except Exception as e: |
| | | logger.error(f"{self.broker_name}获取实时行情失败: {e}") |
| | | return {} |
| | | |
| | | |
| | | class BrokerAPIFactory: |
| | | """券商API工厂""" |
| | | |
| | | @staticmethod |
| | | def create_broker_api(broker_name: str, **kwargs) -> Optional[BrokerAPI]: |
| | | """创建券商API实例""" |
| | | broker_map = { |
| | | 'huatai': HuataiAPI, |
| | | 'citics': CITICSAPI, |
| | | 'guotai': GuotaiAPI |
| | | } |
| | | |
| | | broker_name = broker_name.lower() |
| | | if broker_name in broker_map: |
| | | return broker_map[broker_name]() |
| | | else: |
| | | logger.error(f"不支持的券商: {broker_name}") |
| | | return None |
| | | |
| | | |
| | | if __name__ == '__main__': |
| | | # 测试券商API |
| | | print("=== 券商API测试 ===") |
| | | |
| | | # 测试华泰证券API |
| | | print("\n测试华泰证券API:") |
| | | huatai_api = BrokerAPIFactory.create_broker_api('huatai') |
| | | if huatai_api: |
| | | huatai_api.connect() |
| | | print(f"账户信息: {huatai_api.get_account_info()}") |
| | | print(f"持仓信息: {huatai_api.get_positions()}") |
| | | print(f"实时行情: {huatai_api.get_realtime_quote('600519')}") |
| | | huatai_api.disconnect() |
| | | |
| | | # 测试中信证券API |
| | | print("\n测试中信证券API:") |
| | | citics_api = BrokerAPIFactory.create_broker_api('citics') |
| | | if citics_api: |
| | | citics_api.connect() |
| | | print(f"账户信息: {citics_api.get_account_info()}") |
| | | citics_api.disconnect() |
| | | |
| | | # 测试国泰君安API |
| | | print("\n测试国泰君安API:") |
| | | guotai_api = BrokerAPIFactory.create_broker_api('guotai') |
| | | if guotai_api: |
| | | guotai_api.connect() |
| | | print(f"账户信息: {guotai_api.get_account_info()}") |
| | | guotai_api.disconnect() |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | """ |
| | | 实时交易接口模块 |
| | | 支持连接券商API进行实时交易 |
| | | """ |
| | | |
| | | import time |
| | | import logging |
| | | from datetime import datetime |
| | | from typing import Dict, List, Optional, Tuple |
| | | from dataclasses import dataclass |
| | | |
| | | logging.basicConfig(level=logging.INFO) |
| | | logger = logging.getLogger(__name__) |
| | | |
| | | |
| | | @dataclass |
| | | class RealTimeOrder: |
| | | """实时订单类""" |
| | | stock_code: str |
| | | side: str # 'buy' or 'sell' |
| | | order_type: str # 'limit' or 'market' |
| | | price: Optional[float] # 限价单价格 (市价单为None) |
| | | quantity: int |
| | | order_id: str = None |
| | | status: str = 'pending' # 'pending', 'filled', 'partial', 'cancelled', 'rejected' |
| | | filled_quantity: int = 0 |
| | | filled_price: Optional[float] = None |
| | | submit_time: str = None |
| | | fill_time: str = None |
| | | message: str = '' |
| | | |
| | | def __post_init__(self): |
| | | if self.side not in ['buy', 'sell']: |
| | | raise ValueError(f"Invalid order side: {self.side}") |
| | | if self.order_type not in ['limit', 'market']: |
| | | raise ValueError(f"Invalid order type: {self.order_type}") |
| | | self.submit_time = self.submit_time or datetime.now().strftime('%Y-%m-%d %H:%M:%S') |
| | | |
| | | |
| | | class TradingAPI: |
| | | """交易API基类""" |
| | | |
| | | def __init__(self): |
| | | self.connected = False |
| | | self.account_info = {} |
| | | self.positions = {} |
| | | |
| | | def connect(self, **kwargs) -> bool: |
| | | """连接API""" |
| | | raise NotImplementedError |
| | | |
| | | def disconnect(self) -> bool: |
| | | """断开连接""" |
| | | raise NotImplementedError |
| | | |
| | | def place_order(self, order: RealTimeOrder) -> str: |
| | | """下单""" |
| | | raise NotImplementedError |
| | | |
| | | def cancel_order(self, order_id: str) -> bool: |
| | | """撤单""" |
| | | raise NotImplementedError |
| | | |
| | | def get_order_status(self, order_id: str) -> Dict: |
| | | """获取订单状态""" |
| | | raise NotImplementedError |
| | | |
| | | def get_account_info(self) -> Dict: |
| | | """获取账户信息""" |
| | | raise NotImplementedError |
| | | |
| | | def get_positions(self) -> Dict: |
| | | """获取持仓信息""" |
| | | raise NotImplementedError |
| | | |
| | | def get_realtime_quote(self, stock_code: str) -> Dict: |
| | | """获取实时行情""" |
| | | raise NotImplementedError |
| | | |
| | | |
| | | class SimulatedTradingAPI(TradingAPI): |
| | | """模拟交易API""" |
| | | |
| | | def __init__(self, initial_cash: float = 1000000.0): |
| | | super().__init__() |
| | | self.initial_cash = initial_cash |
| | | self.cash = initial_cash |
| | | self.positions = {} |
| | | self.orders = {} |
| | | self.order_counter = 0 |
| | | self.connected = False |
| | | |
| | | def connect(self, **kwargs) -> bool: |
| | | """连接API""" |
| | | logger.info("✓ 模拟交易API连接成功") |
| | | self.connected = True |
| | | return True |
| | | |
| | | def disconnect(self) -> bool: |
| | | """断开连接""" |
| | | logger.info("✓ 模拟交易API断开连接") |
| | | self.connected = False |
| | | return True |
| | | |
| | | def place_order(self, order: RealTimeOrder) -> str: |
| | | """下单""" |
| | | if not self.connected: |
| | | order.status = 'rejected' |
| | | order.message = 'Not connected' |
| | | return None |
| | | |
| | | # 生成订单ID |
| | | self.order_counter += 1 |
| | | order_id = f"ORDER_{self.order_counter:06d}" |
| | | order.order_id = order_id |
| | | |
| | | # 模拟行情数据 |
| | | quote = self.get_realtime_quote(order.stock_code) |
| | | if not quote or quote.get('price', 0) == 0: |
| | | order.status = 'rejected' |
| | | order.message = 'Price not available' |
| | | self.orders[order_id] = order |
| | | return order_id |
| | | |
| | | # 计算成交价格 |
| | | if order.order_type == 'market': |
| | | fill_price = quote['price'] |
| | | else: # limit |
| | | if order.side == 'buy' and order.price < quote['price']: |
| | | order.status = 'rejected' |
| | | order.message = 'Limit price too low' |
| | | self.orders[order_id] = order |
| | | return order_id |
| | | elif order.side == 'sell' and order.price > quote['price']: |
| | | order.status = 'rejected' |
| | | order.message = 'Limit price too high' |
| | | self.orders[order_id] = order |
| | | return order_id |
| | | fill_price = order.price |
| | | |
| | | # 检查资金或持仓 |
| | | if order.side == 'buy': |
| | | total_cost = order.quantity * fill_price |
| | | if total_cost > self.cash: |
| | | order.status = 'rejected' |
| | | order.message = 'Insufficient cash' |
| | | self.orders[order_id] = order |
| | | return order_id |
| | | else: # sell |
| | | if order.stock_code not in self.positions or self.positions[order.stock_code]['quantity'] < order.quantity: |
| | | order.status = 'rejected' |
| | | order.message = 'Insufficient position' |
| | | self.orders[order_id] = order |
| | | return order_id |
| | | |
| | | # 执行交易 |
| | | time.sleep(0.1) # 模拟交易延迟 |
| | | |
| | | if order.side == 'buy': |
| | | self.cash -= order.quantity * fill_price |
| | | if order.stock_code in self.positions: |
| | | # 更新持仓 |
| | | pos = self.positions[order.stock_code] |
| | | total_cost = pos['avg_price'] * pos['quantity'] + fill_price * order.quantity |
| | | total_quantity = pos['quantity'] + order.quantity |
| | | pos['avg_price'] = total_cost / total_quantity |
| | | pos['quantity'] = total_quantity |
| | | pos['market_value'] = total_quantity * fill_price |
| | | else: |
| | | # 新建持仓 |
| | | self.positions[order.stock_code] = { |
| | | 'stock_code': order.stock_code, |
| | | 'quantity': order.quantity, |
| | | 'avg_price': fill_price, |
| | | 'market_value': order.quantity * fill_price |
| | | } |
| | | else: # sell |
| | | self.cash += order.quantity * fill_price |
| | | pos = self.positions[order.stock_code] |
| | | pos['quantity'] -= order.quantity |
| | | if pos['quantity'] == 0: |
| | | del self.positions[order.stock_code] |
| | | else: |
| | | pos['market_value'] = pos['quantity'] * fill_price |
| | | |
| | | # 更新订单状态 |
| | | order.status = 'filled' |
| | | order.filled_quantity = order.quantity |
| | | order.filled_price = fill_price |
| | | order.fill_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S') |
| | | order.message = 'Success' |
| | | |
| | | self.orders[order_id] = order |
| | | logger.info(f"✓ 订单执行成功: {order_id} - {order.side} {order.quantity}股 {order.stock_code} @ {fill_price}") |
| | | |
| | | return order_id |
| | | |
| | | def cancel_order(self, order_id: str) -> bool: |
| | | """撤单""" |
| | | if order_id in self.orders: |
| | | order = self.orders[order_id] |
| | | if order.status == 'pending': |
| | | order.status = 'cancelled' |
| | | order.message = 'Cancelled by user' |
| | | logger.info(f"✓ 订单已撤销: {order_id}") |
| | | return True |
| | | return False |
| | | |
| | | def get_order_status(self, order_id: str) -> Dict: |
| | | """获取订单状态""" |
| | | if order_id in self.orders: |
| | | order = self.orders[order_id] |
| | | return { |
| | | 'order_id': order.order_id, |
| | | 'stock_code': order.stock_code, |
| | | 'side': order.side, |
| | | 'order_type': order.order_type, |
| | | 'price': order.price, |
| | | 'quantity': order.quantity, |
| | | 'status': order.status, |
| | | 'filled_quantity': order.filled_quantity, |
| | | 'filled_price': order.filled_price, |
| | | 'submit_time': order.submit_time, |
| | | 'fill_time': order.fill_time, |
| | | 'message': order.message |
| | | } |
| | | return {} |
| | | |
| | | def get_account_info(self) -> Dict: |
| | | """获取账户信息""" |
| | | total_value = self.cash + sum(pos['market_value'] for pos in self.positions.values()) |
| | | return { |
| | | 'cash': self.cash, |
| | | 'total_value': total_value, |
| | | 'positions_value': sum(pos['market_value'] for pos in self.positions.values()), |
| | | 'pnl': total_value - self.initial_cash |
| | | } |
| | | |
| | | def get_positions(self) -> Dict: |
| | | """获取持仓信息""" |
| | | return self.positions |
| | | |
| | | def get_realtime_quote(self, stock_code: str) -> Dict: |
| | | """获取实时行情""" |
| | | # 模拟行情数据 |
| | | import random |
| | | base_price = 100.0 |
| | | if stock_code in self.positions: |
| | | base_price = self.positions[stock_code]['avg_price'] |
| | | |
| | | price = base_price * (1 + random.uniform(-0.02, 0.02)) |
| | | price = round(price, 2) |
| | | |
| | | return { |
| | | 'stock_code': stock_code, |
| | | 'price': price, |
| | | 'open': price * (1 + random.uniform(-0.01, 0.01)), |
| | | 'high': price * (1 + random.uniform(0, 0.02)), |
| | | 'low': price * (1 - random.uniform(0, 0.02)), |
| | | 'volume': random.randint(100000, 1000000), |
| | | 'amount': price * random.randint(100000, 1000000), |
| | | 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S') |
| | | } |
| | | |
| | | |
| | | class RealTimeTrader: |
| | | """实时交易器""" |
| | | |
| | | def __init__(self, api: TradingAPI): |
| | | self.api = api |
| | | self.order_history = [] |
| | | self.position_history = [] |
| | | |
| | | def connect(self, **kwargs) -> bool: |
| | | """连接交易API""" |
| | | return self.api.connect(**kwargs) |
| | | |
| | | def disconnect(self) -> bool: |
| | | """断开连接""" |
| | | return self.api.disconnect() |
| | | |
| | | def buy(self, stock_code: str, quantity: int, price: float = None) -> str: |
| | | """买入""" |
| | | order_type = 'market' if price is None else 'limit' |
| | | order = RealTimeOrder( |
| | | stock_code=stock_code, |
| | | side='buy', |
| | | order_type=order_type, |
| | | price=price, |
| | | quantity=quantity |
| | | ) |
| | | |
| | | order_id = self.api.place_order(order) |
| | | if order_id: |
| | | self.order_history.append(order) |
| | | return order_id |
| | | |
| | | def sell(self, stock_code: str, quantity: int, price: float = None) -> str: |
| | | """卖出""" |
| | | order_type = 'market' if price is None else 'limit' |
| | | order = RealTimeOrder( |
| | | stock_code=stock_code, |
| | | side='sell', |
| | | order_type=order_type, |
| | | price=price, |
| | | quantity=quantity |
| | | ) |
| | | |
| | | order_id = self.api.place_order(order) |
| | | if order_id: |
| | | self.order_history.append(order) |
| | | return order_id |
| | | |
| | | def cancel(self, order_id: str) -> bool: |
| | | """撤单""" |
| | | return self.api.cancel_order(order_id) |
| | | |
| | | def get_order(self, order_id: str) -> Dict: |
| | | """获取订单信息""" |
| | | return self.api.get_order_status(order_id) |
| | | |
| | | def get_account(self) -> Dict: |
| | | """获取账户信息""" |
| | | return self.api.get_account_info() |
| | | |
| | | def get_positions(self) -> Dict: |
| | | """获取持仓信息""" |
| | | positions = self.api.get_positions() |
| | | self.position_history.append({ |
| | | 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), |
| | | 'positions': positions |
| | | }) |
| | | return positions |
| | | |
| | | def get_quote(self, stock_code: str) -> Dict: |
| | | """获取实时行情""" |
| | | return self.api.get_realtime_quote(stock_code) |
| | | |
| | | def check_position(self, stock_code: str) -> Optional[Dict]: |
| | | """检查持仓""" |
| | | positions = self.api.get_positions() |
| | | return positions.get(stock_code) |
| | | |
| | | def calculate_pnl(self, stock_code: str) -> float: |
| | | """计算单个股票的盈亏""" |
| | | position = self.check_position(stock_code) |
| | | if not position: |
| | | return 0.0 |
| | | |
| | | quote = self.get_quote(stock_code) |
| | | current_price = quote.get('price', position['avg_price']) |
| | | cost = position['avg_price'] * position['quantity'] |
| | | current_value = current_price * position['quantity'] |
| | | return current_value - cost |
| | | |
| | | |
| | | if __name__ == '__main__': |
| | | # 测试模拟交易API |
| | | print("=== 模拟交易API测试 ===") |
| | | |
| | | api = SimulatedTradingAPI(initial_cash=1000000) |
| | | trader = RealTimeTrader(api) |
| | | |
| | | # 连接API |
| | | trader.connect() |
| | | |
| | | # 获取账户信息 |
| | | account = trader.get_account() |
| | | print(f"初始账户信息: {account}") |
| | | |
| | | # 买入股票 |
| | | order_id1 = trader.buy('600519', 100, price=1800.0) |
| | | print(f"买入订单ID: {order_id1}") |
| | | |
| | | # 获取订单状态 |
| | | order_status = trader.get_order(order_id1) |
| | | print(f"订单状态: {order_status}") |
| | | |
| | | # 获取持仓 |
| | | positions = trader.get_positions() |
| | | print(f"持仓: {positions}") |
| | | |
| | | # 卖出股票 |
| | | order_id2 = trader.sell('600519', 50) |
| | | print(f"卖出订单ID: {order_id2}") |
| | | |
| | | # 获取账户信息 |
| | | account = trader.get_account() |
| | | print(f"最终账户信息: {account}") |
| | | |
| | | # 断开连接 |
| | | trader.disconnect() |
| | |
| | | 'min_price': 1.0, # 最低股价 |
| | | 'max_price': 3000.0, # 最高股价 |
| | | 'min_volume': 0, # 最小成交量 |
| | | 'min_amount': 1000000, # 最小成交额(100万) |
| | | 'min_amount': 1000000, # 最小成交额(100万) |
| | | 'min_data_records_per_stock': 100, # 每只股票最少记录数 |
| | | 'max_turnover_rate': 100.0, # 最大换手率(100%) |
| | | 'max_pe_ttm': 1000.0, # 最大市盈率 |
| | | 'min_pe_ttm': 0.1, # 最小市盈率 |
| | | 'max_pb': 50.0, # 最大市净率 |
| | | 'min_pb': 0.1, # 最小市净率 |
| | | 'max_roe': 100.0, # 最大ROE |
| | | 'min_roe': -50.0, # 最小ROE |
| | | } |
| | | |
| | | # 标准字段名称 |
| | |
| | | ) |
| | | |
| | | def _check_outliers(self, data: pd.DataFrame): |
| | | """检查异常值:涨跌停、不合理价格、成交量""" |
| | | """检查异常值:涨跌停、不合理价格、成交量、财务指标""" |
| | | logger.info(" 🔍 检查异常值...") |
| | | |
| | | outlier_count = 0 |
| | |
| | | if zero_volume > 0: |
| | | self.report.warnings.append(f"零成交量记录: {zero_volume} 条") |
| | | |
| | | # 检查成交额异常 |
| | | if 'amount' in data.columns: |
| | | low_amount = (data['amount'] < self.thresholds['min_amount']).sum() |
| | | if low_amount > 0: |
| | | self.report.warnings.append(f"低成交额记录 (<{self.thresholds['min_amount']}): {low_amount} 条") |
| | | |
| | | # 检查换手率异常 |
| | | if 'turnover' in data.columns or 'turnover_rate' in data.columns: |
| | | col = 'turnover' if 'turnover' in data.columns else 'turnover_rate' |
| | | high_turnover = (data[col] > self.thresholds['max_turnover_rate']).sum() |
| | | if high_turnover > 0: |
| | | outlier_count += high_turnover |
| | | self.report.issues.append(f"{col} 过高 (>{self.thresholds['max_turnover_rate']}%): {high_turnover} 条") |
| | | |
| | | # 检查财务指标异常 |
| | | if 'pe_ttm' in data.columns: |
| | | too_low_pe = (data['pe_ttm'] < self.thresholds['min_pe_ttm']).sum() |
| | | too_high_pe = (data['pe_ttm'] > self.thresholds['max_pe_ttm']).sum() |
| | | if too_low_pe > 0: |
| | | outlier_count += too_low_pe |
| | | self.report.issues.append(f"PE_TTM 过低 (<{self.thresholds['min_pe_ttm']}): {too_low_pe} 条") |
| | | if too_high_pe > 0: |
| | | outlier_count += too_high_pe |
| | | self.report.issues.append(f"PE_TTM 过高 (>{self.thresholds['max_pe_ttm']}): {too_high_pe} 条") |
| | | |
| | | if 'pb' in data.columns: |
| | | too_low_pb = (data['pb'] < self.thresholds['min_pb']).sum() |
| | | too_high_pb = (data['pb'] > self.thresholds['max_pb']).sum() |
| | | if too_low_pb > 0: |
| | | outlier_count += too_low_pb |
| | | self.report.issues.append(f"PB 过低 (<{self.thresholds['min_pb']}): {too_low_pb} 条") |
| | | if too_high_pb > 0: |
| | | outlier_count += too_high_pb |
| | | self.report.issues.append(f"PB 过高 (>{self.thresholds['max_pb']}): {too_high_pb} 条") |
| | | |
| | | if 'roe' in data.columns: |
| | | too_low_roe = (data['roe'] < self.thresholds['min_roe']).sum() |
| | | too_high_roe = (data['roe'] > self.thresholds['max_roe']).sum() |
| | | if too_low_roe > 0: |
| | | outlier_count += too_low_roe |
| | | self.report.issues.append(f"ROE 过低 (<{self.thresholds['min_roe']}%): {too_low_roe} 条") |
| | | if too_high_roe > 0: |
| | | outlier_count += too_high_roe |
| | | self.report.issues.append(f"ROE 过高 (>{self.thresholds['max_roe']}%): {too_high_roe} 条") |
| | | |
| | | self.report.outlier_records = outlier_count |
| | | |
| | | logger.info(f" 检测到 {outlier_count} 条异常记录") |
| | |
| | | return {} |
| | | |
| | | |
| | | class EastMoneyDataSource: |
| | | """东方财富数据源""" |
| | | |
| | | def __init__(self): |
| | | self.name = "EastMoney" |
| | | self.is_available = False |
| | | |
| | | def test_connection(self) -> bool: |
| | | try: |
| | | import requests |
| | | url = "http://push2.eastmoney.com/api/qt/stock/get?secid=1.600519&fields=f43,f44,f45,f46,f51,f52" |
| | | response = requests.get(url, timeout=5) |
| | | if response.status_code == 200: |
| | | data = response.json() |
| | | if 'data' in data: |
| | | self.is_available = True |
| | | logger.info(f" ✓ 东方财富连接成功") |
| | | return True |
| | | except Exception as e: |
| | | logger.warning(f" ✗ 东方财富连接失败: {e}") |
| | | return False |
| | | |
| | | def get_stock_realtime(self, code: str) -> Dict: |
| | | """获取实时数据""" |
| | | try: |
| | | import requests |
| | | # 转换代码格式 |
| | | if code.startswith('6'): |
| | | secid = f"1.{code}" |
| | | else: |
| | | secid = f"0.{code}" |
| | | |
| | | url = f"http://push2.eastmoney.com/api/qt/stock/get?secid={secid}&fields=f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13,f14,f15,f16,f17,f18,f20,f21,f22,f23,f24,f25,f26,f27,f28,f29,f30,f31,f32,f33,f34,f35,f36,f37,f38,f39,f40,f41,f42,f43,f44,f45,f46,f47,f48,f49,f50,f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61,f62,f63,f64,f65" |
| | | response = requests.get(url, timeout=5) |
| | | if response.status_code == 200: |
| | | data = response.json() |
| | | if 'data' in data: |
| | | data = data['data'] |
| | | return { |
| | | 'price': float(data.get('f2', 0)), |
| | | 'open': float(data.get('f17', 0)), |
| | | 'high': float(data.get('f15', 0)), |
| | | 'low': float(data.get('f16', 0)), |
| | | 'pre_close': float(data.get('f18', 0)), |
| | | 'change_pct': float(data.get('f3', 0)), |
| | | 'change_amt': float(data.get('f4', 0)), |
| | | 'volume': int(data.get('f5', 0)), |
| | | 'amount': float(data.get('f6', 0)), |
| | | 'turnover_rate': float(data.get('f8', 0)), |
| | | 'pe_ttm': float(data.get('f9', 0)), |
| | | 'pb': float(data.get('f23', 0)), |
| | | 'market_cap': float(data.get('f20', 0)) / 100000000 if data.get('f20') else 0 |
| | | } |
| | | except Exception as e: |
| | | logger.warning(f" 东方财富获取{code}失败: {e}") |
| | | return {} |
| | | |
| | | |
| | | class MultiSourceStockFetcher: |
| | | """多数据源股票数据获取器""" |
| | | |
| | |
| | | self.zhitu_available = False |
| | | self.tencent_available = False |
| | | self.sina_available = False |
| | | self.eastmoney_available = False |
| | | self.tushare_source = None |
| | | self.zhitu_source = None |
| | | self.tencent_source = None |
| | | self.sina_source = None |
| | | self.eastmoney_source = None |
| | | self.bs = None |
| | | self._stock_info_cache = {} |
| | | self._industry_cache = {} |
| | |
| | | |
| | | # 初始化新浪财经 |
| | | self._init_sina() |
| | | |
| | | # 初始化东方财富 |
| | | self._init_eastmoney() |
| | | |
| | | def _init_tushare(self): |
| | | """初始化Tushare数据源""" |
| | |
| | | except Exception as e: |
| | | logger.warning(f"新浪财经初始化失败: {e}") |
| | | self.sina_available = False |
| | | |
| | | def _init_eastmoney(self): |
| | | """初始化东方财富数据源""" |
| | | try: |
| | | self.eastmoney_source = EastMoneyDataSource() |
| | | self.eastmoney_available = self.eastmoney_source.test_connection() |
| | | self.metadata['sources_tested'].append({ |
| | | 'name': "EastMoney", |
| | | 'available': self.eastmoney_available |
| | | }) |
| | | except Exception as e: |
| | | logger.warning(f"东方财富初始化失败: {e}") |
| | | self.eastmoney_available = False |
| | | |
| | | def get_stock_list(self) -> pd.DataFrame: |
| | | """获取股票列表""" |
| | |
| | | except Exception as e: |
| | | logger.warning(f"新浪财经获取{code}失败: {e}") |
| | | |
| | | # 尝试东方财富 |
| | | if self.eastmoney_available and self.eastmoney_source: |
| | | try: |
| | | eastmoney_data = self.eastmoney_source.get_stock_realtime(pure_code) |
| | | if eastmoney_data.get('price', 0) > 0: |
| | | result['price'] = eastmoney_data['price'] |
| | | result['open'] = eastmoney_data['open'] |
| | | result['high'] = eastmoney_data['high'] |
| | | result['low'] = eastmoney_data['low'] |
| | | result['pre_close'] = eastmoney_data['pre_close'] |
| | | result['change_pct'] = eastmoney_data['change_pct'] |
| | | result['change_amt'] = eastmoney_data['change_amt'] |
| | | result['volume'] = eastmoney_data['volume'] |
| | | result['amount'] = eastmoney_data['amount'] |
| | | result['turnover_rate'] = eastmoney_data['turnover_rate'] |
| | | result['pe_ttm'] = eastmoney_data['pe_ttm'] |
| | | result['pb'] = eastmoney_data['pb'] |
| | | result['market_cap'] = eastmoney_data['market_cap'] |
| | | logger.info(f"✓ 东方财富获取{pure_code}成功: {result['price']}元") |
| | | # 缓存数据 |
| | | self._realtime_data_cache[cache_key] = { |
| | | 'timestamp': current_time, |
| | | 'data': result.copy() |
| | | } |
| | | return result |
| | | except Exception as e: |
| | | logger.warning(f"东方财富获取{code}失败: {e}") |
| | | |
| | | # 尝试AKShare |
| | | if self.akshare_available: |
| | | try: |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | """ |
| | | 智能资金管理系统 |
| | | 功能: |
| | | 1. 动态资金分配 |
| | | 2. 风险预算管理 |
| | | 3. 仓位调整策略 |
| | | 4. 资金使用效率优化 |
| | | """ |
| | | |
| | | import pandas as pd |
| | | import numpy as np |
| | | from typing import Dict, List, Tuple, Optional |
| | | from datetime import datetime |
| | | import json |
| | | import os |
| | | import logging |
| | | |
| | | logging.basicConfig(level=logging.INFO) |
| | | logger = logging.getLogger(__name__) |
| | | |
| | | |
| | | class FundManager: |
| | | """智能资金管理器""" |
| | | |
| | | def __init__(self, initial_capital: float, risk_budget: float = 0.15): |
| | | """ |
| | | 初始化资金管理器 |
| | | |
| | | Args: |
| | | initial_capital: 初始资金 |
| | | risk_budget: 风险预算(最大回撤限制) |
| | | """ |
| | | self.initial_capital = initial_capital |
| | | self.current_capital = initial_capital |
| | | self.risk_budget = risk_budget |
| | | self.cash = initial_capital |
| | | self.positions = {} |
| | | self.portfolio_value = initial_capital |
| | | self.risk_exposure = 0.0 |
| | | self.alpha_signals = {} |
| | | self.risk_signals = {} |
| | | self.transaction_history = [] |
| | | self.portfolio_history = [] |
| | | self.risk_history = [] |
| | | |
| | | def update_portfolio(self, prices: Dict[str, float]): |
| | | """更新投资组合价值""" |
| | | market_value = 0.0 |
| | | for stock, pos in self.positions.items(): |
| | | if stock in prices: |
| | | pos['market_value'] = pos['quantity'] * prices[stock] |
| | | market_value += pos['market_value'] |
| | | |
| | | self.portfolio_value = self.cash + market_value |
| | | self.current_capital = self.portfolio_value |
| | | |
| | | # 记录投资组合历史 |
| | | self.portfolio_history.append({ |
| | | 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), |
| | | 'portfolio_value': self.portfolio_value, |
| | | 'cash': self.cash, |
| | | 'market_value': market_value, |
| | | 'positions': {k: v['market_value'] for k, v in self.positions.items()} |
| | | }) |
| | | |
| | | def calculate_risk_exposure(self, volatility: Dict[str, float]) -> float: |
| | | """计算风险暴露""" |
| | | if not self.positions: |
| | | return 0.0 |
| | | |
| | | total_risk = 0.0 |
| | | total_value = self.portfolio_value |
| | | |
| | | for stock, pos in self.positions.items(): |
| | | weight = pos['market_value'] / total_value |
| | | stock_volatility = volatility.get(stock, 0.2) # 默认波动率20% |
| | | total_risk += weight * stock_volatility |
| | | |
| | | self.risk_exposure = total_risk |
| | | |
| | | # 记录风险历史 |
| | | self.risk_history.append({ |
| | | 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), |
| | | 'risk_exposure': total_risk |
| | | }) |
| | | |
| | | return total_risk |
| | | |
| | | def allocate_funds(self, alpha_scores: Dict[str, float], risk_scores: Dict[str, float]) -> Dict[str, float]: |
| | | """ |
| | | 基于alpha和风险分数分配资金 |
| | | |
| | | Args: |
| | | alpha_scores: 股票alpha分数 |
| | | risk_scores: 股票风险分数 |
| | | |
| | | Returns: |
| | | 资金分配比例 |
| | | """ |
| | | self.alpha_signals = alpha_scores |
| | | self.risk_signals = risk_scores |
| | | |
| | | # 计算调整后的分数 |
| | | adjusted_scores = {} |
| | | for stock, alpha in alpha_scores.items(): |
| | | risk = risk_scores.get(stock, 1.0) |
| | | adjusted_score = alpha / risk # 风险调整后的alpha |
| | | adjusted_scores[stock] = adjusted_score |
| | | |
| | | # 归一化 |
| | | total_score = sum(abs(s) for s in adjusted_scores.values()) |
| | | if total_score == 0: |
| | | return {} |
| | | |
| | | allocation = {} |
| | | for stock, score in adjusted_scores.items(): |
| | | allocation[stock] = abs(score) / total_score |
| | | |
| | | return allocation |
| | | |
| | | def adjust_positions(self, target_allocation: Dict[str, float], prices: Dict[str, float], |
| | | max_position: float = 0.15, min_position: float = 0.01): |
| | | """调整仓位""" |
| | | total_value = self.portfolio_value |
| | | |
| | | # 计算目标仓位 |
| | | target_positions = {} |
| | | for stock, weight in target_allocation.items(): |
| | | # 限制单票仓位 |
| | | weight = min(weight, max_position) |
| | | weight = max(weight, min_position) |
| | | target_positions[stock] = { |
| | | 'weight': weight, |
| | | 'target_value': total_value * weight |
| | | } |
| | | |
| | | # 计算现有仓位 |
| | | current_positions = {} |
| | | for stock, pos in self.positions.items(): |
| | | if stock in prices: |
| | | current_positions[stock] = { |
| | | 'quantity': pos['quantity'], |
| | | 'current_value': pos['quantity'] * prices[stock] |
| | | } |
| | | |
| | | # 卖出不需要的仓位 |
| | | for stock, pos in current_positions.items(): |
| | | if stock not in target_positions: |
| | | # 全部卖出 |
| | | sell_quantity = pos['quantity'] |
| | | if sell_quantity > 0: |
| | | self.sell(stock, sell_quantity, prices[stock]) |
| | | |
| | | # 调整现有仓位 |
| | | for stock, target in target_positions.items(): |
| | | if stock in current_positions: |
| | | current_value = current_positions[stock]['current_value'] |
| | | target_value = target['target_value'] |
| | | |
| | | if abs(target_value - current_value) / total_value > 0.01: # 差异超过1% |
| | | if target_value > current_value: |
| | | # 买入 |
| | | buy_amount = target_value - current_value |
| | | buy_quantity = int(buy_amount / prices[stock] / 100) * 100 |
| | | if buy_quantity > 0: |
| | | self.buy(stock, buy_quantity, prices[stock]) |
| | | else: |
| | | # 卖出 |
| | | sell_amount = current_value - target_value |
| | | current_quantity = current_positions[stock]['quantity'] |
| | | sell_quantity = int(sell_amount / prices[stock] / 100) * 100 |
| | | sell_quantity = min(sell_quantity, current_quantity) |
| | | if sell_quantity > 0: |
| | | self.sell(stock, sell_quantity, prices[stock]) |
| | | else: |
| | | # 新建仓位 |
| | | target_value = target['target_value'] |
| | | buy_quantity = int(target_value / prices[stock] / 100) * 100 |
| | | if buy_quantity > 0: |
| | | self.buy(stock, buy_quantity, prices[stock]) |
| | | |
| | | def buy(self, stock: str, quantity: int, price: float): |
| | | """买入股票""" |
| | | total_cost = quantity * price |
| | | if total_cost > self.cash: |
| | | logger.warning(f"资金不足,无法买入 {stock} {quantity}股 @ {price}") |
| | | return |
| | | |
| | | self.cash -= total_cost |
| | | |
| | | if stock in self.positions: |
| | | # 更新持仓 |
| | | pos = self.positions[stock] |
| | | total_cost = pos['avg_price'] * pos['quantity'] + total_cost |
| | | total_quantity = pos['quantity'] + quantity |
| | | pos['avg_price'] = total_cost / total_quantity |
| | | pos['quantity'] = total_quantity |
| | | pos['market_value'] = total_quantity * price |
| | | else: |
| | | # 新建持仓 |
| | | self.positions[stock] = { |
| | | 'quantity': quantity, |
| | | 'avg_price': price, |
| | | 'market_value': quantity * price |
| | | } |
| | | |
| | | # 记录交易 |
| | | self.transaction_history.append({ |
| | | 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), |
| | | 'type': 'buy', |
| | | 'stock': stock, |
| | | 'quantity': quantity, |
| | | 'price': price, |
| | | 'amount': total_cost |
| | | }) |
| | | |
| | | logger.info(f"买入: {stock} {quantity}股 @ {price},总成本: {total_cost}") |
| | | |
| | | def sell(self, stock: str, quantity: int, price: float): |
| | | """卖出股票""" |
| | | if stock not in self.positions: |
| | | logger.warning(f"没有{stock}的持仓") |
| | | return |
| | | |
| | | pos = self.positions[stock] |
| | | if quantity > pos['quantity']: |
| | | logger.warning(f"卖出数量超过持仓数量") |
| | | quantity = pos['quantity'] |
| | | |
| | | total_proceeds = quantity * price |
| | | self.cash += total_proceeds |
| | | |
| | | pos['quantity'] -= quantity |
| | | pos['market_value'] = pos['quantity'] * price |
| | | |
| | | if pos['quantity'] == 0: |
| | | del self.positions[stock] |
| | | |
| | | # 记录交易 |
| | | self.transaction_history.append({ |
| | | 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), |
| | | 'type': 'sell', |
| | | 'stock': stock, |
| | | 'quantity': quantity, |
| | | 'price': price, |
| | | 'amount': total_proceeds |
| | | }) |
| | | |
| | | logger.info(f"卖出: {stock} {quantity}股 @ {price},总收入: {total_proceeds}") |
| | | |
| | | def rebalance_based_on_risk(self, volatility: Dict[str, float], target_risk: float = 0.15): |
| | | """基于风险重新平衡""" |
| | | current_risk = self.calculate_risk_exposure(volatility) |
| | | |
| | | if current_risk > target_risk: |
| | | # 需要降低风险 |
| | | reduction_ratio = target_risk / current_risk |
| | | total_value = self.portfolio_value |
| | | |
| | | # 计算需要卖出的金额 |
| | | target_market_value = total_value * (1 - self.cash / total_value) * reduction_ratio |
| | | current_market_value = total_value - self.cash |
| | | sell_amount = current_market_value - target_market_value |
| | | |
| | | if sell_amount > 0: |
| | | # 按风险比例卖出 |
| | | risk_contributions = {} |
| | | for stock, pos in self.positions.items(): |
| | | weight = pos['market_value'] / current_market_value |
| | | stock_volatility = volatility.get(stock, 0.2) |
| | | risk_contributions[stock] = weight * stock_volatility |
| | | |
| | | total_risk_contribution = sum(risk_contributions.values()) |
| | | |
| | | for stock, contribution in risk_contributions.items(): |
| | | if stock in volatility: |
| | | sell_weight = (contribution / total_risk_contribution) * sell_amount |
| | | pos = self.positions[stock] |
| | | sell_quantity = int(sell_weight / volatility[stock] / 100) * 100 |
| | | if sell_quantity > 0: |
| | | self.sell(stock, sell_quantity, volatility[stock]) |
| | | |
| | | def generate_fund_report(self) -> Dict: |
| | | """生成资金管理报告""" |
| | | total_value = self.portfolio_value |
| | | market_value = total_value - self.cash |
| | | cash_ratio = self.cash / total_value |
| | | |
| | | position_details = {} |
| | | for stock, pos in self.positions.items(): |
| | | position_details[stock] = { |
| | | 'quantity': pos['quantity'], |
| | | 'avg_price': pos['avg_price'], |
| | | 'current_value': pos['market_value'], |
| | | 'weight': pos['market_value'] / total_value |
| | | } |
| | | |
| | | # 计算绩效 |
| | | total_return = (total_value / self.initial_capital) - 1 |
| | | |
| | | # 计算最大回撤 |
| | | max_drawdown = 0.0 |
| | | if self.portfolio_history: |
| | | values = [h['portfolio_value'] for h in self.portfolio_history] |
| | | peak = values[0] |
| | | for val in values[1:]: |
| | | if val > peak: |
| | | peak = val |
| | | drawdown = (peak - val) / peak |
| | | if drawdown > max_drawdown: |
| | | max_drawdown = drawdown |
| | | |
| | | report = { |
| | | 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), |
| | | 'initial_capital': self.initial_capital, |
| | | 'current_capital': self.current_capital, |
| | | 'total_return': total_return, |
| | | 'max_drawdown': max_drawdown, |
| | | 'cash': self.cash, |
| | | 'cash_ratio': cash_ratio, |
| | | 'market_value': market_value, |
| | | 'positions': position_details, |
| | | 'risk_exposure': self.risk_exposure, |
| | | 'transaction_count': len(self.transaction_history) |
| | | } |
| | | |
| | | return report |
| | | |
| | | def save_report(self, output_dir: str = '/Users/variya/.openclaw/workspace/projects/a-stock-advisor/reports'): |
| | | """保存报告""" |
| | | os.makedirs(output_dir, exist_ok=True) |
| | | |
| | | timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') |
| | | report = self.generate_fund_report() |
| | | |
| | | # 保存JSON报告 |
| | | json_path = os.path.join(output_dir, f'fund_management_{timestamp}.json') |
| | | with open(json_path, 'w', encoding='utf-8') as f: |
| | | json.dump(report, f, indent=2, ensure_ascii=False, default=str) |
| | | |
| | | # 生成Markdown报告 |
| | | md_report = self._generate_markdown_report(report) |
| | | md_path = os.path.join(output_dir, f'fund_management_{timestamp}.md') |
| | | with open(md_path, 'w', encoding='utf-8') as f: |
| | | f.write(md_report) |
| | | |
| | | logger.info(f"报告已保存: {json_path}") |
| | | logger.info(f"Markdown报告已保存: {md_path}") |
| | | |
| | | return json_path |
| | | |
| | | def _generate_markdown_report(self, report: Dict) -> str: |
| | | """生成Markdown报告""" |
| | | lines = [] |
| | | |
| | | lines.append("# 资金管理报告\n") |
| | | lines.append(f"**生成时间:** {report['timestamp']}\n") |
| | | lines.append("---\n") |
| | | |
| | | # 基本信息 |
| | | lines.append("## 📊 基本信息\n") |
| | | lines.append(f"- **初始资金:** ¥{report['initial_capital']:,.2f}\n") |
| | | lines.append(f"- **当前资金:** ¥{report['current_capital']:,.2f}\n") |
| | | lines.append(f"- **总收益率:** {report['total_return']:.2%}\n") |
| | | lines.append(f"- **最大回撤:** {report['max_drawdown']:.2%}\n") |
| | | lines.append(f"- **现金比例:** {report['cash_ratio']:.2%}\n") |
| | | lines.append(f"- **风险暴露:** {report['risk_exposure']:.2%}\n") |
| | | lines.append(f"- **交易次数:** {report['transaction_count']}\n\n") |
| | | |
| | | # 持仓详情 |
| | | lines.append("## 📈 持仓详情\n") |
| | | if report['positions']: |
| | | lines.append("| 股票 | 数量 | 成本价 | 当前价值 | 权重 |\n") |
| | | lines.append("|------|------|--------|----------|------|\n") |
| | | for stock, details in report['positions'].items(): |
| | | lines.append(f"| {stock} | {details['quantity']} | {details['avg_price']:.2f} | {details['current_value']:,.2f} | {details['weight']:.2%} |\n") |
| | | else: |
| | | lines.append("无持仓\n") |
| | | lines.append("\n") |
| | | |
| | | # 风险分析 |
| | | lines.append("## 🛡️ 风险分析\n") |
| | | lines.append(f"- **当前风险暴露:** {report['risk_exposure']:.2%}\n") |
| | | lines.append(f"- **风险预算:** {self.risk_budget:.2%}\n") |
| | | |
| | | if report['risk_exposure'] > self.risk_budget: |
| | | lines.append("- **风险状态:** ⚠️ 超出风险预算\n") |
| | | else: |
| | | lines.append("- **风险状态:** ✅ 在风险预算内\n") |
| | | lines.append("\n") |
| | | |
| | | # 交易历史 |
| | | lines.append("## 💱 最近交易\n") |
| | | if self.transaction_history: |
| | | recent_transactions = self.transaction_history[-10:] # 最近10笔交易 |
| | | for tx in reversed(recent_transactions): |
| | | lines.append(f"- {tx['timestamp']}: {tx['type']} {tx['stock']} {tx['quantity']}股 @ {tx['price']} - ¥{tx['amount']:,.2f}\n") |
| | | else: |
| | | lines.append("无交易记录\n") |
| | | lines.append("\n") |
| | | |
| | | lines.append("---\n") |
| | | lines.append("\n## 📋 总结\n\n") |
| | | lines.append("本报告提供了资金管理的详细信息,包括资产配置、风险暴露和交易历史。\n") |
| | | |
| | | return '\n'.join(lines) |
| | | |
| | | |
| | | class RiskBudgetManager: |
| | | """风险预算管理器""" |
| | | |
| | | def __init__(self, total_risk_budget: float = 0.15): |
| | | """ |
| | | 初始化风险预算管理器 |
| | | |
| | | Args: |
| | | total_risk_budget: 总风险预算(最大回撤限制) |
| | | """ |
| | | self.total_risk_budget = total_risk_budget |
| | | self.factor_risk_budgets = {} |
| | | self.sector_risk_budgets = {} |
| | | self.stock_risk_budgets = {} |
| | | self.risk_allocation = {} |
| | | |
| | | def set_factor_risk_budgets(self, factor_budgets: Dict[str, float]): |
| | | """设置因子风险预算""" |
| | | self.factor_risk_budgets = factor_budgets |
| | | |
| | | def set_sector_risk_budgets(self, sector_budgets: Dict[str, float]): |
| | | """设置行业风险预算""" |
| | | self.sector_risk_budgets = sector_budgets |
| | | |
| | | def set_stock_risk_budgets(self, stock_budgets: Dict[str, float]): |
| | | """设置个股风险预算""" |
| | | self.stock_risk_budgets = stock_budgets |
| | | |
| | | def allocate_risk(self, factor_exposures: Dict[str, float], |
| | | sector_exposures: Dict[str, float], |
| | | stock_volatilities: Dict[str, float]) -> Dict: |
| | | """ |
| | | 分配风险预算 |
| | | |
| | | Args: |
| | | factor_exposures: 因子暴露 |
| | | sector_exposures: 行业暴露 |
| | | stock_volatilities: 个股波动率 |
| | | |
| | | Returns: |
| | | 风险分配方案 |
| | | """ |
| | | # 计算因子风险贡献 |
| | | factor_risk = {} |
| | | total_factor_exposure = sum(abs(v) for v in factor_exposures.values()) |
| | | if total_factor_exposure > 0: |
| | | for factor, exposure in factor_exposures.items(): |
| | | budget = self.factor_risk_budgets.get(factor, 0.05) |
| | | factor_risk[factor] = budget * abs(exposure) / total_factor_exposure |
| | | |
| | | # 计算行业风险贡献 |
| | | sector_risk = {} |
| | | total_sector_exposure = sum(abs(v) for v in sector_exposures.values()) |
| | | if total_sector_exposure > 0: |
| | | for sector, exposure in sector_exposures.items(): |
| | | budget = self.sector_risk_budgets.get(sector, 0.10) |
| | | sector_risk[sector] = budget * abs(exposure) / total_sector_exposure |
| | | |
| | | # 计算个股风险贡献 |
| | | stock_risk = {} |
| | | total_volatility = sum(stock_volatilities.values()) |
| | | if total_volatility > 0: |
| | | for stock, volatility in stock_volatilities.items(): |
| | | budget = self.stock_risk_budgets.get(stock, 0.02) |
| | | stock_risk[stock] = budget * volatility / total_volatility |
| | | |
| | | # 综合风险分配 |
| | | self.risk_allocation = { |
| | | 'factor_risk': factor_risk, |
| | | 'sector_risk': sector_risk, |
| | | 'stock_risk': stock_risk, |
| | | 'total_risk_budget': self.total_risk_budget |
| | | } |
| | | |
| | | return self.risk_allocation |
| | | |
| | | def check_risk_limits(self, current_exposures: Dict[str, float], |
| | | risk_type: str = 'factor') -> Dict[str, bool]: |
| | | """ |
| | | 检查风险限制 |
| | | |
| | | Args: |
| | | current_exposures: 当前暴露 |
| | | risk_type: 风险类型 ('factor', 'sector', 'stock') |
| | | |
| | | Returns: |
| | | 风险限制检查结果 |
| | | """ |
| | | checks = {} |
| | | |
| | | if risk_type == 'factor': |
| | | budgets = self.factor_risk_budgets |
| | | elif risk_type == 'sector': |
| | | budgets = self.sector_risk_budgets |
| | | else: # stock |
| | | budgets = self.stock_risk_budgets |
| | | |
| | | for item, exposure in current_exposures.items(): |
| | | budget = budgets.get(item, 0.05) |
| | | checks[item] = abs(exposure) <= budget |
| | | |
| | | return checks |
| | | |
| | | def generate_risk_budget_report(self) -> Dict: |
| | | """生成风险预算报告""" |
| | | report = { |
| | | 'total_risk_budget': self.total_risk_budget, |
| | | 'factor_risk_budgets': self.factor_risk_budgets, |
| | | 'sector_risk_budgets': self.sector_risk_budgets, |
| | | 'stock_risk_budgets': self.stock_risk_budgets, |
| | | 'risk_allocation': self.risk_allocation, |
| | | 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S') |
| | | } |
| | | |
| | | return report |
| | | |
| | | |
| | | if __name__ == '__main__': |
| | | # 测试资金管理器 |
| | | print("=== 资金管理器测试 ===") |
| | | |
| | | # 初始化资金管理器 |
| | | fund_manager = FundManager(initial_capital=1000000, risk_budget=0.15) |
| | | |
| | | # 模拟价格 |
| | | prices = { |
| | | '600519': 1800.0, |
| | | '000858': 160.0, |
| | | '000333': 60.0, |
| | | '601318': 45.0, |
| | | '600036': 35.0 |
| | | } |
| | | |
| | | # 模拟alpha和风险分数 |
| | | alpha_scores = { |
| | | '600519': 0.8, |
| | | '000858': 0.7, |
| | | '000333': 0.6, |
| | | '601318': 0.5, |
| | | '600036': 0.4 |
| | | } |
| | | |
| | | risk_scores = { |
| | | '600519': 1.2, |
| | | '000858': 1.1, |
| | | '000333': 0.9, |
| | | '601318': 0.8, |
| | | '600036': 0.7 |
| | | } |
| | | |
| | | # 分配资金 |
| | | allocation = fund_manager.allocate_funds(alpha_scores, risk_scores) |
| | | print(f"资金分配: {allocation}") |
| | | |
| | | # 调整仓位 |
| | | fund_manager.adjust_positions(allocation, prices) |
| | | |
| | | # 更新投资组合 |
| | | fund_manager.update_portfolio(prices) |
| | | |
| | | # 生成报告 |
| | | report = fund_manager.generate_fund_report() |
| | | print(f"总收益率: {report['total_return']:.2%}") |
| | | print(f"风险暴露: {report['risk_exposure']:.2%}") |
| | | |
| | | # 保存报告 |
| | | fund_manager.save_report() |
| | | |
| | | # 测试风险预算管理器 |
| | | print("\n=== 风险预算管理器测试 ===") |
| | | |
| | | risk_budget_manager = RiskBudgetManager(total_risk_budget=0.15) |
| | | |
| | | # 设置因子风险预算 |
| | | factor_budgets = { |
| | | 'value': 0.05, |
| | | 'momentum': 0.04, |
| | | 'quality': 0.03, |
| | | 'size': 0.02 |
| | | } |
| | | risk_budget_manager.set_factor_risk_budgets(factor_budgets) |
| | | |
| | | # 设置行业风险预算 |
| | | sector_budgets = { |
| | | '银行': 0.10, |
| | | '医药': 0.08, |
| | | '消费': 0.07, |
| | | '科技': 0.10 |
| | | } |
| | | risk_budget_manager.set_sector_risk_budgets(sector_budgets) |
| | | |
| | | # 模拟暴露 |
| | | factor_exposures = { |
| | | 'value': 0.6, |
| | | 'momentum': 0.4, |
| | | 'quality': 0.3, |
| | | 'size': -0.2 |
| | | } |
| | | |
| | | sector_exposures = { |
| | | '银行': 0.3, |
| | | '医药': 0.2, |
| | | '消费': 0.25, |
| | | '科技': 0.25 |
| | | } |
| | | |
| | | stock_volatilities = { |
| | | '600519': 0.25, |
| | | '000858': 0.20, |
| | | '000333': 0.18, |
| | | '601318': 0.15, |
| | | '600036': 0.12 |
| | | } |
| | | |
| | | # 分配风险 |
| | | risk_allocation = risk_budget_manager.allocate_risk(factor_exposures, sector_exposures, stock_volatilities) |
| | | print(f"风险分配: {risk_allocation}") |
| | | |
| | | # 检查风险限制 |
| | | factor_checks = risk_budget_manager.check_risk_limits(factor_exposures, 'factor') |
| | | print(f"因子风险检查: {factor_checks}") |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | """ |
| | | 市场微观结构模型 |
| | | 功能: |
| | | 1. 订单簿建模 |
| | | 2. 流动性分析 |
| | | 3. 价格冲击模型 |
| | | 4. 市场深度分析 |
| | | 5. 交易成本估算 |
| | | """ |
| | | |
| | | import pandas as pd |
| | | import numpy as np |
| | | from typing import Dict, List, Optional, Tuple |
| | | from dataclasses import dataclass |
| | | import logging |
| | | from datetime import datetime |
| | | |
| | | logging.basicConfig(level=logging.INFO) |
| | | logger = logging.getLogger(__name__) |
| | | |
| | | |
| | | @dataclass |
| | | class OrderBookLevel: |
| | | """订单簿层级""" |
| | | price: float |
| | | size: int |
| | | total_size: int = 0 |
| | | |
| | | |
| | | class OrderBook: |
| | | """订单簿模型""" |
| | | |
| | | def __init__(self, symbol: str): |
| | | self.symbol = symbol |
| | | self.bids: List[OrderBookLevel] = [] # 买单 |
| | | self.asks: List[OrderBookLevel] = [] # 卖单 |
| | | self.timestamp: Optional[datetime] = None |
| | | |
| | | def update(self, bids: List[Tuple[float, int]], asks: List[Tuple[float, int]], timestamp: datetime): |
| | | """更新订单簿""" |
| | | # 按价格排序 |
| | | self.bids = [] |
| | | total_bid_size = 0 |
| | | for price, size in sorted(bids, key=lambda x: -x[0]): |
| | | total_bid_size += size |
| | | self.bids.append(OrderBookLevel(price=price, size=size, total_size=total_bid_size)) |
| | | |
| | | self.asks = [] |
| | | total_ask_size = 0 |
| | | for price, size in sorted(asks, key=lambda x: x[0]): |
| | | total_ask_size += size |
| | | self.asks.append(OrderBookLevel(price=price, size=size, total_size=total_ask_size)) |
| | | |
| | | self.timestamp = timestamp |
| | | |
| | | def get_bid_price(self, level: int = 0) -> float: |
| | | """获取买单价格""" |
| | | if len(self.bids) > level: |
| | | return self.bids[level].price |
| | | return 0.0 |
| | | |
| | | def get_ask_price(self, level: int = 0) -> float: |
| | | """获取卖单价格""" |
| | | if len(self.asks) > level: |
| | | return self.asks[level].price |
| | | return 0.0 |
| | | |
| | | def get_spread(self) -> float: |
| | | """获取买卖价差""" |
| | | bid = self.get_bid_price() |
| | | ask = self.get_ask_price() |
| | | if bid > 0 and ask > 0: |
| | | return ask - bid |
| | | return 0.0 |
| | | |
| | | def get_mid_price(self) -> float: |
| | | """获取中间价""" |
| | | bid = self.get_bid_price() |
| | | ask = self.get_ask_price() |
| | | if bid > 0 and ask > 0: |
| | | return (bid + ask) / 2 |
| | | return 0.0 |
| | | |
| | | def get_market_depth(self, side: str, depth: int = 5) -> Dict: |
| | | """获取市场深度""" |
| | | if side == 'bid': |
| | | levels = self.bids[:depth] |
| | | else: |
| | | levels = self.asks[:depth] |
| | | |
| | | depth_data = {} |
| | | for i, level in enumerate(levels): |
| | | depth_data[f'level_{i+1}'] = { |
| | | 'price': level.price, |
| | | 'size': level.size, |
| | | 'total_size': level.total_size |
| | | } |
| | | |
| | | return depth_data |
| | | |
| | | def estimate_execution_cost(self, order_size: int, side: str) -> Tuple[float, float]: |
| | | """估算执行成本 |
| | | |
| | | Args: |
| | | order_size: 订单大小 |
| | | side: 'buy' 或 'sell' |
| | | |
| | | Returns: |
| | | (执行价格, 价格冲击) |
| | | """ |
| | | if side == 'buy': |
| | | levels = self.asks |
| | | base_price = self.get_bid_price() |
| | | else: |
| | | levels = self.bids |
| | | base_price = self.get_ask_price() |
| | | |
| | | if not levels or base_price == 0: |
| | | return 0.0, 0.0 |
| | | |
| | | remaining_size = order_size |
| | | total_cost = 0.0 |
| | | |
| | | for level in levels: |
| | | if remaining_size <= 0: |
| | | break |
| | | |
| | | execute_size = min(remaining_size, level.size) |
| | | total_cost += execute_size * level.price |
| | | remaining_size -= execute_size |
| | | |
| | | if order_size - remaining_size > 0: |
| | | avg_price = total_cost / (order_size - remaining_size) |
| | | price_impact = avg_price - base_price if side == 'buy' else base_price - avg_price |
| | | return avg_price, price_impact |
| | | |
| | | return 0.0, 0.0 |
| | | |
| | | |
| | | class LiquidityAnalyzer: |
| | | """流动性分析器""" |
| | | |
| | | def __init__(self): |
| | | self.order_books = {} |
| | | |
| | | def add_order_book(self, symbol: str, order_book: OrderBook): |
| | | """添加订单簿""" |
| | | self.order_books[symbol] = order_book |
| | | |
| | | def get_liquidity_metrics(self, symbol: str) -> Dict: |
| | | """获取流动性指标""" |
| | | if symbol not in self.order_books: |
| | | return {} |
| | | |
| | | order_book = self.order_books[symbol] |
| | | |
| | | # 买卖价差 |
| | | spread = order_book.get_spread() |
| | | mid_price = order_book.get_mid_price() |
| | | |
| | | # 相对价差 |
| | | relative_spread = spread / mid_price if mid_price > 0 else 0 |
| | | |
| | | # 市场深度 |
| | | bid_depth = sum(level.size for level in order_book.bids[:5]) |
| | | ask_depth = sum(level.size for level in order_book.asks[:5]) |
| | | total_depth = bid_depth + ask_depth |
| | | |
| | | # 深度加权平均价格 |
| | | bid_weighted_price = 0.0 |
| | | ask_weighted_price = 0.0 |
| | | |
| | | if bid_depth > 0: |
| | | bid_weighted_price = sum(level.price * level.size for level in order_book.bids[:5]) / bid_depth |
| | | |
| | | if ask_depth > 0: |
| | | ask_weighted_price = sum(level.price * level.size for level in order_book.asks[:5]) / ask_depth |
| | | |
| | | return { |
| | | 'symbol': symbol, |
| | | 'timestamp': order_book.timestamp, |
| | | 'spread': spread, |
| | | 'relative_spread': relative_spread, |
| | | 'mid_price': mid_price, |
| | | 'bid_depth': bid_depth, |
| | | 'ask_depth': ask_depth, |
| | | 'total_depth': total_depth, |
| | | 'bid_weighted_price': bid_weighted_price, |
| | | 'ask_weighted_price': ask_weighted_price |
| | | } |
| | | |
| | | def analyze_market_liquidity(self, symbols: List[str]) -> pd.DataFrame: |
| | | """分析多个股票的流动性""" |
| | | metrics = [] |
| | | |
| | | for symbol in symbols: |
| | | metric = self.get_liquidity_metrics(symbol) |
| | | if metric: |
| | | metrics.append(metric) |
| | | |
| | | return pd.DataFrame(metrics) |
| | | |
| | | |
| | | class PriceImpactModel: |
| | | """价格冲击模型""" |
| | | |
| | | def __init__(self, model_type: str = 'linear'): |
| | | self.model_type = model_type |
| | | self.params = {} |
| | | |
| | | def fit(self, order_sizes: List[int], price_impacts: List[float]): |
| | | """拟合价格冲击模型""" |
| | | X = np.array(order_sizes).reshape(-1, 1) |
| | | y = np.array(price_impacts) |
| | | |
| | | if self.model_type == 'linear': |
| | | # 线性模型: impact = a * size |
| | | from sklearn.linear_model import LinearRegression |
| | | model = LinearRegression() |
| | | model.fit(X, y) |
| | | self.params['slope'] = model.coef_[0] |
| | | self.params['intercept'] = model.intercept_ |
| | | elif self.model_type == 'power': |
| | | # 幂律模型: impact = a * size^b |
| | | X_log = np.log(X + 1e-6) |
| | | y_log = np.log(y + 1e-6) |
| | | from sklearn.linear_model import LinearRegression |
| | | model = LinearRegression() |
| | | model.fit(X_log, y_log) |
| | | self.params['slope'] = model.coef_[0] |
| | | self.params['intercept'] = model.intercept_ |
| | | |
| | | def predict(self, order_size: int) -> float: |
| | | """预测价格冲击""" |
| | | if not self.params: |
| | | return 0.0 |
| | | |
| | | if self.model_type == 'linear': |
| | | return self.params['slope'] * order_size + self.params['intercept'] |
| | | elif self.model_type == 'power': |
| | | return np.exp(self.params['intercept']) * (order_size ** self.params['slope']) |
| | | |
| | | return 0.0 |
| | | |
| | | |
| | | class MarketMicrostructureModel: |
| | | """市场微观结构模型""" |
| | | |
| | | def __init__(self): |
| | | self.order_books = {} |
| | | self.liquidity_analyzer = LiquidityAnalyzer() |
| | | self.price_impact_models = {} |
| | | |
| | | def update_order_book(self, symbol: str, bids: List[Tuple[float, int]], |
| | | asks: List[Tuple[float, int]], timestamp: datetime): |
| | | """更新订单簿""" |
| | | if symbol not in self.order_books: |
| | | self.order_books[symbol] = OrderBook(symbol) |
| | | |
| | | order_book = self.order_books[symbol] |
| | | order_book.update(bids, asks, timestamp) |
| | | self.liquidity_analyzer.add_order_book(symbol, order_book) |
| | | |
| | | def get_order_book(self, symbol: str) -> Optional[OrderBook]: |
| | | """获取订单簿""" |
| | | return self.order_books.get(symbol) |
| | | |
| | | def get_liquidity_metrics(self, symbol: str) -> Dict: |
| | | """获取流动性指标""" |
| | | return self.liquidity_analyzer.get_liquidity_metrics(symbol) |
| | | |
| | | def estimate_execution_cost(self, symbol: str, order_size: int, side: str) -> Tuple[float, float]: |
| | | """估算执行成本""" |
| | | order_book = self.get_order_book(symbol) |
| | | if order_book: |
| | | return order_book.estimate_execution_cost(order_size, side) |
| | | return 0.0, 0.0 |
| | | |
| | | def train_price_impact_model(self, symbol: str, order_sizes: List[int], |
| | | price_impacts: List[float], model_type: str = 'linear'): |
| | | """训练价格冲击模型""" |
| | | model = PriceImpactModel(model_type) |
| | | model.fit(order_sizes, price_impacts) |
| | | self.price_impact_models[symbol] = model |
| | | |
| | | def predict_price_impact(self, symbol: str, order_size: int) -> float: |
| | | """预测价格冲击""" |
| | | if symbol in self.price_impact_models: |
| | | return self.price_impact_models[symbol].predict(order_size) |
| | | return 0.0 |
| | | |
| | | def generate_market_depth_report(self, symbol: str) -> Dict: |
| | | """生成市场深度报告""" |
| | | order_book = self.get_order_book(symbol) |
| | | if not order_book: |
| | | return {} |
| | | |
| | | report = { |
| | | 'symbol': symbol, |
| | | 'timestamp': order_book.timestamp, |
| | | 'spread': order_book.get_spread(), |
| | | 'mid_price': order_book.get_mid_price(), |
| | | 'bid_depth': order_book.get_market_depth('bid'), |
| | | 'ask_depth': order_book.get_market_depth('ask') |
| | | } |
| | | |
| | | return report |
| | | |
| | | |
| | | class TradingCostEstimator: |
| | | """交易成本估算器""" |
| | | |
| | | def __init__(self): |
| | | self.microstructure_model = MarketMicrostructureModel() |
| | | self.fixed_cost_per_trade = 5.0 # 固定交易成本 |
| | | self.fee_rate = 0.0003 # 交易费率 |
| | | |
| | | def estimate_cost(self, symbol: str, order_size: int, side: str, |
| | | price: Optional[float] = None) -> Dict: |
| | | """估算交易成本""" |
| | | # 估算执行价格和价格冲击 |
| | | exec_price, price_impact = self.microstructure_model.estimate_execution_cost( |
| | | symbol, order_size, side |
| | | ) |
| | | |
| | | if price is None: |
| | | order_book = self.microstructure_model.get_order_book(symbol) |
| | | if order_book: |
| | | price = exec_price or order_book.get_mid_price() |
| | | else: |
| | | price = exec_price or 0.0 |
| | | |
| | | # 计算总成本 |
| | | total_value = order_size * price |
| | | fee_cost = total_value * self.fee_rate |
| | | impact_cost = order_size * price_impact |
| | | total_cost = self.fixed_cost_per_trade + fee_cost + impact_cost |
| | | |
| | | return { |
| | | 'symbol': symbol, |
| | | 'order_size': order_size, |
| | | 'side': side, |
| | | 'price': price, |
| | | 'exec_price': exec_price, |
| | | 'price_impact': price_impact, |
| | | 'fixed_cost': self.fixed_cost_per_trade, |
| | | 'fee_cost': fee_cost, |
| | | 'impact_cost': impact_cost, |
| | | 'total_cost': total_cost, |
| | | 'cost_percentage': (total_cost / total_value) * 100 if total_value > 0 else 0 |
| | | } |
| | | |
| | | def compare_trading_strategies(self, symbol: str, total_size: int, |
| | | strategies: List[Dict]) -> List[Dict]: |
| | | """比较不同交易策略的成本""" |
| | | results = [] |
| | | |
| | | for strategy in strategies: |
| | | if strategy['type'] == 'one_shot': |
| | | # 一次性下单 |
| | | cost = self.estimate_cost(symbol, total_size, strategy['side']) |
| | | results.append({ |
| | | 'strategy': 'one_shot', |
| | | 'total_cost': cost['total_cost'], |
| | | 'cost_percentage': cost['cost_percentage'], |
| | | 'details': cost |
| | | }) |
| | | elif strategy['type'] == 'iceberg': |
| | | # 冰山订单 |
| | | slice_size = strategy.get('slice_size', total_size // 5) |
| | | slices = (total_size + slice_size - 1) // slice_size |
| | | total_cost = 0.0 |
| | | total_value = 0.0 |
| | | |
| | | for i in range(slices): |
| | | current_size = min(slice_size, total_size - i * slice_size) |
| | | cost = self.estimate_cost(symbol, current_size, strategy['side']) |
| | | total_cost += cost['total_cost'] |
| | | total_value += current_size * cost['price'] |
| | | |
| | | cost_percentage = (total_cost / total_value) * 100 if total_value > 0 else 0 |
| | | results.append({ |
| | | 'strategy': 'iceberg', |
| | | 'slice_size': slice_size, |
| | | 'slices': slices, |
| | | 'total_cost': total_cost, |
| | | 'cost_percentage': cost_percentage |
| | | }) |
| | | |
| | | return results |
| | | |
| | | |
| | | if __name__ == '__main__': |
| | | print("=== 市场微观结构模型测试 ===") |
| | | |
| | | # 创建市场微观结构模型 |
| | | msm = MarketMicrostructureModel() |
| | | |
| | | # 模拟订单簿数据 |
| | | symbol = '600519' |
| | | bids = [(1799.0, 100), (1798.5, 200), (1798.0, 300), (1797.5, 400), (1797.0, 500)] |
| | | asks = [(1801.0, 100), (1801.5, 200), (1802.0, 300), (1802.5, 400), (1803.0, 500)] |
| | | |
| | | # 更新订单簿 |
| | | msm.update_order_book(symbol, bids, asks, datetime.now()) |
| | | |
| | | # 获取流动性指标 |
| | | liquidity = msm.get_liquidity_metrics(symbol) |
| | | print("\n流动性指标:") |
| | | for key, value in liquidity.items(): |
| | | print(f"{key}: {value}") |
| | | |
| | | # 估算执行成本 |
| | | exec_price, impact = msm.estimate_execution_cost(symbol, 500, 'buy') |
| | | print(f"\n执行成本估算 (买入500股):") |
| | | print(f"执行价格: {exec_price:.2f}") |
| | | print(f"价格冲击: {impact:.2f}") |
| | | |
| | | # 生成市场深度报告 |
| | | depth_report = msm.generate_market_depth_report(symbol) |
| | | print("\n市场深度报告:") |
| | | print(f"买卖价差: {depth_report['spread']:.2f}") |
| | | print(f"中间价: {depth_report['mid_price']:.2f}") |
| | | |
| | | # 测试交易成本估算器 |
| | | cost_estimator = TradingCostEstimator() |
| | | cost = cost_estimator.estimate_cost(symbol, 1000, 'buy') |
| | | print("\n交易成本估算:") |
| | | print(f"总成本: {cost['total_cost']:.2f}") |
| | | print(f"成本百分比: {cost['cost_percentage']:.4f}%") |
| | | |
| | | # 比较交易策略 |
| | | strategies = [ |
| | | {'type': 'one_shot', 'side': 'buy'}, |
| | | {'type': 'iceberg', 'side': 'buy', 'slice_size': 200} |
| | | ] |
| | | comparison = cost_estimator.compare_trading_strategies(symbol, 1000, strategies) |
| | | print("\n交易策略比较:") |
| | | for result in comparison: |
| | | print(f"策略: {result['strategy']}") |
| | | print(f"总成本: {result['total_cost']:.2f}") |
| | | print(f"成本百分比: {result['cost_percentage']:.4f}%") |
| | | print() |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | """ |
| | | 系统管理器 |
| | | 功能: |
| | | 1. 统一管理系统组件 |
| | | 2. 提供插件系统 |
| | | 3. 配置管理 |
| | | 4. 系统健康检查 |
| | | 5. 组件间通信 |
| | | """ |
| | | |
| | | import importlib |
| | | import os |
| | | import sys |
| | | import json |
| | | from datetime import datetime |
| | | from typing import Dict, List, Optional, Any |
| | | import logging |
| | | |
| | | logging.basicConfig(level=logging.INFO) |
| | | logger = logging.getLogger(__name__) |
| | | |
| | | |
| | | class Plugin: |
| | | """插件基类""" |
| | | |
| | | def __init__(self, name: str, config: Dict = None): |
| | | self.name = name |
| | | self.config = config or {} |
| | | self.enabled = True |
| | | |
| | | def initialize(self) -> bool: |
| | | """初始化插件""" |
| | | raise NotImplementedError |
| | | |
| | | def run(self, *args, **kwargs) -> Any: |
| | | """运行插件""" |
| | | raise NotImplementedError |
| | | |
| | | def shutdown(self) -> bool: |
| | | """关闭插件""" |
| | | raise NotImplementedError |
| | | |
| | | |
| | | class PluginManager: |
| | | """插件管理器""" |
| | | |
| | | def __init__(self): |
| | | self.plugins = {} |
| | | self.plugin_paths = [] |
| | | |
| | | def add_plugin_path(self, path: str): |
| | | """添加插件路径""" |
| | | if os.path.exists(path): |
| | | self.plugin_paths.append(path) |
| | | sys.path.insert(0, path) |
| | | logger.info(f"添加插件路径: {path}") |
| | | |
| | | def load_plugin(self, name: str, module_path: str, config: Dict = None) -> bool: |
| | | """加载插件""" |
| | | try: |
| | | # 动态导入模块 |
| | | module = importlib.import_module(module_path) |
| | | # 假设插件类名为Plugin |
| | | plugin_class = getattr(module, 'Plugin', None) |
| | | if not plugin_class: |
| | | logger.error(f"插件 {name} 中未找到Plugin类") |
| | | return False |
| | | |
| | | # 创建插件实例 |
| | | plugin = plugin_class(name, config) |
| | | if plugin.initialize(): |
| | | self.plugins[name] = plugin |
| | | logger.info(f"插件 {name} 加载成功") |
| | | return True |
| | | else: |
| | | logger.error(f"插件 {name} 初始化失败") |
| | | return False |
| | | except Exception as e: |
| | | logger.error(f"加载插件 {name} 失败: {e}") |
| | | return False |
| | | |
| | | def run_plugin(self, name: str, *args, **kwargs) -> Any: |
| | | """运行插件""" |
| | | if name in self.plugins and self.plugins[name].enabled: |
| | | try: |
| | | return self.plugins[name].run(*args, **kwargs) |
| | | except Exception as e: |
| | | logger.error(f"运行插件 {name} 失败: {e}") |
| | | return None |
| | | else: |
| | | logger.warning(f"插件 {name} 未加载或未启用") |
| | | return None |
| | | |
| | | def shutdown_plugin(self, name: str) -> bool: |
| | | """关闭插件""" |
| | | if name in self.plugins: |
| | | try: |
| | | result = self.plugins[name].shutdown() |
| | | del self.plugins[name] |
| | | logger.info(f"插件 {name} 关闭成功") |
| | | return result |
| | | except Exception as e: |
| | | logger.error(f"关闭插件 {name} 失败: {e}") |
| | | return False |
| | | return False |
| | | |
| | | def shutdown_all(self): |
| | | """关闭所有插件""" |
| | | for name in list(self.plugins.keys()): |
| | | self.shutdown_plugin(name) |
| | | |
| | | |
| | | class ConfigManager: |
| | | """配置管理器""" |
| | | |
| | | def __init__(self, config_dir: str = 'config'): |
| | | self.config_dir = config_dir |
| | | self.configs = {} |
| | | self._load_configs() |
| | | |
| | | def _load_configs(self): |
| | | """加载配置文件""" |
| | | if not os.path.exists(self.config_dir): |
| | | os.makedirs(self.config_dir) |
| | | logger.info(f"创建配置目录: {self.config_dir}") |
| | | |
| | | for filename in os.listdir(self.config_dir): |
| | | if filename.endswith('.json'): |
| | | filepath = os.path.join(self.config_dir, filename) |
| | | try: |
| | | with open(filepath, 'r', encoding='utf-8') as f: |
| | | config = json.load(f) |
| | | config_name = filename.replace('.json', '') |
| | | self.configs[config_name] = config |
| | | logger.info(f"加载配置: {config_name}") |
| | | except Exception as e: |
| | | logger.error(f"加载配置文件 {filename} 失败: {e}") |
| | | |
| | | def get(self, config_name: str, key: str = None, default: Any = None) -> Any: |
| | | """获取配置""" |
| | | if config_name not in self.configs: |
| | | return default |
| | | |
| | | if key is None: |
| | | return self.configs[config_name] |
| | | |
| | | return self.configs[config_name].get(key, default) |
| | | |
| | | def set(self, config_name: str, key: str, value: Any): |
| | | """设置配置""" |
| | | if config_name not in self.configs: |
| | | self.configs[config_name] = {} |
| | | |
| | | self.configs[config_name][key] = value |
| | | |
| | | # 保存配置 |
| | | filepath = os.path.join(self.config_dir, f"{config_name}.json") |
| | | try: |
| | | with open(filepath, 'w', encoding='utf-8') as f: |
| | | json.dump(self.configs[config_name], f, indent=2, ensure_ascii=False) |
| | | logger.info(f"保存配置: {config_name}") |
| | | except Exception as e: |
| | | logger.error(f"保存配置文件 {config_name} 失败: {e}") |
| | | |
| | | def reload(self): |
| | | """重新加载配置""" |
| | | self._load_configs() |
| | | logger.info("配置重新加载完成") |
| | | |
| | | |
| | | class SystemManager: |
| | | """系统管理器""" |
| | | |
| | | def __init__(self, base_dir: str = None): |
| | | self.base_dir = base_dir or os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) |
| | | self.config_manager = ConfigManager(os.path.join(self.base_dir, 'config')) |
| | | self.plugin_manager = PluginManager() |
| | | self.components = {} |
| | | self.system_status = 'initialized' |
| | | self.start_time = datetime.now() |
| | | |
| | | # 添加插件路径 |
| | | plugin_dir = os.path.join(self.base_dir, 'plugins') |
| | | if os.path.exists(plugin_dir): |
| | | self.plugin_manager.add_plugin_path(plugin_dir) |
| | | |
| | | def register_component(self, name: str, component: Any): |
| | | """注册组件""" |
| | | self.components[name] = component |
| | | logger.info(f"组件 {name} 注册成功") |
| | | |
| | | def get_component(self, name: str) -> Optional[Any]: |
| | | """获取组件""" |
| | | return self.components.get(name) |
| | | |
| | | def load_plugin(self, name: str, module_path: str, config: Dict = None) -> bool: |
| | | """加载插件""" |
| | | return self.plugin_manager.load_plugin(name, module_path, config) |
| | | |
| | | def run_plugin(self, name: str, *args, **kwargs) -> Any: |
| | | """运行插件""" |
| | | return self.plugin_manager.run_plugin(name, *args, **kwargs) |
| | | |
| | | def get_config(self, config_name: str, key: str = None, default: Any = None) -> Any: |
| | | """获取配置""" |
| | | return self.config_manager.get(config_name, key, default) |
| | | |
| | | def set_config(self, config_name: str, key: str, value: Any): |
| | | """设置配置""" |
| | | self.config_manager.set(config_name, key, value) |
| | | |
| | | def health_check(self) -> Dict: |
| | | """系统健康检查""" |
| | | check_time = datetime.now() |
| | | uptime = (check_time - self.start_time).total_seconds() |
| | | |
| | | # 检查组件状态 |
| | | component_status = {} |
| | | for name, component in self.components.items(): |
| | | try: |
| | | # 检查组件是否有health_check方法 |
| | | if hasattr(component, 'health_check'): |
| | | status = component.health_check() |
| | | else: |
| | | status = {'status': 'ok'} |
| | | component_status[name] = status |
| | | except Exception as e: |
| | | component_status[name] = {'status': 'error', 'message': str(e)} |
| | | |
| | | # 检查插件状态 |
| | | plugin_status = {} |
| | | for name, plugin in self.plugin_manager.plugins.items(): |
| | | plugin_status[name] = {'enabled': plugin.enabled} |
| | | |
| | | health_report = { |
| | | 'timestamp': check_time.strftime('%Y-%m-%d %H:%M:%S'), |
| | | 'system_status': self.system_status, |
| | | 'uptime_seconds': uptime, |
| | | 'components': component_status, |
| | | 'plugins': plugin_status, |
| | | 'configs_loaded': list(self.config_manager.configs.keys()) |
| | | } |
| | | |
| | | return health_report |
| | | |
| | | def start(self): |
| | | """启动系统""" |
| | | logger.info("🚀 启动系统...") |
| | | |
| | | # 初始化组件 |
| | | for name, component in self.components.items(): |
| | | if hasattr(component, 'initialize'): |
| | | try: |
| | | component.initialize() |
| | | logger.info(f"组件 {name} 初始化成功") |
| | | except Exception as e: |
| | | logger.error(f"组件 {name} 初始化失败: {e}") |
| | | |
| | | self.system_status = 'running' |
| | | logger.info("✅ 系统启动完成") |
| | | |
| | | def shutdown(self): |
| | | """关闭系统""" |
| | | logger.info("🛑 关闭系统...") |
| | | |
| | | # 关闭插件 |
| | | self.plugin_manager.shutdown_all() |
| | | |
| | | # 关闭组件 |
| | | for name, component in self.components.items(): |
| | | if hasattr(component, 'shutdown'): |
| | | try: |
| | | component.shutdown() |
| | | logger.info(f"组件 {name} 关闭成功") |
| | | except Exception as e: |
| | | logger.error(f"组件 {name} 关闭失败: {e}") |
| | | |
| | | self.system_status = 'shutdown' |
| | | logger.info("✅ 系统关闭完成") |
| | | |
| | | def generate_system_report(self) -> Dict: |
| | | """生成系统报告""" |
| | | report = { |
| | | 'system': { |
| | | 'base_dir': self.base_dir, |
| | | 'status': self.system_status, |
| | | 'start_time': self.start_time.strftime('%Y-%m-%d %H:%M:%S'), |
| | | 'uptime': (datetime.now() - self.start_time).total_seconds() |
| | | }, |
| | | 'components': list(self.components.keys()), |
| | | 'plugins': list(self.plugin_manager.plugins.keys()), |
| | | 'configs': list(self.config_manager.configs.keys()), |
| | | 'health': self.health_check() |
| | | } |
| | | |
| | | return report |
| | | |
| | | def save_system_report(self, output_dir: str = 'reports/system'): |
| | | """保存系统报告""" |
| | | os.makedirs(output_dir, exist_ok=True) |
| | | |
| | | timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') |
| | | report = self.generate_system_report() |
| | | |
| | | # 保存JSON报告 |
| | | json_path = os.path.join(output_dir, f'system_report_{timestamp}.json') |
| | | with open(json_path, 'w', encoding='utf-8') as f: |
| | | json.dump(report, f, indent=2, ensure_ascii=False, default=str) |
| | | |
| | | # 生成Markdown报告 |
| | | md_report = self._generate_markdown_report(report) |
| | | md_path = os.path.join(output_dir, f'system_report_{timestamp}.md') |
| | | with open(md_path, 'w', encoding='utf-8') as f: |
| | | f.write(md_report) |
| | | |
| | | logger.info(f"系统报告已保存: {json_path}") |
| | | logger.info(f"Markdown报告已保存: {md_path}") |
| | | |
| | | return json_path |
| | | |
| | | def _generate_markdown_report(self, report: Dict) -> str: |
| | | """生成Markdown报告""" |
| | | lines = [] |
| | | |
| | | lines.append("# 系统状态报告\n") |
| | | lines.append(f"**生成时间:** {report['health']['timestamp']}\n") |
| | | lines.append("---\n") |
| | | |
| | | # 系统信息 |
| | | lines.append("## 🖥️ 系统信息\n") |
| | | lines.append(f"- **基础目录:** {report['system']['base_dir']}\n") |
| | | lines.append(f"- **系统状态:** {report['system']['status']}\n") |
| | | lines.append(f"- **启动时间:** {report['system']['start_time']}\n") |
| | | lines.append(f"- **运行时间:** {report['system']['uptime']:.2f} 秒\n\n") |
| | | |
| | | # 组件状态 |
| | | lines.append("## 🧩 组件状态\n") |
| | | if report['components']: |
| | | for component in report['components']: |
| | | status = report['health']['components'].get(component, {'status': 'unknown'}) |
| | | status_str = status['status'] |
| | | if status_str == 'ok': |
| | | status_str = '✅ 正常' |
| | | elif status_str == 'error': |
| | | status_str = f"❌ 错误: {status.get('message', '未知错误')}" |
| | | lines.append(f"- **{component}:** {status_str}\n") |
| | | else: |
| | | lines.append("无组件\n") |
| | | lines.append("\n") |
| | | |
| | | # 插件状态 |
| | | lines.append("## 🔌 插件状态\n") |
| | | if report['plugins']: |
| | | for plugin in report['plugins']: |
| | | enabled = report['health']['plugins'].get(plugin, {'enabled': False})['enabled'] |
| | | status_str = "✅ 启用" if enabled else "⏸️ 禁用" |
| | | lines.append(f"- **{plugin}:** {status_str}\n") |
| | | else: |
| | | lines.append("无插件\n") |
| | | lines.append("\n") |
| | | |
| | | # 配置信息 |
| | | lines.append("## ⚙️ 配置信息\n") |
| | | if report['configs']: |
| | | lines.append("已加载的配置文件:\n") |
| | | for config in report['configs']: |
| | | lines.append(f"- {config}.json\n") |
| | | else: |
| | | lines.append("无配置文件\n") |
| | | lines.append("\n") |
| | | |
| | | lines.append("---\n") |
| | | lines.append("\n## 📋 总结\n\n") |
| | | lines.append("本报告提供了系统的详细状态信息,包括组件、插件和配置的运行情况。\n") |
| | | |
| | | return '\n'.join(lines) |
| | | |
| | | |
| | | class DataPipeline: |
| | | """数据处理管道""" |
| | | |
| | | def __init__(self, system_manager: SystemManager): |
| | | self.system_manager = system_manager |
| | | self.steps = [] |
| | | |
| | | def add_step(self, name: str, func: callable, **kwargs): |
| | | """添加处理步骤""" |
| | | self.steps.append({'name': name, 'func': func, 'kwargs': kwargs}) |
| | | logger.info(f"添加数据处理步骤: {name}") |
| | | |
| | | def run(self, data: Any) -> Any: |
| | | """运行数据处理管道""" |
| | | logger.info("运行数据处理管道...") |
| | | |
| | | current_data = data |
| | | for step in self.steps: |
| | | try: |
| | | logger.info(f"执行步骤: {step['name']}") |
| | | current_data = step['func'](current_data, **step['kwargs']) |
| | | except Exception as e: |
| | | logger.error(f"执行步骤 {step['name']} 失败: {e}") |
| | | return None |
| | | |
| | | logger.info("数据处理管道执行完成") |
| | | return current_data |
| | | |
| | | def clear(self): |
| | | """清空处理步骤""" |
| | | self.steps = [] |
| | | logger.info("数据处理管道已清空") |
| | | |
| | | |
| | | if __name__ == '__main__': |
| | | # 测试系统管理器 |
| | | print("=== 系统管理器测试 ===") |
| | | |
| | | # 创建系统管理器 |
| | | system_manager = SystemManager() |
| | | |
| | | # 注册组件 |
| | | class TestComponent: |
| | | def initialize(self): |
| | | logger.info("测试组件初始化") |
| | | |
| | | def health_check(self): |
| | | return {'status': 'ok'} |
| | | |
| | | system_manager.register_component('test_component', TestComponent()) |
| | | |
| | | # 启动系统 |
| | | system_manager.start() |
| | | |
| | | # 运行健康检查 |
| | | health = system_manager.health_check() |
| | | print(f"系统健康状态: {health['system_status']}") |
| | | |
| | | # 生成系统报告 |
| | | system_manager.save_system_report() |
| | | |
| | | # 关闭系统 |
| | | system_manager.shutdown() |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | """ |
| | | 交易员辅助模块 |
| | | 为没有API接入条件的交易员提供替代解决方案 |
| | | """ |
| | | |
| | | import os |
| | | import json |
| | | import logging |
| | | from datetime import datetime, timedelta |
| | | from typing import Dict, List, Optional |
| | | import pandas as pd |
| | | import matplotlib.pyplot as plt |
| | | |
| | | logging.basicConfig(level=logging.INFO) |
| | | logger = logging.getLogger(__name__) |
| | | |
| | | |
| | | class TradingReportGenerator: |
| | | """交易报表生成器""" |
| | | |
| | | def __init__(self, report_dir: str = 'reports/trading'): |
| | | self.report_dir = report_dir |
| | | os.makedirs(self.report_dir, exist_ok=True) |
| | | |
| | | def generate_daily_report(self, positions: Dict, account_info: Dict, |
| | | trades: List[Dict], date: Optional[str] = None) -> str: |
| | | """生成每日交易报表 |
| | | |
| | | Args: |
| | | positions: 持仓信息 |
| | | account_info: 账户信息 |
| | | trades: 当日交易记录 |
| | | date: 日期 (YYYY-MM-DD) |
| | | |
| | | Returns: |
| | | 报表文件路径 |
| | | """ |
| | | if date is None: |
| | | date = datetime.now().strftime('%Y-%m-%d') |
| | | |
| | | # 生成报表 |
| | | report = { |
| | | 'date': date, |
| | | 'account': account_info, |
| | | 'positions': positions, |
| | | 'trades': trades, |
| | | 'summary': self._generate_summary(positions, account_info, trades) |
| | | } |
| | | |
| | | # 保存JSON报表 |
| | | json_path = os.path.join(self.report_dir, f'daily_report_{date}.json') |
| | | with open(json_path, 'w', encoding='utf-8') as f: |
| | | json.dump(report, f, indent=2, ensure_ascii=False, default=str) |
| | | |
| | | # 生成HTML报表 |
| | | html_path = os.path.join(self.report_dir, f'daily_report_{date}.html') |
| | | self._generate_html_report(report, html_path) |
| | | |
| | | # 生成PDF报表 |
| | | pdf_path = os.path.join(self.report_dir, f'daily_report_{date}.pdf') |
| | | self._generate_pdf_report(report, pdf_path) |
| | | |
| | | logger.info(f"每日交易报表已生成: {json_path}") |
| | | return json_path |
| | | |
| | | def generate_weekly_report(self, start_date: str, end_date: str, |
| | | positions: Dict, account_info: Dict, |
| | | trades: List[Dict]) -> str: |
| | | """生成每周交易报表""" |
| | | # 生成报表 |
| | | report = { |
| | | 'period': f'{start_date} 至 {end_date}', |
| | | 'account': account_info, |
| | | 'positions': positions, |
| | | 'trades': trades, |
| | | 'summary': self._generate_summary(positions, account_info, trades), |
| | | 'weekly_analysis': self._generate_weekly_analysis(trades) |
| | | } |
| | | |
| | | # 保存JSON报表 |
| | | json_path = os.path.join(self.report_dir, f'weekly_report_{start_date}_{end_date}.json') |
| | | with open(json_path, 'w', encoding='utf-8') as f: |
| | | json.dump(report, f, indent=2, ensure_ascii=False, default=str) |
| | | |
| | | # 生成HTML报表 |
| | | html_path = os.path.join(self.report_dir, f'weekly_report_{start_date}_{end_date}.html') |
| | | self._generate_html_report(report, html_path) |
| | | |
| | | logger.info(f"每周交易报表已生成: {json_path}") |
| | | return json_path |
| | | |
| | | def _generate_summary(self, positions: Dict, account_info: Dict, trades: List[Dict]) -> Dict: |
| | | """生成报表摘要""" |
| | | total_positions = len(positions) |
| | | total_value = account_info.get('total_value', 0) |
| | | total_cash = account_info.get('cash', 0) |
| | | total_pnl = account_info.get('pnl', 0) |
| | | |
| | | # 计算当日交易统计 |
| | | buy_trades = [t for t in trades if t['side'] == 'buy'] |
| | | sell_trades = [t for t in trades if t['side'] == 'sell'] |
| | | |
| | | return { |
| | | 'total_positions': total_positions, |
| | | 'total_value': total_value, |
| | | 'total_cash': total_cash, |
| | | 'total_pnl': total_pnl, |
| | | 'buy_trades': len(buy_trades), |
| | | 'sell_trades': len(sell_trades), |
| | | 'total_trades': len(trades) |
| | | } |
| | | |
| | | def _generate_weekly_analysis(self, trades: List[Dict]) -> Dict: |
| | | """生成每周分析""" |
| | | # 按日期分组交易 |
| | | trades_by_date = {} |
| | | for trade in trades: |
| | | date = trade.get('date', datetime.now().strftime('%Y-%m-%d')) |
| | | if date not in trades_by_date: |
| | | trades_by_date[date] = [] |
| | | trades_by_date[date].append(trade) |
| | | |
| | | # 计算每日交易量 |
| | | daily_trades = {date: len(trades) for date, trades in trades_by_date.items()} |
| | | |
| | | return { |
| | | 'trades_by_date': daily_trades, |
| | | 'total_weekly_trades': len(trades), |
| | | 'most_active_day': max(daily_trades, key=daily_trades.get) if daily_trades else None |
| | | } |
| | | |
| | | def _generate_html_report(self, report: Dict, output_path: str): |
| | | """生成HTML报表""" |
| | | html_content = f""" |
| | | <!DOCTYPE html> |
| | | <html> |
| | | <head> |
| | | <meta charset="UTF-8"> |
| | | <title>交易报表 - {report.get('date', report.get('period', 'Unknown'))}</title> |
| | | <style> |
| | | body {{ font-family: Arial, sans-serif; margin: 20px; }} |
| | | h1, h2, h3 {{ color: #333; }} |
| | | table {{ border-collapse: collapse; width: 100%; margin: 20px 0; }} |
| | | th, td {{ border: 1px solid #ddd; padding: 8px; text-align: left; }} |
| | | th {{ background-color: #f2f2f2; }} |
| | | .summary {{ background-color: #f9f9f9; padding: 15px; margin: 20px 0; }} |
| | | .positive {{ color: green; }} |
| | | .negative {{ color: red; }} |
| | | </style> |
| | | </head> |
| | | <body> |
| | | <h1>交易报表</h1> |
| | | <h2>{report.get('date', report.get('period', 'Unknown'))}</h2> |
| | | |
| | | <div class="summary"> |
| | | <h3>摘要</h3> |
| | | <p>总持仓数: {report['summary']['total_positions']}</p> |
| | | <p>总资产: ¥{report['account'].get('total_value', 0):,.2f}</p> |
| | | <p>现金: ¥{report['account'].get('cash', 0):,.2f}</p> |
| | | <p>总盈亏: <span class="{'positive' if report['account'].get('pnl', 0) >= 0 else 'negative'}"> |
| | | ¥{report['account'].get('pnl', 0):,.2f} |
| | | </span></p> |
| | | <p>当日交易: {report['summary']['total_trades']} 笔 (买入: {report['summary']['buy_trades']}, 卖出: {report['summary']['sell_trades']})</p> |
| | | </div> |
| | | |
| | | <h3>持仓情况</h3> |
| | | <table> |
| | | <tr> |
| | | <th>股票代码</th> |
| | | <th>持仓数量</th> |
| | | <th>平均成本</th> |
| | | <th>市值</th> |
| | | </tr> |
| | | """ |
| | | |
| | | # 添加持仓数据 |
| | | for stock_code, pos in report['positions'].items(): |
| | | html_content += f""" |
| | | <tr> |
| | | <td>{stock_code}</td> |
| | | <td>{pos.get('quantity', 0)}</td> |
| | | <td>¥{pos.get('avg_price', 0):,.2f}</td> |
| | | <td>¥{pos.get('market_value', 0):,.2f}</td> |
| | | </tr> |
| | | """ |
| | | |
| | | html_content += """ |
| | | </table> |
| | | |
| | | <h3>交易记录</h3> |
| | | <table> |
| | | <tr> |
| | | <th>时间</th> |
| | | <th>股票代码</th> |
| | | <th>方向</th> |
| | | <th>价格</th> |
| | | <th>数量</th> |
| | | <th>金额</th> |
| | | </tr> |
| | | """ |
| | | |
| | | # 添加交易数据 |
| | | for trade in report['trades']: |
| | | amount = trade.get('price', 0) * trade.get('quantity', 0) |
| | | html_content += f""" |
| | | <tr> |
| | | <td>{trade.get('time', 'N/A')}</td> |
| | | <td>{trade.get('stock_code', 'N/A')}</td> |
| | | <td>{'买入' if trade.get('side') == 'buy' else '卖出'}</td> |
| | | <td>¥{trade.get('price', 0):,.2f}</td> |
| | | <td>{trade.get('quantity', 0)}</td> |
| | | <td>¥{amount:,.2f}</td> |
| | | </tr> |
| | | """ |
| | | |
| | | html_content += """ |
| | | </table> |
| | | """ |
| | | |
| | | # 添加周度分析(如果有) |
| | | if 'weekly_analysis' in report: |
| | | html_content += f""" |
| | | <h3>周度分析</h3> |
| | | <div class="summary"> |
| | | <p>总交易次数: {report['weekly_analysis']['total_weekly_trades']}</p> |
| | | <p>最活跃交易日: {report['weekly_analysis']['most_active_day']}</p> |
| | | </div> |
| | | """ |
| | | |
| | | html_content += """ |
| | | </body> |
| | | </html> |
| | | """ |
| | | |
| | | with open(output_path, 'w', encoding='utf-8') as f: |
| | | f.write(html_content) |
| | | |
| | | def _generate_pdf_report(self, report: Dict, output_path: str): |
| | | """生成PDF报表""" |
| | | # 这里可以使用weasyprint或其他库生成PDF |
| | | # 暂时只创建空文件作为占位符 |
| | | with open(output_path, 'w', encoding='utf-8') as f: |
| | | f.write(f"PDF Report for {report.get('date', report.get('period', 'Unknown'))}") |
| | | |
| | | |
| | | class TraderFeedbackSystem: |
| | | """交易员反馈系统""" |
| | | |
| | | def __init__(self, feedback_dir: str = 'data/feedback'): |
| | | self.feedback_dir = feedback_dir |
| | | os.makedirs(self.feedback_dir, exist_ok=True) |
| | | |
| | | def submit_feedback(self, trader_id: str, feedback: Dict) -> str: |
| | | """提交交易员反馈 |
| | | |
| | | Args: |
| | | trader_id: 交易员ID |
| | | feedback: 反馈内容 |
| | | |
| | | Returns: |
| | | 反馈ID |
| | | """ |
| | | feedback_id = f"FB_{datetime.now().strftime('%Y%m%d%H%M%S')}_{trader_id}" |
| | | feedback_data = { |
| | | 'feedback_id': feedback_id, |
| | | 'trader_id': trader_id, |
| | | 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), |
| | | 'feedback': feedback |
| | | } |
| | | |
| | | # 保存反馈 |
| | | feedback_path = os.path.join(self.feedback_dir, f'{feedback_id}.json') |
| | | with open(feedback_path, 'w', encoding='utf-8') as f: |
| | | json.dump(feedback_data, f, indent=2, ensure_ascii=False) |
| | | |
| | | logger.info(f"交易员反馈已提交: {feedback_id}") |
| | | return feedback_id |
| | | |
| | | def get_feedback(self, feedback_id: str) -> Optional[Dict]: |
| | | """获取反馈""" |
| | | feedback_path = os.path.join(self.feedback_dir, f'{feedback_id}.json') |
| | | if os.path.exists(feedback_path): |
| | | with open(feedback_path, 'r', encoding='utf-8') as f: |
| | | return json.load(f) |
| | | return None |
| | | |
| | | def get_trader_feedback(self, trader_id: str) -> List[Dict]: |
| | | """获取交易员的所有反馈""" |
| | | feedbacks = [] |
| | | for filename in os.listdir(self.feedback_dir): |
| | | if filename.endswith('.json') and trader_id in filename: |
| | | filepath = os.path.join(self.feedback_dir, filename) |
| | | with open(filepath, 'r', encoding='utf-8') as f: |
| | | feedbacks.append(json.load(f)) |
| | | return feedbacks |
| | | |
| | | |
| | | class StrategySyncManager: |
| | | """策略同步管理器""" |
| | | |
| | | def __init__(self, sync_dir: str = 'data/sync'): |
| | | self.sync_dir = sync_dir |
| | | os.makedirs(self.sync_dir, exist_ok=True) |
| | | |
| | | def sync_strategy(self, strategy_id: str, strategy_data: Dict) -> str: |
| | | """同步策略数据""" |
| | | sync_id = f"SYNC_{datetime.now().strftime('%Y%m%d%H%M%S')}_{strategy_id}" |
| | | sync_data = { |
| | | 'sync_id': sync_id, |
| | | 'strategy_id': strategy_id, |
| | | 'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'), |
| | | 'strategy_data': strategy_data |
| | | } |
| | | |
| | | # 保存同步数据 |
| | | sync_path = os.path.join(self.sync_dir, f'{sync_id}.json') |
| | | with open(sync_path, 'w', encoding='utf-8') as f: |
| | | json.dump(sync_data, f, indent=2, ensure_ascii=False) |
| | | |
| | | logger.info(f"策略数据已同步: {sync_id}") |
| | | return sync_id |
| | | |
| | | def get_strategy_sync(self, sync_id: str) -> Optional[Dict]: |
| | | """获取策略同步数据""" |
| | | sync_path = os.path.join(self.sync_dir, f'{sync_id}.json') |
| | | if os.path.exists(sync_path): |
| | | with open(sync_path, 'r', encoding='utf-8') as f: |
| | | return json.load(f) |
| | | return None |
| | | |
| | | |
| | | class TraderAssistant: |
| | | """交易员助手""" |
| | | |
| | | def __init__(self): |
| | | self.report_generator = TradingReportGenerator() |
| | | self.feedback_system = TraderFeedbackSystem() |
| | | self.sync_manager = StrategySyncManager() |
| | | |
| | | def generate_report(self, positions: Dict, account_info: Dict, |
| | | trades: List[Dict], report_type: str = 'daily', |
| | | date: Optional[str] = None, |
| | | start_date: Optional[str] = None, |
| | | end_date: Optional[str] = None) -> str: |
| | | """生成交易报表""" |
| | | if report_type == 'daily': |
| | | return self.report_generator.generate_daily_report( |
| | | positions, account_info, trades, date |
| | | ) |
| | | elif report_type == 'weekly': |
| | | if start_date and end_date: |
| | | return self.report_generator.generate_weekly_report( |
| | | start_date, end_date, positions, account_info, trades |
| | | ) |
| | | else: |
| | | logger.error("周度报表需要提供开始和结束日期") |
| | | return None |
| | | else: |
| | | logger.error(f"不支持的报表类型: {report_type}") |
| | | return None |
| | | |
| | | def submit_feedback(self, trader_id: str, feedback: Dict) -> str: |
| | | """提交交易员反馈""" |
| | | return self.feedback_system.submit_feedback(trader_id, feedback) |
| | | |
| | | def sync_strategy(self, strategy_id: str, strategy_data: Dict) -> str: |
| | | """同步策略数据""" |
| | | return self.sync_manager.sync_strategy(strategy_id, strategy_data) |
| | | |
| | | def get_feedback(self, feedback_id: str) -> Optional[Dict]: |
| | | """获取反馈""" |
| | | return self.feedback_system.get_feedback(feedback_id) |
| | | |
| | | def get_strategy_sync(self, sync_id: str) -> Optional[Dict]: |
| | | """获取策略同步数据""" |
| | | return self.sync_manager.get_strategy_sync(sync_id) |
| | | |
| | | |
| | | if __name__ == '__main__': |
| | | # 测试交易员助手 |
| | | print("=== 交易员助手测试 ===") |
| | | |
| | | assistant = TraderAssistant() |
| | | |
| | | # 测试数据 |
| | | test_positions = { |
| | | '600519': { |
| | | 'stock_code': '600519', |
| | | 'quantity': 100, |
| | | 'avg_price': 1800.0, |
| | | 'market_value': 180000.0 |
| | | }, |
| | | '000001': { |
| | | 'stock_code': '000001', |
| | | 'quantity': 500, |
| | | 'avg_price': 10.0, |
| | | 'market_value': 5000.0 |
| | | } |
| | | } |
| | | |
| | | test_account = { |
| | | 'cash': 815000.0, |
| | | 'total_value': 1000000.0, |
| | | 'positions_value': 185000.0, |
| | | 'pnl': 0.0 |
| | | } |
| | | |
| | | test_trades = [ |
| | | { |
| | | 'time': '09:30:00', |
| | | 'stock_code': '600519', |
| | | 'side': 'buy', |
| | | 'price': 1800.0, |
| | | 'quantity': 100 |
| | | }, |
| | | { |
| | | 'time': '10:30:00', |
| | | 'stock_code': '000001', |
| | | 'side': 'buy', |
| | | 'price': 10.0, |
| | | 'quantity': 500 |
| | | } |
| | | ] |
| | | |
| | | # 生成每日报表 |
| | | print("\n生成每日报表:") |
| | | daily_report = assistant.generate_report( |
| | | test_positions, test_account, test_trades, 'daily' |
| | | ) |
| | | print(f"每日报表生成成功: {daily_report}") |
| | | |
| | | # 生成每周报表 |
| | | print("\n生成每周报表:") |
| | | weekly_report = assistant.generate_report( |
| | | test_positions, test_account, test_trades, 'weekly', |
| | | start_date='2024-01-01', end_date='2024-01-07' |
| | | ) |
| | | print(f"每周报表生成成功: {weekly_report}") |
| | | |
| | | # 提交反馈 |
| | | print("\n提交交易员反馈:") |
| | | feedback = { |
| | | 'type': 'strategy', |
| | | 'content': '策略表现良好,建议增加止损功能', |
| | | 'rating': 4 |
| | | } |
| | | feedback_id = assistant.submit_feedback('trader_001', feedback) |
| | | print(f"反馈提交成功: {feedback_id}") |
| | | |
| | | # 同步策略 |
| | | print("\n同步策略数据:") |
| | | strategy_data = { |
| | | 'name': '动量策略', |
| | | 'parameters': {'window': 20, 'threshold': 0.05}, |
| | | 'last_updated': datetime.now().strftime('%Y-%m-%d %H:%M:%S') |
| | | } |
| | | sync_id = assistant.sync_strategy('strategy_001', strategy_data) |
| | | print(f"策略同步成功: {sync_id}") |
| New file |
| | |
| | | { |
| | | "feedback_id": "FB_20260303133532_trader_001", |
| | | "trader_id": "trader_001", |
| | | "timestamp": "2026-03-03 13:35:32", |
| | | "feedback": { |
| | | "type": "system", |
| | | "content": "系统运行良好,建议增加更多数据源", |
| | | "rating": 5 |
| | | } |
| | | } |
| New file |
| | |
| | | { |
| | | "feedback_id": "FB_20260303133612_trader_001", |
| | | "trader_id": "trader_001", |
| | | "timestamp": "2026-03-03 13:36:12", |
| | | "feedback": { |
| | | "type": "strategy", |
| | | "content": "策略表现良好,建议增加止损功能", |
| | | "rating": 4 |
| | | } |
| | | } |
| New file |
| | |
| | | { |
| | | "sync_id": "SYNC_20260303133612_strategy_001", |
| | | "strategy_id": "strategy_001", |
| | | "timestamp": "2026-03-03 13:36:12", |
| | | "strategy_data": { |
| | | "name": "动量策略", |
| | | "parameters": { |
| | | "window": 20, |
| | | "threshold": 0.05 |
| | | }, |
| | | "last_updated": "2026-03-03 13:36:12" |
| | | } |
| | | } |
| New file |
| | |
| | | #!/usr/bin/env python3 |
| | | """ |
| | | 系统集成示例 |
| | | 展示如何使用SystemManager整合所有组件 |
| | | """ |
| | | |
| | | import sys |
| | | import os |
| | | |
| | | # 添加代码路径 |
| | | sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'code')) |
| | | |
| | | from system.system_manager import SystemManager, DataPipeline |
| | | from data.multi_source_fetcher import MultiSourceStockFetcher |
| | | from data.data_quality_framework import DataQualityPipeline |
| | | from backtest.backtest_engine_v2 import BacktestEngineV2 |
| | | from backtest.real_time_trading import RealTimeTrader, SimulatedTradingAPI |
| | | from backtest.broker_api import BrokerAPIFactory |
| | | from trader.trader_assistant import TraderAssistant |
| | | from risk.fund_management import FundManager, RiskBudgetManager |
| | | from portfolio.portfolio_optimizer import PortfolioOptimizer |
| | | from strategy.alpha_stock_selector import AlphaStockSelector |
| | | from strategy.multi_factor_model import DynamicFactorWeightSystem |
| | | from risk.risk_calculator import FactorRiskModel, FactorExposureMonitor |
| | | |
| | | |
| | | def initialize_system(): |
| | | """初始化系统""" |
| | | print("=== 初始化系统 ===") |
| | | |
| | | # 创建系统管理器 |
| | | system_manager = SystemManager() |
| | | |
| | | # 注册核心组件 |
| | | print("\n1. 注册核心组件") |
| | | |
| | | # 数据获取组件 |
| | | fetcher = MultiSourceStockFetcher() |
| | | system_manager.register_component('data_fetcher', fetcher) |
| | | |
| | | # 数据质量框架 |
| | | quality_framework = DataQualityPipeline() |
| | | system_manager.register_component('data_quality', quality_framework) |
| | | |
| | | # 回测引擎 |
| | | backtest_engine = BacktestEngineV2() |
| | | system_manager.register_component('backtest_engine', backtest_engine) |
| | | |
| | | # 实时交易 |
| | | trading_api = SimulatedTradingAPI() |
| | | real_time_trader = RealTimeTrader(trading_api) |
| | | system_manager.register_component('real_time_trader', real_time_trader) |
| | | |
| | | # 资金管理 |
| | | fund_manager = FundManager(initial_capital=1000000) |
| | | system_manager.register_component('fund_manager', fund_manager) |
| | | |
| | | # 风险预算管理 |
| | | risk_budget_manager = RiskBudgetManager() |
| | | system_manager.register_component('risk_budget_manager', risk_budget_manager) |
| | | |
| | | # 组合优化 |
| | | portfolio_optimizer = PortfolioOptimizer() |
| | | system_manager.register_component('portfolio_optimizer', portfolio_optimizer) |
| | | |
| | | # 选股系统 |
| | | stock_selector = AlphaStockSelector() |
| | | system_manager.register_component('stock_selector', stock_selector) |
| | | |
| | | # 因子权重系统 |
| | | factor_weight_system = DynamicFactorWeightSystem() |
| | | system_manager.register_component('factor_weight_system', factor_weight_system) |
| | | |
| | | # 因子风险模型 |
| | | factor_risk_model = FactorRiskModel() |
| | | system_manager.register_component('factor_risk_model', factor_risk_model) |
| | | |
| | | # 因子暴露监控 |
| | | factor_exposure_monitor = FactorExposureMonitor() |
| | | system_manager.register_component('factor_exposure_monitor', factor_exposure_monitor) |
| | | |
| | | # 券商API |
| | | huatai_api = BrokerAPIFactory.create_broker_api('huatai') |
| | | huatai_trader = RealTimeTrader(huatai_api) |
| | | system_manager.register_component('huatai_trader', huatai_trader) |
| | | |
| | | # 交易员辅助功能 |
| | | trader_assistant = TraderAssistant() |
| | | system_manager.register_component('trader_assistant', trader_assistant) |
| | | |
| | | return system_manager |
| | | |
| | | |
| | | def create_data_pipeline(system_manager): |
| | | """创建数据处理管道""" |
| | | print("\n2. 创建数据处理管道") |
| | | |
| | | pipeline = DataPipeline(system_manager) |
| | | |
| | | # 添加数据处理步骤 |
| | | def fetch_data_step(data): |
| | | fetcher = system_manager.get_component('data_fetcher') |
| | | print(" - 获取数据") |
| | | # 这里可以根据实际需要获取数据 |
| | | return data |
| | | |
| | | def quality_check_step(data): |
| | | quality_framework = system_manager.get_component('data_quality') |
| | | print(" - 数据质量检查") |
| | | # 这里可以根据实际需要进行数据质量检查 |
| | | return data |
| | | |
| | | def stock_selection_step(data): |
| | | stock_selector = system_manager.get_component('stock_selector') |
| | | print(" - 选股") |
| | | # 这里可以根据实际需要进行选股 |
| | | return data |
| | | |
| | | def portfolio_optimization_step(data): |
| | | portfolio_optimizer = system_manager.get_component('portfolio_optimizer') |
| | | print(" - 组合优化") |
| | | # 这里可以根据实际需要进行组合优化 |
| | | return data |
| | | |
| | | def risk_management_step(data): |
| | | factor_risk_model = system_manager.get_component('factor_risk_model') |
| | | print(" - 风险评估") |
| | | # 这里可以根据实际需要进行风险评估 |
| | | return data |
| | | |
| | | # 添加步骤到管道 |
| | | pipeline.add_step('fetch_data', fetch_data_step) |
| | | pipeline.add_step('quality_check', quality_check_step) |
| | | pipeline.add_step('stock_selection', stock_selection_step) |
| | | pipeline.add_step('portfolio_optimization', portfolio_optimization_step) |
| | | pipeline.add_step('risk_management', risk_management_step) |
| | | |
| | | return pipeline |
| | | |
| | | |
| | | def run_system_demo(system_manager, pipeline): |
| | | """运行系统演示""" |
| | | print("\n3. 运行系统演示") |
| | | |
| | | # 启动系统 |
| | | print(" - 启动系统") |
| | | system_manager.start() |
| | | |
| | | # 运行健康检查 |
| | | print(" - 运行健康检查") |
| | | health_status = system_manager.health_check() |
| | | print(f" 系统状态: {health_status['system_status']}") |
| | | print(f" 组件数量: {len(health_status['components'])}") |
| | | |
| | | # 运行数据处理管道 |
| | | print(" - 运行数据处理管道") |
| | | test_data = {} |
| | | result = pipeline.run(test_data) |
| | | |
| | | # 生成系统报告 |
| | | print(" - 生成系统报告") |
| | | report_path = system_manager.save_system_report() |
| | | print(f" 系统报告已保存: {report_path}") |
| | | |
| | | # 演示券商API |
| | | print(" - 演示券商API") |
| | | huatai_trader = system_manager.get_component('huatai_trader') |
| | | if huatai_trader: |
| | | print(" 连接华泰证券API") |
| | | huatai_trader.connect() |
| | | print(" 获取账户信息") |
| | | account_info = huatai_trader.get_account() |
| | | print(f" 账户信息: {account_info}") |
| | | print(" 断开连接") |
| | | huatai_trader.disconnect() |
| | | |
| | | # 演示交易员辅助功能 |
| | | print(" - 演示交易员辅助功能") |
| | | trader_assistant = system_manager.get_component('trader_assistant') |
| | | if trader_assistant: |
| | | print(" 生成交易报表") |
| | | test_positions = { |
| | | '600519': { |
| | | 'stock_code': '600519', |
| | | 'quantity': 100, |
| | | 'avg_price': 1800.0, |
| | | 'market_value': 180000.0 |
| | | } |
| | | } |
| | | test_account = { |
| | | 'cash': 820000.0, |
| | | 'total_value': 1000000.0, |
| | | 'positions_value': 180000.0, |
| | | 'pnl': 0.0 |
| | | } |
| | | test_trades = [ |
| | | { |
| | | 'time': '09:30:00', |
| | | 'stock_code': '600519', |
| | | 'side': 'buy', |
| | | 'price': 1800.0, |
| | | 'quantity': 100 |
| | | } |
| | | ] |
| | | report_path = trader_assistant.generate_report( |
| | | test_positions, test_account, test_trades, 'daily' |
| | | ) |
| | | print(f" 每日报表生成成功: {report_path}") |
| | | |
| | | print(" 提交交易员反馈") |
| | | feedback = { |
| | | 'type': 'system', |
| | | 'content': '系统运行良好,建议增加更多数据源', |
| | | 'rating': 5 |
| | | } |
| | | feedback_id = trader_assistant.submit_feedback('trader_001', feedback) |
| | | print(f" 反馈提交成功: {feedback_id}") |
| | | |
| | | # 关闭系统 |
| | | print(" - 关闭系统") |
| | | system_manager.shutdown() |
| | | |
| | | |
| | | def demonstrate_plugin_system(system_manager): |
| | | """演示插件系统""" |
| | | print("\n4. 演示插件系统") |
| | | |
| | | # 这里可以演示如何加载和运行插件 |
| | | print(" - 插件系统演示") |
| | | print(" 插件系统已集成到SystemManager中") |
| | | print(" 可以通过load_plugin()方法加载自定义插件") |
| | | |
| | | |
| | | def main(): |
| | | """主函数""" |
| | | print("A股量化系统集成示例") |
| | | print("=" * 50) |
| | | |
| | | # 初始化系统 |
| | | system_manager = initialize_system() |
| | | |
| | | # 创建数据处理管道 |
| | | pipeline = create_data_pipeline(system_manager) |
| | | |
| | | # 运行系统演示 |
| | | run_system_demo(system_manager, pipeline) |
| | | |
| | | # 演示插件系统 |
| | | demonstrate_plugin_system(system_manager) |
| | | |
| | | print("\n" + "=" * 50) |
| | | print("系统集成示例完成") |
| | | print("提示: 此示例展示了如何使用SystemManager整合所有组件") |
| | | print("在实际应用中,您可以根据需要调整和扩展系统") |
| | | |
| | | |
| | | if __name__ == '__main__': |
| | | main() |
| New file |
| | |
| | | { |
| | | "system": { |
| | | "base_dir": "/Users/variya/.openclaw/workspace/projects/a-stock-advisor", |
| | | "status": "running", |
| | | "start_time": "2026-03-03 13:18:00", |
| | | "uptime": 33.291428 |
| | | }, |
| | | "components": [ |
| | | "data_fetcher", |
| | | "data_quality", |
| | | "backtest_engine", |
| | | "real_time_trader", |
| | | "fund_manager", |
| | | "risk_budget_manager", |
| | | "portfolio_optimizer", |
| | | "stock_selector", |
| | | "factor_weight_system", |
| | | "factor_risk_model", |
| | | "factor_exposure_monitor" |
| | | ], |
| | | "plugins": [], |
| | | "configs": [ |
| | | "feishu_config", |
| | | "risk_limits", |
| | | "cron_config_v2" |
| | | ], |
| | | "health": { |
| | | "timestamp": "2026-03-03 13:18:33", |
| | | "system_status": "running", |
| | | "uptime_seconds": 33.29143, |
| | | "components": { |
| | | "data_fetcher": { |
| | | "status": "ok" |
| | | }, |
| | | "data_quality": { |
| | | "status": "ok" |
| | | }, |
| | | "backtest_engine": { |
| | | "status": "ok" |
| | | }, |
| | | "real_time_trader": { |
| | | "status": "ok" |
| | | }, |
| | | "fund_manager": { |
| | | "status": "ok" |
| | | }, |
| | | "risk_budget_manager": { |
| | | "status": "ok" |
| | | }, |
| | | "portfolio_optimizer": { |
| | | "status": "ok" |
| | | }, |
| | | "stock_selector": { |
| | | "status": "ok" |
| | | }, |
| | | "factor_weight_system": { |
| | | "status": "ok" |
| | | }, |
| | | "factor_risk_model": { |
| | | "status": "ok" |
| | | }, |
| | | "factor_exposure_monitor": { |
| | | "status": "ok" |
| | | } |
| | | }, |
| | | "plugins": {}, |
| | | "configs_loaded": [ |
| | | "feishu_config", |
| | | "risk_limits", |
| | | "cron_config_v2" |
| | | ] |
| | | } |
| | | } |
| New file |
| | |
| | | # 系统状态报告 |
| | | |
| | | **生成时间:** 2026-03-03 13:18:33 |
| | | |
| | | --- |
| | | |
| | | ## 🖥️ 系统信息 |
| | | |
| | | - **基础目录:** /Users/variya/.openclaw/workspace/projects/a-stock-advisor |
| | | |
| | | - **系统状态:** running |
| | | |
| | | - **启动时间:** 2026-03-03 13:18:00 |
| | | |
| | | - **运行时间:** 33.29 秒 |
| | | |
| | | |
| | | ## 🧩 组件状态 |
| | | |
| | | - **data_fetcher:** ✅ 正常 |
| | | |
| | | - **data_quality:** ✅ 正常 |
| | | |
| | | - **backtest_engine:** ✅ 正常 |
| | | |
| | | - **real_time_trader:** ✅ 正常 |
| | | |
| | | - **fund_manager:** ✅ 正常 |
| | | |
| | | - **risk_budget_manager:** ✅ 正常 |
| | | |
| | | - **portfolio_optimizer:** ✅ 正常 |
| | | |
| | | - **stock_selector:** ✅ 正常 |
| | | |
| | | - **factor_weight_system:** ✅ 正常 |
| | | |
| | | - **factor_risk_model:** ✅ 正常 |
| | | |
| | | - **factor_exposure_monitor:** ✅ 正常 |
| | | |
| | | |
| | | |
| | | ## 🔌 插件状态 |
| | | |
| | | 无插件 |
| | | |
| | | |
| | | |
| | | ## ⚙️ 配置信息 |
| | | |
| | | 已加载的配置文件: |
| | | |
| | | - feishu_config.json |
| | | |
| | | - risk_limits.json |
| | | |
| | | - cron_config_v2.json |
| | | |
| | | |
| | | |
| | | --- |
| | | |
| | | |
| | | ## 📋 总结 |
| | | |
| | | |
| | | 本报告提供了系统的详细状态信息,包括组件、插件和配置的运行情况。 |
| New file |
| | |
| | | { |
| | | "system": { |
| | | "base_dir": "/Users/variya/.openclaw/workspace/projects/a-stock-advisor", |
| | | "status": "running", |
| | | "start_time": "2026-03-03 13:35:11", |
| | | "uptime": 20.103398 |
| | | }, |
| | | "components": [ |
| | | "data_fetcher", |
| | | "data_quality", |
| | | "backtest_engine", |
| | | "real_time_trader", |
| | | "fund_manager", |
| | | "risk_budget_manager", |
| | | "portfolio_optimizer", |
| | | "stock_selector", |
| | | "factor_weight_system", |
| | | "factor_risk_model", |
| | | "factor_exposure_monitor", |
| | | "huatai_trader", |
| | | "trader_assistant" |
| | | ], |
| | | "plugins": [], |
| | | "configs": [ |
| | | "feishu_config", |
| | | "risk_limits", |
| | | "cron_config_v2" |
| | | ], |
| | | "health": { |
| | | "timestamp": "2026-03-03 13:35:32", |
| | | "system_status": "running", |
| | | "uptime_seconds": 20.103403, |
| | | "components": { |
| | | "data_fetcher": { |
| | | "status": "ok" |
| | | }, |
| | | "data_quality": { |
| | | "status": "ok" |
| | | }, |
| | | "backtest_engine": { |
| | | "status": "ok" |
| | | }, |
| | | "real_time_trader": { |
| | | "status": "ok" |
| | | }, |
| | | "fund_manager": { |
| | | "status": "ok" |
| | | }, |
| | | "risk_budget_manager": { |
| | | "status": "ok" |
| | | }, |
| | | "portfolio_optimizer": { |
| | | "status": "ok" |
| | | }, |
| | | "stock_selector": { |
| | | "status": "ok" |
| | | }, |
| | | "factor_weight_system": { |
| | | "status": "ok" |
| | | }, |
| | | "factor_risk_model": { |
| | | "status": "ok" |
| | | }, |
| | | "factor_exposure_monitor": { |
| | | "status": "ok" |
| | | }, |
| | | "huatai_trader": { |
| | | "status": "ok" |
| | | }, |
| | | "trader_assistant": { |
| | | "status": "ok" |
| | | } |
| | | }, |
| | | "plugins": {}, |
| | | "configs_loaded": [ |
| | | "feishu_config", |
| | | "risk_limits", |
| | | "cron_config_v2" |
| | | ] |
| | | } |
| | | } |
| New file |
| | |
| | | # 系统状态报告 |
| | | |
| | | **生成时间:** 2026-03-03 13:35:32 |
| | | |
| | | --- |
| | | |
| | | ## 🖥️ 系统信息 |
| | | |
| | | - **基础目录:** /Users/variya/.openclaw/workspace/projects/a-stock-advisor |
| | | |
| | | - **系统状态:** running |
| | | |
| | | - **启动时间:** 2026-03-03 13:35:11 |
| | | |
| | | - **运行时间:** 20.10 秒 |
| | | |
| | | |
| | | ## 🧩 组件状态 |
| | | |
| | | - **data_fetcher:** ✅ 正常 |
| | | |
| | | - **data_quality:** ✅ 正常 |
| | | |
| | | - **backtest_engine:** ✅ 正常 |
| | | |
| | | - **real_time_trader:** ✅ 正常 |
| | | |
| | | - **fund_manager:** ✅ 正常 |
| | | |
| | | - **risk_budget_manager:** ✅ 正常 |
| | | |
| | | - **portfolio_optimizer:** ✅ 正常 |
| | | |
| | | - **stock_selector:** ✅ 正常 |
| | | |
| | | - **factor_weight_system:** ✅ 正常 |
| | | |
| | | - **factor_risk_model:** ✅ 正常 |
| | | |
| | | - **factor_exposure_monitor:** ✅ 正常 |
| | | |
| | | - **huatai_trader:** ✅ 正常 |
| | | |
| | | - **trader_assistant:** ✅ 正常 |
| | | |
| | | |
| | | |
| | | ## 🔌 插件状态 |
| | | |
| | | 无插件 |
| | | |
| | | |
| | | |
| | | ## ⚙️ 配置信息 |
| | | |
| | | 已加载的配置文件: |
| | | |
| | | - feishu_config.json |
| | | |
| | | - risk_limits.json |
| | | |
| | | - cron_config_v2.json |
| | | |
| | | |
| | | |
| | | --- |
| | | |
| | | |
| | | ## 📋 总结 |
| | | |
| | | |
| | | 本报告提供了系统的详细状态信息,包括组件、插件和配置的运行情况。 |
| New file |
| | |
| | | |
| | | <!DOCTYPE html> |
| | | <html> |
| | | <head> |
| | | <meta charset="UTF-8"> |
| | | <title>交易报表 - 2026-03-03</title> |
| | | <style> |
| | | body { font-family: Arial, sans-serif; margin: 20px; } |
| | | h1, h2, h3 { color: #333; } |
| | | table { border-collapse: collapse; width: 100%; margin: 20px 0; } |
| | | th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } |
| | | th { background-color: #f2f2f2; } |
| | | .summary { background-color: #f9f9f9; padding: 15px; margin: 20px 0; } |
| | | .positive { color: green; } |
| | | .negative { color: red; } |
| | | </style> |
| | | </head> |
| | | <body> |
| | | <h1>交易报表</h1> |
| | | <h2>2026-03-03</h2> |
| | | |
| | | <div class="summary"> |
| | | <h3>摘要</h3> |
| | | <p>总持仓数: 2</p> |
| | | <p>总资产: ¥1,000,000.00</p> |
| | | <p>现金: ¥815,000.00</p> |
| | | <p>总盈亏: <span class="positive"> |
| | | ¥0.00 |
| | | </span></p> |
| | | <p>当日交易: 2 笔 (买入: 2, 卖出: 0)</p> |
| | | </div> |
| | | |
| | | <h3>持仓情况</h3> |
| | | <table> |
| | | <tr> |
| | | <th>股票代码</th> |
| | | <th>持仓数量</th> |
| | | <th>平均成本</th> |
| | | <th>市值</th> |
| | | </tr> |
| | | |
| | | <tr> |
| | | <td>600519</td> |
| | | <td>100</td> |
| | | <td>¥1,800.00</td> |
| | | <td>¥180,000.00</td> |
| | | </tr> |
| | | |
| | | <tr> |
| | | <td>000001</td> |
| | | <td>500</td> |
| | | <td>¥10.00</td> |
| | | <td>¥5,000.00</td> |
| | | </tr> |
| | | |
| | | </table> |
| | | |
| | | <h3>交易记录</h3> |
| | | <table> |
| | | <tr> |
| | | <th>时间</th> |
| | | <th>股票代码</th> |
| | | <th>方向</th> |
| | | <th>价格</th> |
| | | <th>数量</th> |
| | | <th>金额</th> |
| | | </tr> |
| | | |
| | | <tr> |
| | | <td>09:30:00</td> |
| | | <td>600519</td> |
| | | <td>买入</td> |
| | | <td>¥1,800.00</td> |
| | | <td>100</td> |
| | | <td>¥180,000.00</td> |
| | | </tr> |
| | | |
| | | <tr> |
| | | <td>10:30:00</td> |
| | | <td>000001</td> |
| | | <td>买入</td> |
| | | <td>¥10.00</td> |
| | | <td>500</td> |
| | | <td>¥5,000.00</td> |
| | | </tr> |
| | | |
| | | </table> |
| | | |
| | | </body> |
| | | </html> |
| New file |
| | |
| | | { |
| | | "date": "2026-03-03", |
| | | "account": { |
| | | "cash": 815000.0, |
| | | "total_value": 1000000.0, |
| | | "positions_value": 185000.0, |
| | | "pnl": 0.0 |
| | | }, |
| | | "positions": { |
| | | "600519": { |
| | | "stock_code": "600519", |
| | | "quantity": 100, |
| | | "avg_price": 1800.0, |
| | | "market_value": 180000.0 |
| | | }, |
| | | "000001": { |
| | | "stock_code": "000001", |
| | | "quantity": 500, |
| | | "avg_price": 10.0, |
| | | "market_value": 5000.0 |
| | | } |
| | | }, |
| | | "trades": [ |
| | | { |
| | | "time": "09:30:00", |
| | | "stock_code": "600519", |
| | | "side": "buy", |
| | | "price": 1800.0, |
| | | "quantity": 100 |
| | | }, |
| | | { |
| | | "time": "10:30:00", |
| | | "stock_code": "000001", |
| | | "side": "buy", |
| | | "price": 10.0, |
| | | "quantity": 500 |
| | | } |
| | | ], |
| | | "summary": { |
| | | "total_positions": 2, |
| | | "total_value": 1000000.0, |
| | | "total_cash": 815000.0, |
| | | "total_pnl": 0.0, |
| | | "buy_trades": 2, |
| | | "sell_trades": 0, |
| | | "total_trades": 2 |
| | | } |
| | | } |
| New file |
| | |
| | | PDF Report for 2026-03-03 |
| New file |
| | |
| | | |
| | | <!DOCTYPE html> |
| | | <html> |
| | | <head> |
| | | <meta charset="UTF-8"> |
| | | <title>交易报表 - 2024-01-01 至 2024-01-07</title> |
| | | <style> |
| | | body { font-family: Arial, sans-serif; margin: 20px; } |
| | | h1, h2, h3 { color: #333; } |
| | | table { border-collapse: collapse; width: 100%; margin: 20px 0; } |
| | | th, td { border: 1px solid #ddd; padding: 8px; text-align: left; } |
| | | th { background-color: #f2f2f2; } |
| | | .summary { background-color: #f9f9f9; padding: 15px; margin: 20px 0; } |
| | | .positive { color: green; } |
| | | .negative { color: red; } |
| | | </style> |
| | | </head> |
| | | <body> |
| | | <h1>交易报表</h1> |
| | | <h2>2024-01-01 至 2024-01-07</h2> |
| | | |
| | | <div class="summary"> |
| | | <h3>摘要</h3> |
| | | <p>总持仓数: 2</p> |
| | | <p>总资产: ¥1,000,000.00</p> |
| | | <p>现金: ¥815,000.00</p> |
| | | <p>总盈亏: <span class="positive"> |
| | | ¥0.00 |
| | | </span></p> |
| | | <p>当日交易: 2 笔 (买入: 2, 卖出: 0)</p> |
| | | </div> |
| | | |
| | | <h3>持仓情况</h3> |
| | | <table> |
| | | <tr> |
| | | <th>股票代码</th> |
| | | <th>持仓数量</th> |
| | | <th>平均成本</th> |
| | | <th>市值</th> |
| | | </tr> |
| | | |
| | | <tr> |
| | | <td>600519</td> |
| | | <td>100</td> |
| | | <td>¥1,800.00</td> |
| | | <td>¥180,000.00</td> |
| | | </tr> |
| | | |
| | | <tr> |
| | | <td>000001</td> |
| | | <td>500</td> |
| | | <td>¥10.00</td> |
| | | <td>¥5,000.00</td> |
| | | </tr> |
| | | |
| | | </table> |
| | | |
| | | <h3>交易记录</h3> |
| | | <table> |
| | | <tr> |
| | | <th>时间</th> |
| | | <th>股票代码</th> |
| | | <th>方向</th> |
| | | <th>价格</th> |
| | | <th>数量</th> |
| | | <th>金额</th> |
| | | </tr> |
| | | |
| | | <tr> |
| | | <td>09:30:00</td> |
| | | <td>600519</td> |
| | | <td>买入</td> |
| | | <td>¥1,800.00</td> |
| | | <td>100</td> |
| | | <td>¥180,000.00</td> |
| | | </tr> |
| | | |
| | | <tr> |
| | | <td>10:30:00</td> |
| | | <td>000001</td> |
| | | <td>买入</td> |
| | | <td>¥10.00</td> |
| | | <td>500</td> |
| | | <td>¥5,000.00</td> |
| | | </tr> |
| | | |
| | | </table> |
| | | |
| | | <h3>周度分析</h3> |
| | | <div class="summary"> |
| | | <p>总交易次数: 2</p> |
| | | <p>最活跃交易日: 2026-03-03</p> |
| | | </div> |
| | | |
| | | </body> |
| | | </html> |
| New file |
| | |
| | | { |
| | | "period": "2024-01-01 至 2024-01-07", |
| | | "account": { |
| | | "cash": 815000.0, |
| | | "total_value": 1000000.0, |
| | | "positions_value": 185000.0, |
| | | "pnl": 0.0 |
| | | }, |
| | | "positions": { |
| | | "600519": { |
| | | "stock_code": "600519", |
| | | "quantity": 100, |
| | | "avg_price": 1800.0, |
| | | "market_value": 180000.0 |
| | | }, |
| | | "000001": { |
| | | "stock_code": "000001", |
| | | "quantity": 500, |
| | | "avg_price": 10.0, |
| | | "market_value": 5000.0 |
| | | } |
| | | }, |
| | | "trades": [ |
| | | { |
| | | "time": "09:30:00", |
| | | "stock_code": "600519", |
| | | "side": "buy", |
| | | "price": 1800.0, |
| | | "quantity": 100 |
| | | }, |
| | | { |
| | | "time": "10:30:00", |
| | | "stock_code": "000001", |
| | | "side": "buy", |
| | | "price": 10.0, |
| | | "quantity": 500 |
| | | } |
| | | ], |
| | | "summary": { |
| | | "total_positions": 2, |
| | | "total_value": 1000000.0, |
| | | "total_cash": 815000.0, |
| | | "total_pnl": 0.0, |
| | | "buy_trades": 2, |
| | | "sell_trades": 0, |
| | | "total_trades": 2 |
| | | }, |
| | | "weekly_analysis": { |
| | | "trades_by_date": { |
| | | "2026-03-03": 2 |
| | | }, |
| | | "total_weekly_trades": 2, |
| | | "most_active_day": "2026-03-03" |
| | | } |
| | | } |