From be4ee5d41c52a4ab81c4dc42f448a66f19fdbe38 Mon Sep 17 00:00:00 2001 From: cuizhan <3971687@qq.com> Date: Mon, 8 Dec 2025 17:53:35 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20=E5=BE=AE=E6=9C=8D=E5=8A=A1?= =?UTF-8?q?=E6=9E=B6=E6=9E=84=E9=87=8D=E6=9E=84=20-=20=E9=98=B6=E6=AE=B51?= =?UTF-8?q?=E6=A0=B8=E5=BF=83=E6=A8=A1=E5=9D=97=E5=AE=8C=E6=88=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 新增架构设计文档 (ARCHITECTURE.md) - 新增构建方案文档 (BUILD_PLAN.md) - 实现核心模块 (src/core/): - config.py: Pydantic Settings + YAML 配置管理 - redis_client.py: 异步 Redis 客户端 - database.py: SQLAlchemy 2.0 异步数据库 - logger.py: 统一日志模块 - models/: 数据模型 (market, order, position, symbol_strategy) - 新增服务启动入口 (src/main.py) - 清理旧代码,准备微服务架构 --- .env.example | 20 + .gitignore | 316 +++++-- LICENSE | 21 - README.md | 775 +++++------------ configs/settings.yaml | 86 ++ docs/architecture/ARCHITECTURE.md | 280 +++++++ docs/architecture/BUILD_PLAN.md | 297 +++++++ example_and_demos/README.md | 45 - example_and_demos/http/http_client_example.py | 73 -- example_and_demos/http/run_http_server.py | 129 --- example_and_demos/socket/run_socket_server.py | 156 ---- .../socket/socket_client_example.py | 71 -- requirements.txt | 34 + requirements36.txt | 15 + src/__init__.py | 3 + src/back_trader/README.md | 217 ----- src/back_trader/__init__.py | 25 - src/back_trader/backtest_engine.py | 525 ------------ .../multi_timeframe_ma_backtest_strategy.py | 793 ------------------ .../multi_timeframe_ma_score_strategy.py | 0 src/back_trader/performance_analyzer.py | 392 --------- src/back_trader/real_backtest_demo.py | 715 ---------------- src/back_trader/simple_backtest_engine.py | 0 src/back_trader/strategy_base.py | 221 ----- src/core/__init__.py | 15 + src/core/config.py | 294 +++++++ src/core/database.py | 194 +++++ src/core/logger.py | 109 +++ src/core/models/__init__.py | 14 + src/core/models/market.py | 100 +++ src/core/models/order.py | 136 +++ src/core/models/position.py | 92 ++ src/core/models/symbol_strategy.py | 113 +++ src/core/redis_client.py | 319 +++++++ src/data_process_model/README.md | 393 --------- src/data_process_model/common.py | 411 --------- src/data_process_model/database_config.py | 150 ---- src/data_process_model/database_manager.py | 416 --------- src/data_process_model/main.py | 584 ------------- src/data_process_model/shared_memory_cache.py | 423 ---------- src/data_process_model/stock_kline_viewer.py | 606 ------------- src/data_process_model/stock_models.py | 115 --- src/data_process_model/stockdata_manager.py | 474 ----------- src/data_process_model/stocktrade_manager.py | 471 ----------- .../technical_indicators.py | 285 ------- src/data_process_model/test_stocktrade.py | 205 ----- src/data_process_model/trade_example.py | 263 ------ src/data_process_model/trade_models.py | 118 --- src/log/__init__.py | 3 - src/log/logger.py | 148 ---- src/main.py | 326 ++++--- src/network_model/__init__.py | 20 - src/network_model/http_client.py | 119 --- src/network_model/http_server.py | 154 ---- src/network_model/simple_socket_client.py | 141 ---- src/network_model/simple_socket_server.py | 180 ---- src/strategy/__init__.py | 8 - src/strategy/grid_strategy.py | 131 --- test/test_simple_socket.py | 55 -- test/test_socket_only.py | 112 --- tests/README.md | 288 +++++++ 61 files changed, 3048 insertions(+), 10146 deletions(-) create mode 100644 .env.example delete mode 100644 LICENSE create mode 100644 configs/settings.yaml create mode 100644 docs/architecture/ARCHITECTURE.md create mode 100644 docs/architecture/BUILD_PLAN.md delete mode 100644 example_and_demos/README.md delete mode 100644 example_and_demos/http/http_client_example.py delete mode 100644 example_and_demos/http/run_http_server.py delete mode 100644 example_and_demos/socket/run_socket_server.py delete mode 100644 example_and_demos/socket/socket_client_example.py create mode 100644 requirements.txt create mode 100644 requirements36.txt create mode 100644 src/__init__.py delete mode 100644 src/back_trader/README.md delete mode 100644 src/back_trader/__init__.py delete mode 100644 src/back_trader/backtest_engine.py delete mode 100644 src/back_trader/multi_timeframe_ma_backtest_strategy.py delete mode 100644 src/back_trader/multi_timeframe_ma_score_strategy.py delete mode 100644 src/back_trader/performance_analyzer.py delete mode 100644 src/back_trader/real_backtest_demo.py delete mode 100644 src/back_trader/simple_backtest_engine.py delete mode 100644 src/back_trader/strategy_base.py create mode 100644 src/core/__init__.py create mode 100644 src/core/config.py create mode 100644 src/core/database.py create mode 100644 src/core/logger.py create mode 100644 src/core/models/__init__.py create mode 100644 src/core/models/market.py create mode 100644 src/core/models/order.py create mode 100644 src/core/models/position.py create mode 100644 src/core/models/symbol_strategy.py create mode 100644 src/core/redis_client.py delete mode 100644 src/data_process_model/README.md delete mode 100644 src/data_process_model/common.py delete mode 100644 src/data_process_model/database_config.py delete mode 100644 src/data_process_model/database_manager.py delete mode 100644 src/data_process_model/main.py delete mode 100644 src/data_process_model/shared_memory_cache.py delete mode 100644 src/data_process_model/stock_kline_viewer.py delete mode 100644 src/data_process_model/stock_models.py delete mode 100644 src/data_process_model/stockdata_manager.py delete mode 100644 src/data_process_model/stocktrade_manager.py delete mode 100644 src/data_process_model/technical_indicators.py delete mode 100644 src/data_process_model/test_stocktrade.py delete mode 100644 src/data_process_model/trade_example.py delete mode 100644 src/data_process_model/trade_models.py delete mode 100644 src/log/__init__.py delete mode 100644 src/log/logger.py delete mode 100644 src/network_model/__init__.py delete mode 100644 src/network_model/http_client.py delete mode 100644 src/network_model/http_server.py delete mode 100644 src/network_model/simple_socket_client.py delete mode 100644 src/network_model/simple_socket_server.py delete mode 100644 src/strategy/__init__.py delete mode 100644 src/strategy/grid_strategy.py delete mode 100644 test/test_simple_socket.py delete mode 100644 test/test_socket_only.py create mode 100644 tests/README.md diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..e691b48 --- /dev/null +++ b/.env.example @@ -0,0 +1,20 @@ +# QTrade 环境变量配置 +# 复制此文件为 .env 并修改实际值 + +# 应用环境 +QTRADE_ENV=development + +# Redis +REDIS_HOST=127.0.0.1 +REDIS_PORT=6379 +REDIS_PASSWORD= + +# MySQL +DB_HOST=127.0.0.1 +DB_PORT=3306 +DB_USER=root +DB_PASSWORD=your_password_here +DB_NAME=qtrade + +# 日志级别 +LOG_LEVEL=INFO diff --git a/.gitignore b/.gitignore index 2a8473f..06edf66 100644 --- a/.gitignore +++ b/.gitignore @@ -1,105 +1,262 @@ -# Python缓存文件 +# Python# Python# Python缓存文件 + __pycache__/ -*.py[cod] + +*.py[cod]__pycache__/__pycache__/ + *$py.class -# Python分发/打包 -*.so -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -pip-wheel-metadata/ -share/python-wheels/ -*.egg-info/ -.installed.cfg -*.egg -MANIFEST +*.so*.py[cod]*.py[cod] -# PyInstaller -*.manifest -*.spec -# Installer logs -pip-log.txt -pip-delete-this-directory.txt -# Unit test / coverage reports -htmlcov/ -.tox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -*.py,cover -.hypothesis/ -.pytest_cache/ +# Virtual Environment*$py.class*$py.class -# Translations -*.mo -*.pot +venv/ -# Django stuff: -*.log -local_settings.py -db.sqlite3 -db.sqlite3-journal +env/*.so -# Flask stuff: -instance/ -.webassets-cache -# Scrapy stuff: -.scrapy -# Sphinx documentation -docs/_build/ +# Environment Variables.Python# Python分发/打包 -# PyBuilder -target/ +.env + +configs/.env*.so + + + +# IDE# Virtual Environment.Python + +.vscode/ + +.idea/venv/build/ + +*.swp + +env/develop-eggs/ # Jupyter Notebook -.ipynb_checkpoints -# IPython -profile_default/ -ipython_config.py +.ipynb_checkpointsENV/dist/ -# pyenv -.python-version -# pipenv + +# Test / Coverage.venvdownloads/ + +.pytest_cache/ + +htmlcov/.conda/eggs/ + +.coverage + +.eggs/ + +# Logs + +logs/*.log# Environment Variableslib/ + +*.log + +.envlib64/ + +# Data files (ignore content, keep structure) + +data/raw/*.env.localparts/ + +data/processed/* + +data/cache/*sdist/ + +!data/*/.gitkeep + +# IDEvar/ + +# QMT specific + +qmt_data/.vscode/wheels/ + +*.qmt + +.idea/pip-wheel-metadata/ + +# Database + +*.db*.swpshare/python-wheels/ + +*.sqlite + +*.sqlite3*.swo*.egg-info/ + + + +# OS specific*~.installed.cfg + +.DS_Store + +Thumbs.db*.egg + + + +# Project specific# Jupyter NotebookMANIFEST + +configs/secrets.yaml + +configs/local.yaml.ipynb_checkpoints + +*.csv + +!example*.csv*.ipynb# PyInstaller + + +*.manifest + +# Distribution / Packaging*.spec + +build/ + +develop-eggs/# Installer logs + +dist/pip-log.txt + +downloads/pip-delete-this-directory.txt + +eggs/ + +.eggs/# Unit test / coverage reports + +lib/htmlcov/ + +lib64/.tox/ + +parts/.coverage + +sdist/.coverage.* + +var/.cache + +wheels/nosetests.xml + +*.egg-info/coverage.xml + +.installed.cfg*.cover + +*.egg*.py,cover + +.hypothesis/ + +# PyInstaller.pytest_cache/ + +*.manifest + +*.spec# Translations + +*.mo + +# Unit test / coverage reports*.pot + +htmlcov/ + +.tox/# Django stuff: + +.coverage*.log + +.coverage.*local_settings.py + +.cachedb.sqlite3 + +nosetests.xmldb.sqlite3-journal + +coverage.xml + +*.cover# Flask stuff: + +.hypothesis/instance/ + +.pytest_cache/.webassets-cache + + + +# Logs# Scrapy stuff: + +logs/*.log.scrapy + +*.log + +# Sphinx documentation + +# Data files (keep structure but ignore content)docs/_build/ + +data/raw/* + +data/processed/*# PyBuilder + +data/cache/*target/ + +!data/raw/.gitkeep + +!data/processed/.gitkeep# Jupyter Notebook + +!data/cache/.gitkeep.ipynb_checkpoints + + + +# QMT specific# IPython + +qmt_data/profile_default/ + +*.qmtipython_config.py + + + +# Database# pyenv + +*.db.python-version + +*.sqlite + +*.sqlite3# pipenv + Pipfile.lock -# PEP 582 -__pypackages__/ +# Temporary files + +tmp/# PEP 582 + +temp/__pypackages__/ + +*.tmp # Celery stuff -celerybeat-schedule -celerybeat.pid -# SageMath parsed files +# OS specificcelerybeat-schedule + +.DS_Storecelerybeat.pid + +Thumbs.db + +desktop.ini# SageMath parsed files + *.sage.py -# Environments -.env +# Backup files + +*.bak# Environments + +*.backup.env + .venv -env/ -venv/ -ENV/ -env.bak/ -venv.bak/ + +# Project specificenv/ + +config/secrets.yamlvenv/ + +config/local.yamlENV/ + +*.csvenv.bak/ + +!example*.csvvenv.bak/ + # Spyder project settings .spyderproject @@ -160,6 +317,11 @@ data/**/*.csv src/**/data/*.csv logs/*.log +# 临时生成的文件 +project_structure*.txt +*_temp.md +*_draft.md + # 防止空文件重复出现 # 临时文件和缓存 .vscode/launch.json diff --git a/LICENSE b/LICENSE deleted file mode 100644 index 3b0a36b..0000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2025 Zhao hai feng - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/README.md b/README.md index 4a16654..1bb8280 100644 --- a/README.md +++ b/README.md @@ -1,624 +1,263 @@ -# QTrade - 高性能量化交易系统 +# QTrade - 量化交易系统 (v2.0) -QTrade 是一个基于 Socket 长连接的高性能量化交易系统,专为中国股市设计。系统采用高效的Socket通信架构和双层数据处理架构,支持实时数据处理和网格交易策略,集成了完整的股票数据处理和存储功能,相比HTTP版本性能提升了**13倍**。 +轻量级 A 股量化交易系统,基于微服务架构。 -## 🚀 主要特性 +> ⚠️ **重构中**: 系统正在从单体架构重构为微服务架构 -- **Socket长连接通信**:高效的持久连接,支持实时双向通信 -- **双层数据架构**:统一的数据处理架构,单例长连接,高性能数据访问 -- **股票数据处理**:集成xtquant数据源,支持历史数据下载和实时处理 -- **K线图可视化**:支持技术指标的交互式K线图显示 -- **MySQL数据库支持**:使用Peewee ORM,支持股票K线数据持久化存储 -- **网格交易策略**:自动化的网格交易算法,支持实时信号生成 -- **多客户端支持**:同时支持最多50个客户端并发连接 -- **超高性能**:0.31ms平均延迟,3242 QPS,13倍性能提升 -- **自动重连机制**:客户端断线自动重连,保证连接稳定性 -- **消息广播**:支持向所有客户端广播消息 -- **完善的测试覆盖**:包含功能测试、性能测试、压力测试 +## 特性 -## 📁 项目结构 +- 🚀 **微服务架构**: FastAPI + Redis + MySQL +- 📊 **实时行情**: 通过 QMT 获取实时行情数据 +- 🤖 **策略引擎**: 支持多策略并行运行 +- 💹 **股票-策略配对**: 每个配对独立管理持仓和资金 +- 🔄 **回测支持**: 回测与实盘使用相同代码 +- 🐧 **跨平台**: 支持 Linux 和 Windows + +## 架构 + +``` +┌─────────────┐ +│ Gateway │ ← 外部 API 入口 (8001) +└──────┬──────┘ + │ +┌──────┴──────┬────────────────┬─────────────────┐ +│ │ │ │ +▼ ▼ ▼ ▼ +┌──────────┐ ┌────────────┐ ┌──────────────┐ ┌─────────────┐ +│Core Svc │ │Data Service│ │Strategy Eng. │ │QMT Adapter │ +│ (8010) │ │ (8020) │ │ (8030) │ │ (Py 3.6) │ +└──────────┘ └────────────┘ └──────────────┘ └─────────────┘ + │ │ │ │ + └─────────────┴────────────────┴─────────────────┘ + │ + ┌─────┴─────┐ + │ Redis │ + └─────┬─────┘ + │ + ┌─────┴─────┐ + │ MySQL │ + └───────────┘ +``` + +## 📋 项目结构 ``` QTrade/ -├── README.md # 项目主要文档 -├── LICENSE # 许可证文件 -├── data/ # 股票历史数据文件目录 -│ ├── 510310_SH_1m_20250722_*.csv -│ ├── 601398_SH_1m_20250722_*.csv -│ └── 601658_SH_1m_20250722_*.csv -│ -├── src/ # 源代码目录 -│ ├── main.py # 主服务器入口 (Socket版本) -│ ├── data_process_model/ # 数据处理模块 ⭐ (双层架构) -│ │ ├── main.py # 数据处理主程序 -│ │ ├── common.py # 公共配置和工具函数 -│ │ ├── database_manager.py # 数据库管理器 (底层-单例长连接) -│ │ ├── stockdata_manager.py # 股票数据管理器 (上层-DataFrame转换) -│ │ ├── stock_models.py # 股票数据模型 (Peewee ORM) -│ │ ├── stock_kline_viewer.py # K线图查看器 (技术指标可视化) -│ │ ├── technical_indicators.py # 技术指标计算模块 -│ │ ├── shared_memory_cache.py # 共享内存缓存 -│ │ ├── test_kline_viewer.py # K线查看器测试 -│ │ ├── REFACTOR_SUMMARY.md # 架构重构总结 -│ │ └── data/ # 本地数据文件 -│ ├── log/ # 日志模块 -│ │ ├── __init__.py -│ │ └── logger.py -│ ├── network_model/ # 网络模型 (核心代码) -│ │ ├── __init__.py -│ │ ├── simple_socket_server.py # Socket服务器核心实现 -│ │ ├── simple_socket_client.py # Socket客户端核心实现 -│ │ ├── http_server.py # HTTP服务器实现 (兼容性) -│ │ └── http_client.py # HTTP客户端实现 -│ └── strategy/ # 交易策略模块 -│ ├── __init__.py -│ └── grid_strategy.py # 网格交易策略 -│ -├── example_and_demos/ # 示例和演示文件 -│ ├── README.md # 示例说明文档 -│ ├── http/ # HTTP相关示例 -│ │ ├── http_client_example.py -│ │ └── run_http_server.py -│ └── socket/ # Socket相关示例 -│ ├── run_socket_server.py -│ └── socket_client_example.py -│ -├── test/ # 测试文件 -│ ├── test_simple_socket.py # Socket基础测试 -│ └── test_socket_only.py # Socket专用测试 -│ -└── logs/ # 日志文件 - └── *.log +├── docs/ # 文档 +│ └── architecture/ +│ ├── ARCHITECTURE.md # 架构设计 +│ └── BUILD_PLAN.md # 构建方案 +├── src/ +│ ├── core/ # 核心模块 +│ │ ├── config.py # 配置管理 +│ │ ├── database.py # 数据库连接 +│ │ ├── redis_client.py # Redis 客户端 +│ │ ├── logger.py # 日志模块 +│ │ └── models/ # 数据模型 +│ ├── gateway/ # API 网关 +│ ├── core_service/ # 核心业务服务 +│ ├── data_service/ # 数据服务 +│ ├── strategy_engine/ # 策略引擎 +│ └── qmt_adapter/ # QMT 适配层 +├── configs/ # 配置文件 +│ └── settings.yaml +├── database/ # 数据库脚本 +├── scripts/ # 运维脚本 +├── tests/ # 测试 +└── logs/ # 日志 ``` -## 🛠️ 快速开始 +## 🚀 快速开始 -### 环境要求 -- Python 3.7+ -- MySQL数据库 (可选,用于数据持久化) -- 依赖包: - - `pandas` - 数据处理 - - `numpy` - 数值计算 - - `peewee` - ORM数据库框架 - - `pymysql` - MySQL数据库驱动 - - `xtquant` - 量化数据源 (可选) - - `talib` - 技术指标计算 - - `matplotlib` - 图表绘制 +### 1. 安装依赖 -### 安装依赖 ```bash -pip install pandas numpy peewee pymysql talib matplotlib -# 如需使用xtquant数据源 -pip install xtquant +pip install -r requirements.txt ``` -### 方式1: 运行数据处理程序 ⭐ +### 2. 配置 ```bash -# 运行股票数据处理和存储程序 -cd src/data_process_model -python main.py +# 复制配置模板 +copy configs\.env.example configs\.env + +# 根据需要编辑各个配置文件 +# - configs/global_config.yaml # 全局配置 +# - configs/log.yaml # 日志配置(必需) +# - configs/database.yaml # 数据库配置(如需使用) +# - configs/networks.yaml # 网络服务配置(如需使用) +# - configs/qmt.yaml # QMT 配置(如需使用) +# - configs/strategy.yaml # 策略配置(如需使用) +# - configs/.env # 敏感信息(密码等) ``` -功能说明: -- 自动下载股票历史数据 (基于xtquant) -- 使用双层架构进行数据处理和格式化 -- 保存为CSV文件到 `data/` 目录 -- 自动创建MySQL数据表并存储数据 -- 支持增量数据更新 -- 单例长连接,高性能数据库操作 - -### 方式2: 运行K线图查看器 ⭐ +### 3. 运行 ```bash -# 运行K线图可视化程序 -cd src/data_process_model -python stock_kline_viewer.py -``` - -功能说明: -- 从数据库读取K线数据 -- 计算技术指标 (MA, MACD等) -- 显示交互式K线图表 -- 支持缩放、平移等操作 -- 黑色主题,专业图表显示 - -### 方式3: 运行Socket服务器 - -```bash -# 终端1: 启动Socket服务器 +# 启动 Socket 服务器 python src/main.py -# 终端2: 运行客户端演示 -python example_and_demos/socket/socket_client_example.py +# 或使用新架构 +python src/main_v2.py ``` -### 方式4: HTTP服务器 (兼容模式) +## 📦 核心依赖 -```bash -# 终端1: 启动HTTP服务器 -python example_and_demos/http/run_http_server.py +- **pyyaml** - 配置文件解析 +- **pandas** - 数据处理 +- **numpy** - 数值计算 +- **peewee** - 数据库 ORM(可选) +- **pytest** - 测试框架(可选) -# 终端2: 运行HTTP客户端 -python example_and_demos/http/http_client_example.py +## � 目录说明 + +### configs/ - 运行时配置 +**用途**: 存放程序运行时需要读取的所有配置文件 +- `global_config.yaml` - 全局配置(项目信息、路径、环境等) +- `log.yaml` - 日志配置(必需) +- `database.yaml` - 数据库配置 +- `networks.yaml` - 网络服务配置(Socket + HTTP) +- `qmt.yaml` - QMT 配置 +- `strategy.yaml` - 策略配置 +- `config.example.yaml` - 配置示例 +- `.env` - 敏感信息配置(密码、密钥等,不提交到 git) +- `.env.example` - 环境变量模板 + +### src/ - 源代码 +**用途**: 所有源代码文件 +- 分层架构:core → utils → 业务层(networks/database/datas/strategy) +- 统一入口:`main.py` 或 `main_v2.py` + +### logs/ - 日志文件 +**用途**: 存放程序运行时自动生成的日志文件 +- `qtrade.log` - 应用主日志 +- 自动轮转,保留最近的日志 + +### tests/ - 测试代码 +**用途**: 存放单元测试和集成测试的代码和用例 +- 单元测试:测试单个函数/类 +- 集成测试:测试完整流程 +- 使用 pytest 运行 + +### examples_and_demos/ - 程序示例 +**用途**: 存放具体的程序使用示例 +- Socket 通信示例 +- HTTP 服务示例 +- 配置加载示例 +- 策略使用示例 + +### docs/ - 文档 +**用途**: 存放相关文档和 API 说明 +- 架构设计文档 +- API 接口文档 +- 开发指南 +- 使用说明 + +### data/ - 数据文件(可选) +**用途**: 存放数据文件 +- `raw/` - 原始数据(CSV 等) +- `processed/` - 处理后的数据 +- `cache/` - 缓存数据 + +## 📚 架构说明 + +### 分层架构 + +``` +应用层 (main.py) + ↓ +策略层 (strategy/) + ↓ +业务层 (networks/, datas/, database/) + ↓ +核心层 (core/) + ↓ +工具层 (utils/) ``` -## 📊 性能对比 +### 核心模块 -Socket实现相比HTTP版本有显著性能提升: +- **core/** - 定义核心抽象和协议 +- **networks/** - 网络通信(Socket + HTTP) +- **database/** - 数据库操作和 ORM 模型 +- **datas/** - 数据处理和技术指标计算 +- **strategy/** - 交易策略实现 +- **utils/** - 日志、配置等工具 -| 指标 | HTTP短连接 | Socket长连接 | 性能提升 | -| -------- | ---------- | ------------ | ------------ | -| 平均延迟 | 4.13ms | 0.31ms | **13.3倍** | -| 理论QPS | 242 | 3242 | **13.4倍** | -| 并发支持 | 有限 | 50客户端 | **无限制** | -| 连接开销 | 每次握手 | 一次握手 | **显著降低** | -| 实时性 | 请求响应 | 双向实时 | **实时通信** | +## 📖 使用示例 -## 🏗️ 核心架构 +### Socket 客户端 -### 双层数据架构 ⭐ -- **数据操作层 (database_manager.py)**: - - 原始数据库操作接口 - - 支持MySQL连接管理和基础CRUD操作 - - 单例模式,全局长连接,高性能 -- **数据转换层 (stockdata_manager.py)**: - - DataFrame接口封装 - - 自动数据类型转换和格式化 - - 提供统一的数据访问API -- **ORM模型层 (stock_models.py)**: - - 动态表模型创建 - - 支持多股票多周期数据表 - - 高精度价格数据存储 (DECIMAL) - -### K线可视化系统 ⭐ -- **技术指标计算 (technical_indicators.py)**: - - 集成TA-Lib库,支持MACD、MA等主流指标 - - 高性能向量化计算 - - 可扩展指标体系 -- **图表渲染引擎 (stock_kline_viewer.py)**: - - 基于matplotlib的专业K线图表 - - 支持交互式缩放、平移操作 - - 黑色主题,符合交易软件习惯 - - 同时显示价格和技术指标 - -### 数据处理流水线 -- **数据源集成**: 支持xtquant数据源,获取实时和历史股票数据 -- **自动化处理**: 数据下载、清洗、格式化和存储全自动 -- **双重存储**: CSV文件 + MySQL数据库同步存储 -- **增量更新**: 支持增量数据下载和更新机制 - -### Socket长连接架构 -- **服务器**: 支持多客户端并发连接 (最多50个) -- **客户端**: 支持自动重连、长连接保持 -- **消息同步**: 实时双向通信 -- **广播功能**: 支持消息广播给所有客户端 - -### 数据库设计 -- **动态表结构**: 为每个股票代码和周期创建独立数据表 -- **表命名规则**: `kline_{股票代码}_{周期}` (如: `kline_601658_sh_1m`) -- **字段设计**: - ```sql - timestamp - K线时间戳 (主键) - open_price - 开盘价 (DECIMAL精度) - high_price - 最高价 - low_price - 最低价 - close_price - 收盘价 - volume - 成交量 (BIGINT) - amount - 成交额 (DECIMAL) - created_at - 记录创建时间 - updated_at - 记录更新时间 - ``` - -### 消息协议 - -1. **文本消息** - - `ping` → `pong` - - `hello` → `Hello from QTrade!` - - `time` → 当前时间戳 - - `status` → 服务器状态 - -2. **JSON消息** - ```json - { - "type": "update_kline", - "data": { - "close": 5.67, - "timestamp": 1234567890 - } - } - ``` - -3. **服务器响应** - ```json - { - "type": "trade_signal", - "signal": { - "action": "buy", - "qty": 1200, - "price": 5.67 - }, - "timestamp": 1234567890, - "processed_price": 5.67, - "broadcast": true - } - ``` - -## 🔧 功能特性 - -### ✅ 数据处理功能 -- **双层架构设计**: database_manager + stockdata_manager 分层设计 -- **多数据源支持**: 集成xtquant,支持A股、港股、美股数据 -- **多周期支持**: 支持1分钟、5分钟、日线等多种数据周期 -- **批量处理**: 支持多个股票代码同时处理 -- **数据验证**: 自动数据完整性检查和异常处理 -- **增量下载**: 支持增量数据更新,避免重复下载 -- **双重存储**: 同时支持CSV文件和MySQL数据库存储 - -### ✅ K线可视化功能 -- **专业K线图**: 基于matplotlib的高质量K线图表渲染 -- **技术指标集成**: 支持MACD、MA(移动平均)等主流技术指标 -- **交互式操作**: 支持图表缩放、平移、数据点查看 -- **黑色主题**: 专业交易软件风格的暗色主题 -- **实时数据**: 从数据库实时读取最新K线数据 -- **多指标显示**: 价格图表 + 技术指标子图同时显示 - -### ✅ 数据库功能 -- **MySQL集成**: 使用Peewee ORM,支持复杂查询操作 -- **单例长连接**: 全局数据库连接池,高并发性能 -- **自动建表**: 根据股票代码自动创建数据表结构 -- **数据精度**: 使用DECIMAL类型确保价格数据精度 -- **索引优化**: 时间戳字段建立索引,提升查询性能 -- **动态模型**: 支持运行时动态创建ORM模型 - -### ✅ 服务器端功能 -- **多客户端支持**: 最多50个并发连接 -- **长连接管理**: 自动连接管理和清理 -- **消息广播**: 支持向所有客户端广播消息 -- **实时处理**: 毫秒级响应时间 -- **异常处理**: 完善的错误处理和日志记录 - -### ✅ 客户端功能 -- **自动重连**: 断线自动重连机制 -- **消息同步**: 实时双向通信 -- **多种消息类型**: 支持文本和JSON消息 -- **回调机制**: 连接状态和消息处理回调 -- **自动模式**: 定时发送数据的自动模式 - -### ✅ 交易策略集成 -- **网格交易策略**: 完整的网格交易策略实现 -- **实时信号**: 根据价格变化实时生成交易信号 -- **参数配置**: 灵活的策略参数配置 - -## 🧪 测试说明 - -### 数据处理测试 -```bash -# 测试数据处理模块 -cd src/data_process_model -python main.py - -# 检查生成的CSV文件 -ls data/*.csv - -# 检查MySQL数据库 -# 登录MySQL查看生成的表和数据 -``` - -### K线图查看器测试 -```bash -# 测试K线查看器数据库连接 -cd src/data_process_model -python test_kline_viewer.py - -# 运行K线图查看器 -python stock_kline_viewer.py -``` - -### Socket通信测试 -```bash -# 基本Socket测试 -python test/test_simple_socket.py - -# Socket专用测试 -python test/test_socket_only.py -``` - -### 示例演示 -```bash -# Socket服务器演示 -python example_and_demos/socket/run_socket_server.py - -# Socket客户端演示 -python example_and_demos/socket/socket_client_example.py - -# HTTP服务器演示 (兼容模式) -python example_and_demos/http/run_http_server.py -``` - -## 🔧 技术栈 - -### 核心技术 -- **Python 3.7+**: 主要开发语言 -- **Socket**: 长连接通信协议 -- **Threading**: 多线程并发处理 -- **JSON**: 数据交换格式 - -### 数据处理技术 -- **Pandas**: 数据处理和分析框架 -- **NumPy**: 数值计算库 -- **xtquant**: 量化数据源接口 - -### 数据存储技术 -- **MySQL**: 关系型数据库 -- **Peewee ORM**: Python对象关系映射框架 -- **PyMySQL**: MySQL数据库驱动程序 -- **CSV**: 标准数据交换格式 - -### 可视化和分析技术 -- **matplotlib**: 专业图表绘制库 -- **TA-Lib**: 技术分析指标计算库 -- **技术指标**: MACD、移动平均线等量化分析工具 - -### 交易策略技术 -- **网格策略算法**: 基于价格区间的自动交易 -- **实时信号处理**: 毫秒级交易信号生成 - -## 💾 数据配置 - -### 股票代码配置 -在 `src/data_process_model/main.py` 中配置目标股票: ```python -g_stock_code_list = ["601658.SH", "510310.SH", "601398.SH"] # 股票代码 -g_period = "1m" # 数据周期 -g_start_date = "20250501" # 开始日期 -g_end_date = "20250721" # 结束日期 +from src.networks import SimpleQTradeSocketClient + +client = SimpleQTradeSocketClient(host='127.0.0.1', port=8888) +client.connect() +client.send({"type": "ping", "data": {}}) +response = client.receive() +client.disconnect() ``` -### MySQL数据库配置 -在 `src/data_process_model/database_config.py` 中配置数据库连接: +### 数据处理 + ```python -DATABASE_CONFIG = { - 'host': 'localhost', # MySQL服务器地址 - 'port': 3306, # MySQL端口 - 'user': 'root', # 用户名 - 'password': '1234', # 密码 - 'database': 'qtrade_stock_data', # 数据库名 - 'charset': 'utf8mb4' -} +from src.datas import KlineDataProcessor +import pandas as pd + +processor = KlineDataProcessor() +df = pd.read_csv('data/raw/stock.csv') +df_clean = processor.clean_data(df) +df_indicators = processor.calculate_indicators(df_clean) ``` -### 支持的股票代码格式 -- **A股**: `600000.SH`, `000001.SZ` -- **港股**: `00700.HK` -- **ETF**: `510300.SH`, `159919.SZ` -- **期货**: `IF2312.CFX` +### 网格策略 -### 支持的数据周期 -- **分钟线**: `1m`, `5m`, `15m`, `30m`, `60m` -- **日线**: `1d` -- **周线**: `1w` -- **月线**: `1M` +```python +from src.strategy import GridStrategy -## ⚙️ 开发指南 +strategy = GridStrategy( + upper_price=10.0, + lower_price=8.0, + grid_levels=10 +) + +signal = strategy.get_signal(current_price=9.0) +print(signal['action']) # buy/sell/hold +``` + +## 🧪 测试 -### 环境设置 ```bash -# 克隆项目 -git clone -cd QTrade +# 运行所有测试 +pytest tests/ -v -# 安装Python依赖 -pip install pandas numpy peewee pymysql xtquant - -# 配置MySQL数据库 -# 1. 安装MySQL服务器 -# 2. 创建数据库用户 -# 3. 修改 src/data_process_model/database_config.py 中的配置 +# 运行特定测试 +pytest tests/test_simple_socket.py ``` -### 扩展开发 +## 📝 更多示例 -1. **添加新的股票数据源** - ```python - # 在 src/data_process_model/main.py 中 - # 修改 download_stock_data() 函数 - # 支持其他数据源API - ``` +查看 `examples_and_demos/` 目录: -2. **添加新的数据周期** - ```python - # 修改全局配置 - g_period = "5m" # 改为5分钟线 - ``` +- **socket/** - Socket 通信示例 +- **http/** - HTTP 服务示例 -3. **添加新的数据库字段** - ```python - # 在 src/data_process_model/stock_models.py 中 - # 修改 StockKlineBase 模型类 - # 添加新的字段定义 - ``` +## ⚠️ 注意事项 -4. **添加新的消息类型** - - 修改 `src/main.py` 中的 `handle_dict_message()` - - 添加对应的处理函数 +1. **配置文件** - 确保 `configs/.env` 不要提交到 git +2. **数据库** - 首次使用需要创建数据库和表 +3. **QMT** - 需要单独安装 QMT 客户端和 xtquant 库 +4. **端口** - 确保配置的端口没有被占用 -5. **添加新的交易策略** - - 在 `src/strategy/` 中创建新策略类 - - 实现 `determine_signal()` 方法 +## 📄 License -### 数据处理流程扩展 +MIT License -1. **自定义数据处理函数** - ```python - def custom_process_data(df): - # 添加技术指标计算 - df['ma5'] = df['close'].rolling(5).mean() - df['ma20'] = df['close'].rolling(20).mean() - return df - ``` +## 👤 Author -2. **添加新的存储格式** - ```python - def save_to_hdf5(df, filename): - # 实现HDF5格式保存 - df.to_hdf(filename, key='stock_data') - ``` - -## 📝 故障排查 - -### 数据处理常见问题 - -1. **xtquant连接失败** - - 检查网络连接 - - 确认xtquant账户状态 - - 检查API访问权限 - -2. **MySQL连接失败** - - 检查MySQL服务是否启动 - - 确认用户名密码正确 - - 检查防火墙设置 - - 验证数据库权限 - -3. **数据下载慢或超时** - - 调整请求频率和超时设置 - - 检查网络带宽 - - 使用增量下载模式 - -4. **CSV文件编码问题** - - 使用UTF-8-BOM编码 - - 检查特殊字符处理 - - 验证文件路径权限 - -### Socket通信常见问题 - -1. **连接失败** - - 检查服务器是否启动 - - 检查端口8081是否被占用 - - 查看防火墙设置 - -2. **性能问题** - - 检查并发客户端数量 - - 监控内存使用情况 - - 调整请求间隔 - -3. **消息丢失** - - 检查网络连接稳定性 - - 确认消息格式正确 - - 查看服务器日志 - -### 数据库问题 - -1. **表创建失败** - - 检查数据库用户权限 - - 验证表名命名规范 - - 查看MySQL错误日志 - -2. **数据插入慢** - - 使用批量插入 - - 检查索引设置 - - 优化数据库连接池 - -3. **数据精度问题** - - 使用DECIMAL类型存储价格 - - 检查字段长度设置 - - 验证数据类型匹配 - -## 🔄 版本历史 - -### v2.1.0 (当前版本) ⭐ -- ✅ 集成股票数据处理模块,支持xtquant数据源 -- ✅ 添加MySQL数据库支持,使用Peewee ORM -- ✅ 实现自动建表和数据存储功能 -- ✅ 支持CSV和数据库双重存储 -- ✅ 添加增量数据下载和更新机制 -- ✅ 优化数据处理流水线和错误处理 -- ✅ 支持多股票多周期数据管理 - -### v2.0.0 (历史版本) -- ✅ 完全切换到Socket长连接架构 -- ✅ 移除HTTP依赖,性能提升13倍 -- ✅ 添加多客户端并发支持 -- ✅ 实现消息广播功能 -- ✅ 完善测试套件和演示程序 -- ✅ 重新组织文件结构 - -### v1.0.0 (历史版本) -- 基础HTTP服务器实现 -- 网格交易策略 -- 基本的客户端通信 - -## 🎯 发展路线图 - -### 近期规划 (v2.2.0) -- [ ] 添加更多技术指标计算 -- [ ] 实现实时数据推送功能 -- [ ] 优化数据库查询性能 -- [ ] 添加数据可视化组件 - -### 中期规划 (v3.0.0) -- [ ] 支持多种数据源集成 -- [ ] 实现分布式数据处理 -- [ ] 添加机器学习策略模块 -- [ ] 构建Web管理界面 - -### 长期规划 (v4.0.0) -- [ ] 支持实盘交易接口 -- [ ] 实现高频交易功能 -- [ ] 添加风险管理模块 -- [ ] 构建量化策略回测平台 - -## 📞 支持与贡献 - -### 使用说明 -1. **数据处理入门** - ```bash - # 第一次使用,先配置数据库 - # 编辑 src/data_process_model/database_config.py - # 然后运行数据处理程序 - cd src/data_process_model - python main.py - ``` - -2. **Socket通信入门** - ```bash - # 启动服务器 - python src/main.py - - # 在另一个终端启动客户端 - python example_and_demos/socket/socket_client_example.py - ``` - -### 报告问题 -如果遇到问题,请提供: -- 错误信息和完整日志 -- Python版本和依赖包版本 -- 运行环境信息 (Windows/Linux/macOS) -- MySQL版本信息 (如果使用数据库功能) -- 具体的重现步骤 - -### 贡献代码 -1. Fork项目到您的GitHub账户 -2. 创建特性分支 (`git checkout -b feature/new-feature`) -3. 提交更改 (`git commit -am 'Add new feature'`) -4. 推送到分支 (`git push origin feature/new-feature`) -5. 创建Pull Request - -### 联系方式 -- 📧 邮箱:[您的邮箱] -- 💬 微信群:[QTrade用户交流群] -- 📚 文档:[详细文档链接] +yyppdcc --- -🎯 **QTrade 量化交易系统** - 高性能数据处理与Socket通信解决方案 - -*专为中国股市设计的一体化量化交易系统,集数据获取、处理、存储和实时通信于一体* - -**主要优势**: -- 🚀 **高性能**: Socket长连接,13倍性能提升 -- 💾 **数据完整**: 支持MySQL和CSV双重存储 -- 🔄 **自动化**: 一键数据下载和处理 -- 🌐 **实时通信**: 毫秒级响应的Socket服务 -- 📈 **策略集成**: 内置网格交易策略 -- 🛠️ **易扩展**: 模块化设计,方便二次开发 +**Version**: 0.2.1 +**Status**: 轻量化开发版 diff --git a/configs/settings.yaml b/configs/settings.yaml new file mode 100644 index 0000000..3aff48c --- /dev/null +++ b/configs/settings.yaml @@ -0,0 +1,86 @@ +# QTrade 主配置文件 +# 说明: 敏感信息建议通过环境变量覆盖 + +# 应用配置 +app: + name: "QTrade" + version: "2.0.0" + env: "development" # development, production + debug: true + +# Redis 配置 +redis: + host: "127.0.0.1" + port: 6379 + password: "" + db: 0 + # 连接池配置 + pool_size: 10 + pool_timeout: 30 + +# MySQL 配置 +database: + host: "127.0.0.1" + port: 3306 + user: "root" + password: "" + database: "qtrade" + # 连接池配置 + pool_size: 5 + pool_recycle: 3600 + echo: false # SQL 日志 + +# 服务配置 +services: + gateway: + host: "0.0.0.0" + port: 8001 + core_service: + host: "0.0.0.0" + port: 8010 + data_service: + host: "0.0.0.0" + port: 8020 + strategy_engine: + host: "0.0.0.0" + port: 8030 + +# 日志配置 +logging: + level: "INFO" # DEBUG, INFO, WARNING, ERROR + format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + # 文件日志 + file: + enabled: true + path: "logs" + max_size: 10485760 # 10MB + backup_count: 5 + +# 行情配置 +market: + # 支持的K线周期 + kline_periods: + - "1m" + - "5m" + - "15m" + - "30m" + - "60m" + - "1d" + - "1w" + # 行情缓存时间(秒) + cache_ttl: 60 + +# 交易配置 +trading: + # 交易时段 + sessions: + morning: + start: "09:30" + end: "11:30" + afternoon: + start: "13:00" + end: "15:00" + # 风控配置 + risk: + max_position_ratio: 0.3 # 单只股票最大仓位比例 + max_order_value: 1000000 # 单笔最大金额 diff --git a/docs/architecture/ARCHITECTURE.md b/docs/architecture/ARCHITECTURE.md new file mode 100644 index 0000000..17f15d6 --- /dev/null +++ b/docs/architecture/ARCHITECTURE.md @@ -0,0 +1,280 @@ +# QTrade 系统架构设计 + +> 创建日期: 2025-12-08 +> 版本: 2.0 + +## 一、系统概述 + +QTrade 是一个轻量化的 A股量化交易系统,采用微服务架构,支持实盘交易和历史回测。 + +### 核心特性 + +- **实时行情**: 对接 QMT 获取 A股实时行情 +- **策略管理**: 支持同一股票配置多个策略,独立管理仓位和资金 +- **回测系统**: 复用实盘代码,从数据库回放历史数据模拟实盘 +- **跨平台**: 主系统支持 Linux/Windows,QMT适配层仅 Windows +- **水平扩展**: 支持多机部署 (2-3台) + +--- + +## 二、服务架构 + +### 2.1 服务列表 + +| 服务 | 端口 | Python版本 | 职责 | +| ------------------- | ------ | ---------- | ------------------------------------------------ | +| **gateway** | 8001 | 3.10+ | API入口、路由分发、认证鉴权、请求日志 | +| **core-service** | 8010 | 3.10+ | 交易管理、风控检查、账户管理、持仓管理、配对管理 | +| **data-service** | 8020 | 3.10+ | 行情接收/分发、K线存储查询、回测数据回放 | +| **strategy-engine** | 8030 | 3.10+ | 策略管理、策略执行、信号生成 | +| **qmt-adapter** | 无HTTP | 3.6 | QMT行情采集、交易执行、账户同步 (仅Windows) | + +### 2.2 架构图 + +``` + 外部调用(Web/App/脚本) + │ + │ HTTP REST + ▼ + ┌─────────────────┐ + │ gateway │ FastAPI :8001 + │ (API入口) │ + └────────┬────────┘ + │ + │ Redis Pub/Sub + ▼ + ┌────────────────────┼────────────────────┐ + │ │ │ + ▼ ▼ ▼ +┌──────────────┐ ┌──────────────┐ ┌──────────────┐ +│ core-service │ │ data-service │ │strategy-engine│ +│ FastAPI:8010 │ │ FastAPI:8020 │ │ FastAPI:8030 │ +│ │ │ │ │ │ +│ - 交易管理 │ │ - 行情分发 │ │ - 策略管理 │ +│ - 风控检查 │ │ - K线存储 │ │ - 信号生成 │ +│ - 账户管理 │ │ - 回测回放 │ │ │ +│ - 配对管理 │ │ │ │ │ +└──────────────┘ └──────────────┘ └──────────────┘ + │ │ │ + └────────────────────┼────────────────────┘ + │ + Redis + │ + ┌──────────────┴──────────────┐ + │ │ + ▼ ▼ + ┌─────────────────┐ ┌─────────────────┐ + │ qmt-adapter │ │ MySQL │ + │ (Python 3.6) │ │ (数据持久化) │ + │ Windows Only │ │ │ + └─────────────────┘ └─────────────────┘ + │ + ▼ + ┌─────────────────┐ + │ QMT 客户端 │ + │ (券商软件) │ + └─────────────────┘ +``` + +--- + +## 三、技术选型 + +| 组件 | 选择 | 说明 | +| ------------- | ------------------------ | ----------------------------- | +| **Web框架** | FastAPI | 异步、高性能、自动生成API文档 | +| **ORM** | SQLAlchemy 2.0 (async) | 异步数据库操作 | +| **数据库** | MySQL | 数据持久化存储 | +| **缓存/消息** | Redis | 所有业务数据交换、Pub/Sub | +| **配置管理** | Pydantic Settings + YAML | 类型安全的配置 | +| **进程管理** | Supervisor | 跨平台进程管理 | +| **日志** | Python logging | 标准日志库 | + +--- + +## 四、数据流设计 + +### 4.1 实盘行情流 + +``` +QMT实时行情 + │ + ▼ +qmt-adapter (market_feeder) + │ + │ Redis PUBLISH "market:tick:{symbol}" + ▼ +data-service (market/receiver) + │ + │ Redis PUBLISH "market:dispatch:{symbol}" + ▼ +strategy-engine (订阅) + │ + │ 生成交易信号 + ▼ +core-service (trading) + │ + │ Redis PUBLISH "trade:order:submit" + ▼ +qmt-adapter (trade_executor) + │ + │ 调用 QMT 下单 + ▼ +QMT 交易接口 +``` + +### 4.2 回测数据流 + +``` +MySQL (历史K线) + │ + │ 读取 + ▼ +data-service (backtest/data_player) + │ + │ 模拟实盘节奏 + │ Redis PUBLISH "market:tick:{symbol}" + ▼ +data-service (market/receiver) ← 与实盘完全相同 + │ + ▼ +strategy-engine ← 代码无需修改 + │ + ▼ +backtest/matcher (模拟撮合) ← 替代 qmt-adapter +``` + +**关键设计**: 回测时,data_player 模拟 qmt-adapter 的推送行为,下游服务代码完全不变。 + +--- + +## 五、核心数据模型 + +### 5.1 股票-策略配对 (核心) + +``` +股票 A ──┬── 策略1 → 独立持仓、独立资金 + ├── 策略2 → 独立持仓、独立资金 + └── 策略3 → 独立持仓、独立资金 + +股票 B ──┬── 策略1 → 独立持仓、独立资金 + └── 策略4 → 独立持仓、独立资金 +``` + +### 5.2 数据库表设计 + +| 表名 | 说明 | +| ------------------- | ---------------------- | +| `strategies` | 策略定义 | +| `symbol_strategies` | 股票-策略配对 (核心表) | +| `ss_positions` | 配对持仓 | +| `ss_accounts` | 配对资金账户 | +| `orders` | 订单记录 | +| `trades` | 成交记录 | +| `klines_1m` | 1分钟K线 | +| `klines_5m` | 5分钟K线 | +| `klines_15m` | 15分钟K线 | +| `klines_30m` | 30分钟K线 | +| `klines_60m` | 60分钟K线 | +| `klines_1d` | 日K线 | +| `klines_1w` | 周K线 | + +--- + +## 六、Redis 通道定义 + +### 6.1 行情相关 + +``` +market:tick:{symbol} # Tick行情推送 +market:kline:{symbol}:{period} # K线推送 +market:dispatch:{symbol} # 行情分发(给策略引擎) +``` + +### 6.2 交易相关 + +``` +trade:order:submit # 下单请求 +trade:order:cancel # 撤单请求 +trade:order:update # 订单状态更新 +trade:trade:report # 成交回报 +``` + +### 6.3 账户相关 + +``` +account:sync:position # 持仓同步 +account:sync:balance # 资金同步 +``` + +### 6.4 服务通信 + +``` +service:{from}:{to}:{action} # 服务间请求 +service:broadcast:{event} # 广播事件 +``` + +--- + +## 七、部署架构 + +### 7.1 多机部署示例 (3台) + +``` +┌─────────────────────────────────────┐ +│ 主机 A (主节点) │ +│ 192.168.1.100 │ +├─────────────────────────────────────┤ +│ Redis :6379 │ +│ MySQL :3306 │ +│ gateway :8001 │ +│ core-service :8010 │ +└─────────────────────────────────────┘ + +┌─────────────────────────────────────┐ +│ 主机 B (数据节点) │ +│ 192.168.1.101 │ +├─────────────────────────────────────┤ +│ data-service :8020 │ +│ strategy-engine :8030 │ +└─────────────────────────────────────┘ + +┌─────────────────────────────────────┐ +│ 主机 C (QMT节点/Windows) │ +│ 192.168.1.102 │ +├─────────────────────────────────────┤ +│ qmt-adapter (Python 3.6) │ +│ QMT 客户端 │ +└─────────────────────────────────────┘ +``` + +### 7.2 进程管理 + +使用 Supervisor 管理所有服务进程,支持: +- 自动启动/重启 +- 日志管理 +- 状态监控 + +--- + +## 八、跨平台支持 + +| 平台 | 支持的服务 | +| ----------- | ---------------------------------------------------- | +| **Linux** | gateway, core-service, data-service, strategy-engine | +| **Windows** | 全部服务 + qmt-adapter | + +设计原则: +- 使用 `pathlib.Path` 处理路径 +- 使用 `platform` 模块检测系统 +- 配置文件使用 YAML,UTF-8 编码 +- 进程管理使用跨平台方案 + +--- + +## 九、版本记录 + +| 版本 | 日期 | 说明 | +| ---- | ---------- | ------------------ | +| 2.0 | 2025-12-08 | 微服务架构重构设计 | +| 1.0 | - | 原单体架构 | diff --git a/docs/architecture/BUILD_PLAN.md b/docs/architecture/BUILD_PLAN.md new file mode 100644 index 0000000..c67646a --- /dev/null +++ b/docs/architecture/BUILD_PLAN.md @@ -0,0 +1,297 @@ +# QTrade 重构构建方案 + +> 创建日期: 2025-12-08 +> 状态: 进行中 + +## 一、重构目标 + +将现有单体架构重构为微服务架构,实现: +- FastAPI + Redis + MySQL 技术栈 +- 服务化拆分 +- 实盘/回测代码复用 +- 跨平台支持 + +--- + +## 二、构建阶段 + +### 阶段1: 核心模块 (core) + +**目标**: 建立所有服务共用的基础模块 + +| 任务 | 状态 | 说明 | +| --------------------------------- | -------- | ------------------------ | +| 1.1 项目结构搭建 | ✅ 已完成 | 创建目录结构 | +| 1.2 配置管理 (config.py) | ✅ 已完成 | Pydantic Settings + YAML | +| 1.3 Redis客户端 (redis_client.py) | ✅ 已完成 | 异步Redis封装 | +| 1.4 数据库连接 (database.py) | ✅ 已完成 | SQLAlchemy async | +| 1.5 日志模块 (logger.py) | ✅ 已完成 | 统一日志配置 | +| 1.6 数据模型 (models/) | ✅ 已完成 | Pydantic 模型定义 | + +**产出物**: +``` +src/core/ +├── __init__.py +├── config.py # 配置管理 +├── redis_client.py # Redis 客户端 +├── database.py # 数据库连接 +├── logger.py # 日志模块 +└── models/ # 数据模型 + ├── __init__.py + ├── market.py # 行情数据模型 + ├── order.py # 订单模型 + ├── position.py # 持仓模型 + └── symbol_strategy.py # 配对模型 +``` + +--- + +### 阶段2: Gateway 服务 + +**目标**: 建立 API 入口服务 + +| 任务 | 状态 | 说明 | +| -------------------- | -------- | ------------------ | +| 2.1 FastAPI 应用框架 | ⬜ 待开始 | 应用实例、生命周期 | +| 2.2 健康检查接口 | ⬜ 待开始 | /health | +| 2.3 路由结构 | ⬜ 待开始 | 路由模块划分 | +| 2.4 中间件 | ⬜ 待开始 | 日志、异常处理 | +| 2.5 启动脚本 | ⬜ 待开始 | 服务启动入口 | + +**产出物**: +``` +src/gateway/ +├── __init__.py +├── main.py # 服务入口 +├── app.py # FastAPI 应用 +├── deps.py # 依赖注入 +├── middleware.py # 中间件 +└── routes/ + ├── __init__.py + ├── health.py # 健康检查 + ├── market.py # 行情接口 (转发) + ├── trading.py # 交易接口 (转发) + ├── account.py # 账户接口 (转发) + └── backtest.py # 回测接口 (转发) +``` + +--- + +### 阶段3: Data Service 服务 + +**目标**: 建立数据服务 + +| 任务 | 状态 | 说明 | +| ---------------- | -------- | --------------- | +| 3.1 服务框架 | ⬜ 待开始 | FastAPI 应用 | +| 3.2 行情接收模块 | ⬜ 待开始 | 订阅 Redis 行情 | +| 3.3 行情分发模块 | ⬜ 待开始 | 分发给策略引擎 | +| 3.4 K线存储模块 | ⬜ 待开始 | 按周期分表存储 | +| 3.5 K线查询接口 | ⬜ 待开始 | 历史数据查询 | +| 3.6 回测数据回放 | ⬜ 待开始 | 模拟QMT推送 | + +**产出物**: +``` +src/data_service/ +├── __init__.py +├── main.py +├── app.py +├── market/ +│ ├── receiver.py # 行情接收 +│ ├── dispatcher.py # 行情分发 +│ └── cache.py # 行情缓存 +├── kline/ +│ ├── storage.py # K线存储 +│ ├── query.py # K线查询 +│ └── models.py # K线ORM模型 +├── backtest/ +│ ├── data_player.py # 数据回放 +│ └── matcher.py # 模拟撮合 +└── routes/ + ├── market.py + ├── kline.py + └── backtest.py +``` + +--- + +### 阶段4: Core Service 服务 + +**目标**: 建立核心业务服务 + +| 任务 | 状态 | 说明 | +| ---------------- | -------- | -------------------- | +| 4.1 服务框架 | ⬜ 待开始 | FastAPI 应用 | +| 4.2 配对管理模块 | ⬜ 待开始 | 股票-策略配对 CRUD | +| 4.3 订单管理模块 | ⬜ 待开始 | 订单创建、查询、撤销 | +| 4.4 风控模块 | ⬜ 待开始 | 下单前风控检查 | +| 4.5 持仓管理模块 | ⬜ 待开始 | 持仓更新、查询 | +| 4.6 资金管理模块 | ⬜ 待开始 | 资金冻结、释放 | + +**产出物**: +``` +src/core_service/ +├── __init__.py +├── main.py +├── app.py +├── symbol_strategy/ +│ └── manager.py # 配对管理 +├── trading/ +│ ├── order_manager.py +│ └── executor.py # 发送到Redis +├── risk/ +│ └── checker.py # 风控检查 +├── account/ +│ ├── position_manager.py +│ └── balance_manager.py +└── routes/ + ├── symbol_strategy.py + ├── order.py + ├── position.py + └── account.py +``` + +--- + +### 阶段5: Strategy Engine 服务 + +**目标**: 建立策略引擎服务 + +| 任务 | 状态 | 说明 | +| ---------------- | -------- | ------------------ | +| 5.1 服务框架 | ⬜ 待开始 | FastAPI 应用 | +| 5.2 策略管理模块 | ⬜ 待开始 | 策略加载、启停 | +| 5.3 行情订阅模块 | ⬜ 待开始 | 订阅 Redis 行情 | +| 5.4 信号生成模块 | ⬜ 待开始 | 策略执行、信号输出 | +| 5.5 策略基类 | ⬜ 待开始 | 策略抽象接口 | + +**产出物**: +``` +src/strategy_engine/ +├── __init__.py +├── main.py +├── app.py +├── engine/ +│ ├── manager.py # 策略管理 +│ ├── executor.py # 策略执行器 +│ └── base_strategy.py # 策略基类 +├── market/ +│ └── subscriber.py # 行情订阅 +└── routes/ + └── strategy.py +``` + +--- + +### 阶段6: QMT Adapter (Python 3.6) + +**目标**: 建立QMT适配层 + +| 任务 | 状态 | 说明 | +| ---------------- | -------- | --------------- | +| 6.1 项目结构 | ⬜ 待开始 | Python 3.6 兼容 | +| 6.2 行情采集模块 | ⬜ 待开始 | QMT → Redis | +| 6.3 交易执行模块 | ⬜ 待开始 | Redis → QMT | +| 6.4 账户同步模块 | ⬜ 待开始 | QMT → Redis | +| 6.5 启动脚本 | ⬜ 待开始 | 独立运行 | + +**产出物**: +``` +src/qmt_adapter/ +├── __init__.py +├── main.py # 入口 +├── market_feeder.py # 行情采集 +├── trade_executor.py # 交易执行 +├── account_sync.py # 账户同步 +└── qmt_client.py # QMT SDK 封装 +``` + +--- + +### 阶段7: 数据库与配置 + +**目标**: 完善数据库和配置 + +| 任务 | 状态 | 说明 | +| ------------------ | -------- | ------------- | +| 7.1 数据库迁移脚本 | ⬜ 待开始 | Alembic | +| 7.2 初始化SQL | ⬜ 待开始 | 表结构 | +| 7.3 配置文件模板 | ⬜ 待开始 | settings.yaml | +| 7.4 环境变量示例 | ⬜ 待开始 | .env.example | + +--- + +### 阶段8: 部署与运维 + +**目标**: 建立部署方案 + +| 任务 | 状态 | 说明 | +| ------------------- | -------- | ---------- | +| 8.1 启动脚本 | ⬜ 待开始 | 跨平台启动 | +| 8.2 Supervisor 配置 | ⬜ 待开始 | 进程管理 | +| 8.3 部署文档 | ⬜ 待开始 | 部署说明 | + +--- + +## 三、目录结构总览 + +``` +QTrade/ +├── docs/ +│ └── architecture/ +│ ├── ARCHITECTURE.md # 架构设计文档 +│ └── BUILD_PLAN.md # 本文档 +│ +├── src/ +│ ├── core/ # 阶段1: 核心模块 +│ ├── gateway/ # 阶段2: API网关 +│ ├── data_service/ # 阶段3: 数据服务 +│ ├── core_service/ # 阶段4: 核心业务 +│ ├── strategy_engine/ # 阶段5: 策略引擎 +│ └── qmt_adapter/ # 阶段6: QMT适配 +│ +├── configs/ +│ ├── settings.yaml # 主配置 +│ └── logging.yaml # 日志配置 +│ +├── database/ +│ ├── migrations/ # 数据库迁移 +│ └── init.sql # 初始化SQL +│ +├── scripts/ +│ ├── start.py # 启动脚本 +│ └── supervisord/ # Supervisor配置 +│ +├── tests/ # 测试 +├── requirements.txt # Python 3.10+ 依赖 +├── requirements36.txt # Python 3.6 依赖 +└── README.md +``` + +--- + +## 四、进度跟踪 + +### 当前状态 + +- **当前阶段**: 阶段2 - Gateway 服务 +- **当前任务**: 2.1 FastAPI 应用框架 +- **开始日期**: 2025-12-08 +- **预计完成**: - + +### 进度记录 + +| 日期 | 完成内容 | 备注 | +| ---------- | ------------ | -------------------------------------------------- | +| 2025-12-08 | 架构设计完成 | 确定技术方案 | +| 2025-12-08 | 构建方案创建 | 本文档 | +| 2025-12-08 | 阶段1完成 | 核心模块 (config, redis, database, logger, models) | + +--- + +## 五、注意事项 + +1. **不兼容旧代码**: 重构不考虑与现有代码的兼容性 +2. **一步步来**: 每完成一个任务验证后再进行下一个 +3. **及时纠偏**: 发现问题立即讨论调整 +4. **文档同步**: 代码变更同步更新文档 diff --git a/example_and_demos/README.md b/example_and_demos/README.md deleted file mode 100644 index 6edcd32..0000000 --- a/example_and_demos/README.md +++ /dev/null @@ -1,45 +0,0 @@ -# Example and Demos Directory Structure - -This directory contains example code and demonstration scripts organized by protocol type. - -## Directory Structure - -``` -example_and_demos/ -├── http/ # HTTP相关的示例和演示 -│ ├── http_client_example.py # HTTP客户端示例 -│ └── run_http_server.py # HTTP服务器启动脚本 -└── socket/ # Socket相关的示例和演示 - ├── run_socket_server.py # 简化版Socket服务器启动脚本 - └── socket_client_example.py # 简化版Socket客户端示例 -``` - -## Usage - -### HTTP Examples -- **HTTP Client Example**: `python example_and_demos/http/http_client_example.py` -- **HTTP Server**: `python example_and_demos/http/run_http_server.py` - -### Socket Examples -- **Simple Socket Server**: `python example_and_demos/socket/run_socket_server.py` -- **Simple Socket Client**: `python example_and_demos/socket/socket_client_example.py` - -## Quick Start - -Use the main quick start script at project root: -```bash -python quick_start.py -``` - -Or use the Socket-specific quick start: -```bash -python quick_start_socket.py -``` - -## Performance Comparison - -Socket implementation shows **13x performance improvement** over HTTP: -- HTTP: 4.13ms average latency, 242 QPS -- Socket: 0.31ms average latency, 3,242 QPS - -For performance testing, see `/test/` directory (test_stress.py). diff --git a/example_and_demos/http/http_client_example.py b/example_and_demos/http/http_client_example.py deleted file mode 100644 index 56ea745..0000000 --- a/example_and_demos/http/http_client_example.py +++ /dev/null @@ -1,73 +0,0 @@ -#!/usr/bin/env python3 -# -*- coding: utf-8 -*- -""" -QTrade Client 快速入门示例 -最简单的使用方式,适合新手快速上手 -""" - -import sys -import os - -# 添加项目根目录到Python路径 -sys.path.append( - os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -) - -from src.network_model import QTradeHTTPClient - - -def quick_start_example(): - """快速入门示例""" - print("🚀 QTrade Client 快速入门") - print("=" * 40) - - # 1. 创建客户端并连接服务器 - with QTradeHTTPClient() as client: - # 2. 测试连接 - ping_result = client.ping() - print(f"连接测试: {ping_result}") - - # 检查ping是否成功 - if isinstance(ping_result, dict) and "error" in ping_result: - print(f"❌ 连接失败: {ping_result['error']}") - print( - "请确保HTTP服务器已启动:python example_and_demos/http/run_http_server.py" - ) - return - - # 3. 获取服务器状态 - status = client.status() - if isinstance(status, dict) and "error" in status: - print(f"❌ 获取状态失败: {status['error']}") - else: - print(f"服务器版本: {status.get('version', 'unknown')}") - - # 4. 发送简单消息 - hello_result = client.send("hello") - print(f"问候消息: {hello_result}") - - # 5. 发送K线数据获取交易信号 - # 注意:价格必须在1.0-8.0范围内 - result = client.send_kline( - symbol="AAPL", # 股票代码 - close=2.5, # 收盘价 - high=2.6, # 最高价 - low=2.4, # 最低价 - volume=1000000, # 成交量 - ) - - if isinstance(result, dict) and "signal" in result: - signal = result["signal"] - action = ( - signal.get("action", "unknown") - if isinstance(signal, dict) - else "unknown" - ) - qty = signal.get("qty", 0) if isinstance(signal, dict) else 0 - print(f"交易信号: {action} {qty}股") - - print("\n✅ 快速入门完成!") - - -if __name__ == "__main__": - quick_start_example() diff --git a/example_and_demos/http/run_http_server.py b/example_and_demos/http/run_http_server.py deleted file mode 100644 index 3324e71..0000000 --- a/example_and_demos/http/run_http_server.py +++ /dev/null @@ -1,129 +0,0 @@ -""" -QTrade Server - 现代化简洁版 -不保证向后兼容性,专注于性能和简洁性 -""" - -import time -import sys -import os - -# 添加项目根目录到Python路径 -sys.path.append( - os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -) - -from src.strategy.grid_strategy import GridStrategy -from src.network_model.http_server import QTradeHTTPServerManager - -# 全局策略实例 -strategy = GridStrategy( - upper_price=8.0, - lower_price=1.0, - grid_step=0.04, - quantity_per_grid=1200, - trend="up_and_down", -) - - -def handle_message(message): - """统一的消息处理器""" - try: - # 字符串消息处理 - if isinstance(message, str): - return handle_text_message(message) - - # 字典消息处理 - elif isinstance(message, dict): - return handle_dict_message(message) - - # 其他类型 - else: - return {"error": "Unsupported message type", "type": type(message).__name__} - - except Exception as e: - return {"error": f"Message processing failed: {str(e)}"} - - -def handle_text_message(message): - """处理文本消息""" - handlers = { - "ping": lambda: "pong", - "hello": lambda: "Hello from QTrade!", - "time": lambda: time.time(), - "status": lambda: "Server is running", - } - - return handlers.get(message, lambda: f"Unknown command: {message}")() - - -def handle_dict_message(message): - """处理字典消息""" - msg_type = message.get("type", "unknown") - - handlers = { - "update_kline": handle_kline_update, - "get_server_status": handle_status_request, - "ping": lambda msg: "pong", - "echo": lambda msg: {"echo": msg}, - } - - handler = handlers.get( - msg_type, - lambda msg: {"error": f"Unknown message type: {msg_type}", "received": msg}, - ) - - return handler(message) - - -def handle_kline_update(message): - """处理K线数据更新""" - data = message.get("data", {}) - close_price = data.get("close", 0) - - if close_price <= 0: - return {"error": "Invalid close price", "received": close_price} - - # 使用策略计算信号 - signal = strategy.determine_signal(close_price) - - return { - "type": "trade_signal", - "signal": signal, - "timestamp": time.time(), - "processed_price": close_price, - } - - -def handle_status_request(message): - """处理状态请求""" - return { - "type": "server_status", - "status": "online", - "version": "2.0.0", - "uptime": time.time(), - "strategy": { - "type": "GridStrategy", - "upper_price": strategy.upper_price, - "lower_price": strategy.lower_price, - "grid_step": strategy.grid_step, - }, - "supported_commands": ["ping", "update_kline", "get_server_status"], - "timestamp": time.time(), - } - - -def main(): - """主函数 - 简洁启动""" - print("🎯 QTrade Server v2.0 - 现代化版本") - print("=" * 50) - - # 创建服务器 - server = QTradeHTTPServerManager(host="127.0.0.1", port=8080) - server.set_message_handler(handle_message) - - # 启动服务器 - server.start() - - -if __name__ == "__main__": - main() diff --git a/example_and_demos/socket/run_socket_server.py b/example_and_demos/socket/run_socket_server.py deleted file mode 100644 index 9c51507..0000000 --- a/example_and_demos/socket/run_socket_server.py +++ /dev/null @@ -1,156 +0,0 @@ -""" -QTrade Socket服务器启动脚本 - 简化版 -专注于同步消息处理和网格策略 -""" - -import time -import sys -import os - -# 添加项目根目录到Python路径 -sys.path.append( - os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -) - -from src.strategy.grid_strategy import GridStrategy -from src.network_model.simple_socket_server import SimpleQTradeSocketServerManager - -# 全局策略实例 -strategy = GridStrategy( - upper_price=8.0, - lower_price=1.0, - grid_step=0.04, - quantity_per_grid=1200, - trend="up_and_down", -) - - -def handle_message(message): - """同步消息处理器 - 包含网格策略""" - try: - # 处理字符串消息 - if isinstance(message, str): - if message == "ping": - return {"type": "response", "data": "pong", "request_id": None} - elif message == "status": - return { - "type": "server_status", - "status": "online", - "strategy": f"GridStrategy({strategy.upper_price}-{strategy.lower_price})", - "timestamp": time.time(), - "request_id": None, - } - else: - return { - "type": "response", - "data": f"Unknown command: {message}", - "request_id": None, - } - - # 处理字典消息 - elif isinstance(message, dict): - request_id = message.get("request_id") - msg_type = message.get("type", "unknown") - - # K线数据更新 - 使用网格策略 - if msg_type == "update_kline": - data = message.get("data", {}) - close_price = data.get("close", 0) - - if close_price <= 0: - return { - "type": "error", - "error": "Invalid close price", - "request_id": request_id, - } - - # 使用网格策略计算信号 - signal = strategy.determine_signal(close_price) - - return { - "type": "trade_signal", - "signal": signal, - "request_id": request_id, - } - - # 获取服务器状态 - elif msg_type == "get_server_status": - return { - "type": "server_status", - "status": "online", - "version": "2.0.0-simplified", - "protocol": "socket", - "strategy": { - "type": "GridStrategy", - "upper_price": strategy.upper_price, - "lower_price": strategy.lower_price, - "grid_step": strategy.grid_step, - "quantity_per_grid": strategy.quantity_per_grid, - }, - "timestamp": time.time(), - "request_id": request_id, - } - - # 测试同步消息 - elif msg_type == "test_sync": - return { - "type": "sync_response", - "message": "Sync message processed successfully", - "received_data": message.get("data"), - "timestamp": time.time(), - "request_id": request_id, - } - - # 未知消息类型 - else: - return { - "type": "error", - "error": f"Unknown message type: {msg_type}", - "request_id": request_id, - } - - # 其他类型消息 - else: - return { - "type": "error", - "error": "Unsupported message type", - "request_id": None, - } - - except Exception as e: - return { - "type": "error", - "error": f"Message processing failed: {str(e)}", - "request_id": message.get("request_id") - if isinstance(message, dict) - else None, - } - - -def main(): - """主函数 - 简化版""" - print("🎯 QTrade Socket Server - 极简版 (单客户端同步 + 网格策略)") - print("=" * 60) - print( - f"📊 网格策略配置: {strategy.upper_price}-{strategy.lower_price}, 步长: {strategy.grid_step}" - ) - print("🎯 监听地址: 127.0.0.1:8081 (单客户端)") - print("=" * 60) - - # 创建服务器 - server = SimpleQTradeSocketServerManager(host="127.0.0.1", port=8081) - server.set_message_handler(handle_message) - - # 启动服务器 - try: - server.start() - except KeyboardInterrupt: - print("\n⚠️ 收到中断信号") - server.stop() - except Exception as e: - print(f"\n❌ 服务器错误: {e}") - server.stop() - - -if __name__ == "__main__": - main() diff --git a/example_and_demos/socket/socket_client_example.py b/example_and_demos/socket/socket_client_example.py deleted file mode 100644 index 622af53..0000000 --- a/example_and_demos/socket/socket_client_example.py +++ /dev/null @@ -1,71 +0,0 @@ -#!/usr/bin/env python3 -""" -QTrade Socket客户端 - 极简版示例 -专注于同步消息和网格策略交互 -""" - -import sys -import os -import time - -# 添加项目根目录到Python路径 -sys.path.append( - os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) -) - -from src.network_model.simple_socket_client import SimpleQTradeSocketClient - - -def main(): - # 创建客户端 - client = SimpleQTradeSocketClient("127.0.0.1", 8081) - - # 连接到服务器 - if not client.connect(): - print("❌ 连接失败") - return - - print("✅ 连接成功") - - try: - # 测试1: ping测试 - print("\n=== Ping测试 ===") - ping_response = client.ping() - print(f"Ping响应: {ping_response}") - - # 测试2: 获取服务器状态 - print("\n=== 获取服务器状态 ===") - status = client.get_server_status() - if status: - print(f"服务器状态: {status}") - - # 测试3: 发送K线数据并获取网格策略信号 - print("\n=== 网格策略测试 ===") - test_prices = [2.5, 5.0, 7.5, 1.2, 8.5] - - for price in test_prices: - print(f"\n发送价格: {price}") - kline_response = client.send_kline_update(price) - if kline_response: - signal = kline_response.get("signal", {}) - print(f"网格策略信号: {signal}") - - time.sleep(0.5) # 短暂延迟 - - # 测试4: 同步消息测试 - print("\n=== 同步消息测试 ===") - sync_response = client.test_sync_message("极简版测试数据") - print(f"同步响应: {sync_response}") - - except KeyboardInterrupt: - print("\n⚠️ 用户中断") - except Exception as e: - print(f"\n❌ 测试过程中发生错误: {e}") - finally: - # 断开连接 - client.disconnect() - print("\n✅ 测试完成") - - -if __name__ == "__main__": - main() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..0b255eb --- /dev/null +++ b/requirements.txt @@ -0,0 +1,34 @@ +# QTrade Python 3.10+ 依赖 +# 主服务依赖 + +# Web 框架 +fastapi>=0.104.0 +uvicorn[standard]>=0.24.0 + +# 数据库 +sqlalchemy[asyncio]>=2.0.0 +aiomysql>=0.2.0 +pymysql>=1.1.0 +alembic>=1.12.0 + +# Redis +redis>=5.0.0 + +# 配置管理 +pydantic>=2.5.0 +pydantic-settings>=2.1.0 +pyyaml>=6.0.0 + +# 日志 +python-json-logger>=2.0.0 + +# 开发工具 +pytest>=7.4.0 +pytest-asyncio>=0.21.0 +httpx>=0.25.0 +black>=23.0.0 +ruff>=0.1.0 +mypy>=1.6.0 + +# 类型提示 +typing_extensions>=4.8.0 diff --git a/requirements36.txt b/requirements36.txt new file mode 100644 index 0000000..19a6210 --- /dev/null +++ b/requirements36.txt @@ -0,0 +1,15 @@ +# QTrade Python 3.6 依赖 +# QMT Adapter 专用 + +# Redis +redis>=3.5.0,<4.0.0 + +# 配置 +pyyaml>=5.4.0 + +# 日志 +python-json-logger>=2.0.0 + +# 类型提示 (兼容 Python 3.6) +typing_extensions>=3.7.4 +dataclasses>=0.8 diff --git a/src/__init__.py b/src/__init__.py new file mode 100644 index 0000000..8b4ce7e --- /dev/null +++ b/src/__init__.py @@ -0,0 +1,3 @@ +""" +QTrade 源代码包 +""" diff --git a/src/back_trader/README.md b/src/back_trader/README.md deleted file mode 100644 index f6c2372..0000000 --- a/src/back_trader/README.md +++ /dev/null @@ -1,217 +0,0 @@ -# QTrade 回测引擎 - -这是一个基于Python的股票回测引擎,支持自定义策略和性能分析。 - -## 目录结构 - -``` -back_trader/ -├── __init__.py # 模块初始化 -├── strategy_base.py # 策略基类 -├── ma_cross_strategy.py # 均线交叉策略 -├── backtest_engine.py # 回测引擎核心 -├── performance_analyzer.py # 性能分析器 -├── example_backtest.py # 完整示例 -├── run_quick_backtest.py # 快速回测脚本 -└── README.md # 本文件 -``` - -## 核心功能 - -### 1. 策略框架 -- **StrategyBase**: 所有策略的基类,定义了策略接口 -- **Portfolio**: 投资组合管理,处理持仓和交易 -- **Signal**: 交易信号定义 - -### 2. 内置策略 -- **MACrossStrategy**: 双均线交叉策略 - - 支持金叉买入、死叉卖出 - - 可配置止损、止盈 - - 支持仓位控制 - -### 3. 回测引擎 -- **BacktestEngine**: 核心回测引擎 - - 从数据库读取历史数据 - - 逐日推送数据给策略 - - 执行交易信号 - - 记录回测过程 - -### 4. 性能分析 -- **PerformanceAnalyzer**: 性能分析器 - - 计算总收益、年化收益 - - 最大回撤分析 - - 夏普比率、卡尔玛比率 - - 年度统计报告 - -## 使用方法 - -### 快速开始 - -1. **运行快速回测**: -```bash -cd src/back_trader -python run_quick_backtest.py -``` - -2. **完整示例**: -```bash -cd src/back_trader -python example_backtest.py -``` - -### 自定义回测 - -```python -from back_trader.backtest_engine import BacktestEngine -from back_trader.ma_cross_strategy import MACrossStrategy - -# 创建回测引擎 -engine = BacktestEngine(initial_capital=1000000.0) - -# 设置股票池 -engine.set_universe(["601658.SH", "510310.SH"]) - -# 设置回测期间 -engine.set_period("2024-01-01", "2024-12-31", "1d") - -# 创建策略 -strategy = MACrossStrategy({ - 'short_period': 5, # 短期均线 - 'long_period': 20, # 长期均线 - 'stop_loss': 0.05, # 止损5% - 'take_profit': 0.15, # 止盈15% - 'position_size': 0.3 # 每次30%仓位 -}) - -engine.set_strategy(strategy) - -# 运行回测 -if engine.load_data_from_database(): - if engine.run_backtest(): - engine.print_summary() -``` - -### 自定义策略 - -```python -from back_trader.strategy_base import StrategyBase -import pandas as pd -from datetime import datetime - -class MyStrategy(StrategyBase): - def __init__(self, params=None): - super().__init__("My Custom Strategy", params) - - def initialize(self): - """策略初始化""" - self.log_info("策略初始化完成") - - def on_data(self, data: pd.DataFrame, timestamp: datetime): - """处理数据""" - # 获取当前价格 - current_price = data['close_price'].iloc[-1] - stock_code = getattr(data, 'stock_code', 'UNKNOWN') - - # 简单策略:价格上涨5%买入,下跌5%卖出 - if len(data) >= 2: - prev_price = data['close_price'].iloc[-2] - change = (current_price - prev_price) / prev_price - - if change > 0.05: # 上涨5% - self.generate_signal(timestamp, stock_code, 'BUY', 1.0, "价格上涨5%") - elif change < -0.05: # 下跌5% - self.generate_signal(timestamp, stock_code, 'SELL', 1.0, "价格下跌5%") - -# 使用自定义策略 -strategy = MyStrategy({'param1': 'value1'}) -engine.set_strategy(strategy) -``` - -## 性能指标说明 - -### 收益指标 -- **总收益率**: (最终价值 - 初始资金) / 初始资金 -- **年化收益率**: 按年化计算的收益率 -- **超额收益**: 相对基准的超额收益 - -### 风险指标 -- **最大回撤**: 从最高点到最低点的最大跌幅 -- **回撤持续时间**: 最大回撤的持续天数 -- **波动率**: 收益率的标准差(年化) - -### 风险调整收益 -- **夏普比率**: (年化收益率 - 无风险利率) / 年化波动率 -- **卡尔玛比率**: 年化收益率 / 最大回撤 - -### 交易统计 -- **总交易次数**: 完整买卖对的次数 -- **胜率**: 盈利交易 / 总交易次数 -- **盈亏比**: 平均盈利 / 平均亏损 -- **平均盈利/亏损**: 单笔交易的平均盈亏 - -## 数据要求 - -回测引擎从`data_process_model`模块的数据库中读取数据,需要确保: - -1. 数据库连接正常 -2. 股票数据表已创建 -3. 数据时间范围覆盖回测期间 -4. 数据包含OHLCV字段 - -## 注意事项 - -1. **手续费**: 默认手续费率为0.03%,可在Portfolio中调整 -2. **交易单位**: A股以100股为单位,自动处理 -3. **数据对齐**: 不同股票的交易日可能不同,引擎会自动处理 -4. **内存使用**: 大量历史数据可能占用较多内存 -5. **运行时间**: 复杂策略和长时间回测可能需要较长时间 - -## 扩展开发 - -### 添加新策略 -1. 继承`StrategyBase`类 -2. 实现`initialize()`和`on_data()`方法 -3. 使用`generate_signal()`生成交易信号 - -### 添加新指标 -1. 在`data_process_model/technical_indicators.py`中添加指标计算 -2. 在策略中调用指标函数 - -### 自定义性能分析 -1. 继承`PerformanceAnalyzer`类 -2. 添加新的性能指标计算方法 -3. 修改报告生成逻辑 - -## 示例结果 - -``` -============================================================ - 回测性能报告 -============================================================ - -📊 总体指标: -总收益率: 15.30% -年化收益率: 14.20% -最大回撤: 8.50% -回撤持续: 45 天 -夏普比率: 1.25 -卡尔玛比率: 1.67 -波动率: 18.30% - -📈 交易统计: -总交易次数: 24 -胜率: 58.33% -盈亏比: 1.45 -平均盈利: 5234.50 -平均亏损: -3608.20 - -📅 年度统计: - 年份 收益率 最大回撤 夏普比率 交易次数 ------------------------------------------------------------- - 2024 15.30% 8.50% 1.25 24 -============================================================ -``` - -## 技术支持 - -如有问题或建议,请查看项目文档或联系开发团队。 diff --git a/src/back_trader/__init__.py b/src/back_trader/__init__.py deleted file mode 100644 index 6d70b55..0000000 --- a/src/back_trader/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -""" -回测引擎模块 -""" - -try: - from .backtest_engine import BacktestEngine -except ImportError: - # 如果导入失败,使用简化版本 - BacktestEngine = None - -from .simple_backtest_engine import SimpleBacktestEngine -from .strategy_base import StrategyBase -from .ma_cross_strategy import MACrossStrategy -from .performance_analyzer import PerformanceAnalyzer - -__all__ = [ - 'SimpleBacktestEngine', - 'StrategyBase', - 'MACrossStrategy', - 'PerformanceAnalyzer' -] - -# 如果完整版本可用,也导出 -if BacktestEngine is not None: - __all__.append('BacktestEngine') diff --git a/src/back_trader/backtest_engine.py b/src/back_trader/backtest_engine.py deleted file mode 100644 index a15fde8..0000000 --- a/src/back_trader/backtest_engine.py +++ /dev/null @@ -1,525 +0,0 @@ -""" -回测引擎模块 - -核心回测引擎,负责: -1. 从数据库读取历史数据 -2. 按时间顺序逐笔推送数据给策略 -3. 执行策略生成的交易信号 -4. 记录回测过程和结果 -""" - -import pandas as pd -import numpy as np -from datetime import datetime, timedelta -from typing import Dict, List, Any, Optional, Tuple -import logging -import sys -import os - -logger = logging.getLogger(__name__) - -# 添加项目根目录到Python路径 -current_dir = os.path.dirname(os.path.abspath(__file__)) -project_root = os.path.dirname(os.path.dirname(current_dir)) -src_dir = os.path.join(project_root, 'src') -data_model_dir = os.path.join(src_dir, 'data_process_model') -sys.path.append(src_dir) -sys.path.append(data_model_dir) - -try: - from database_config import init_database - from stock_models import create_stock_kline_model - DATABASE_AVAILABLE = True -except ImportError as e: - logger.warning(f"数据库模块导入失败: {e}") - DATABASE_AVAILABLE = False -from strategy_base import StrategyBase, Portfolio -from performance_analyzer import PerformanceAnalyzer - -logger = logging.getLogger(__name__) - - -class BacktestEngine: - """ - 回测引擎 - - 负责整个回测流程的协调和管理 - """ - - def __init__(self, initial_capital: float = 1000000.0): - self.initial_capital = initial_capital - self.portfolio = Portfolio(initial_capital) - self.strategy: Optional[StrategyBase] = None - self.performance_analyzer = PerformanceAnalyzer() - - # 回测配置 - self.stock_codes: List[str] = [] - self.start_date: Optional[datetime] = None - self.end_date: Optional[datetime] = None - self.period: str = "1d" - - # 数据缓存 - self.data_cache: Dict[str, pd.DataFrame] = {} - self.current_date: Optional[datetime] = None - - # 运行状态 - self.is_running = False - self.progress_callback = None - - def set_strategy(self, strategy: StrategyBase): - """设置交易策略""" - self.strategy = strategy - self.strategy.set_portfolio(self.portfolio) - - def set_universe(self, stock_codes: List[str]): - """设置股票池""" - self.stock_codes = stock_codes - - def set_period(self, start_date: str, end_date: str, period: str = "1d"): - """ - 设置回测时间范围 - - Args: - start_date: 开始日期,格式 "YYYY-MM-DD" - end_date: 结束日期,格式 "YYYY-MM-DD" - period: 数据周期,如 "1d", "1h", "5m" - """ - self.start_date = datetime.strptime(start_date, "%Y-%m-%d") - self.end_date = datetime.strptime(end_date, "%Y-%m-%d") - self.period = period - - def load_data_from_database(self) -> bool: - """从数据库加载历史数据""" - if not DATABASE_AVAILABLE: - logger.error("数据库模块不可用,无法加载数据") - return False - - try: - logger.info("开始从数据库加载历史数据...") - - # 初始化数据库连接 - if not init_database(): - logger.error("数据库连接失败") - return False - - for stock_code in self.stock_codes: - try: - # 创建对应的数据模型 - model_class = create_stock_kline_model(stock_code, self.period) - - # 查询数据 - query = model_class.select().where( - (model_class.timestamp >= self.start_date) & - (model_class.timestamp <= self.end_date) - ).order_by(model_class.timestamp) - - # 转换为DataFrame - data_list = [] - for record in query: - data_list.append({ - 'timestamp': record.timestamp, - 'open': float(record.open), - 'high': float(record.high), - 'low': float(record.low), - 'close': float(record.close), - 'volume': record.volume, - 'amount': float(record.amount) - }) - - if data_list: - df = pd.DataFrame(data_list) - df.set_index('timestamp', inplace=True) - df.sort_index(inplace=True) - df.stock_code = stock_code # 添加股票代码属性 - - self.data_cache[stock_code] = df - logger.info(f"✅ 加载 {stock_code} 数据: {len(df)} 条记录") - else: - logger.warning(f"⚠️ {stock_code} 无数据") - - except Exception as e: - logger.error(f"❌ 加载 {stock_code} 数据失败: {e}") - continue - - total_records = sum(len(df) for df in self.data_cache.values()) - logger.info(f"数据加载完成,共 {len(self.data_cache)} 只股票,{total_records} 条记录") - - return len(self.data_cache) > 0 - - except Exception as e: - logger.error(f"数据加载失败: {e}") - return False - - def get_trading_dates(self) -> List[datetime]: - """获取交易日期列表""" - if not self.data_cache: - return [] - - # 合并所有股票的交易日期 - all_dates = set() - for df in self.data_cache.values(): - all_dates.update(df.index) - - # 排序并转换为列表 - trading_dates = sorted(list(all_dates)) - return trading_dates - - def get_data_at_date(self, target_date: datetime, stock_code: str, - lookback_days: int = 100) -> pd.DataFrame: - """ - 获取指定日期之前的历史数据 - - Args: - target_date: 目标日期 - stock_code: 股票代码 - lookback_days: 向前查看的天数 - - Returns: - pd.DataFrame: 历史数据 - """ - if stock_code not in self.data_cache: - return pd.DataFrame() - - df = self.data_cache[stock_code] - - # 获取目标日期之前的数据 - mask = df.index <= target_date - historical_data = df[mask] - - # 限制数据长度 - if len(historical_data) > lookback_days: - historical_data = historical_data.tail(lookback_days) - - # 添加股票代码属性 - historical_data.stock_code = stock_code - - return historical_data - - def execute_signals(self, timestamp: datetime): - """执行策略生成的交易信号""" - if not self.strategy or not self.strategy.signals: - return - - # 处理当前时间戳的信号 - current_signals = [s for s in self.strategy.signals - if s.timestamp == timestamp] - - for signal in current_signals: - try: - # 获取当前价格(使用收盘价) - if signal.stock_code not in self.data_cache: - continue - - df = self.data_cache[signal.stock_code] - price_data = df[df.index == timestamp] - - if price_data.empty: - continue - - current_price = price_data['close'].iloc[0] - - if signal.action == 'BUY': - # 使用信号中指定的股数,如果没有则按比例计算 - if hasattr(signal, 'shares') and signal.shares > 0: - shares = signal.shares - else: - # 使用信号中指定的金额,如果没有则使用20%资金 - if hasattr(signal, 'amount') and signal.amount > 0: - target_value = min(signal.amount, self.portfolio.cash) - else: - position_ratio = 0.2 # 默认每次使用20%资金 - target_value = self.portfolio.cash * position_ratio - - shares = int(target_value / current_price / 100) * 100 # 向下取整到100的倍数 - - if shares > 0 and shares * current_price <= self.portfolio.cash: - success = self.portfolio.execute_trade( - timestamp, signal.stock_code, 'BUY', shares, current_price - ) - if success: - self.performance_analyzer.add_trade(self.portfolio.trades[-1]) - logger.info(f"✅ 买入: {signal.stock_code} {shares}股 @{current_price:.3f}") - - # 通知策略更新买入价格 - if hasattr(self.strategy, 'update_buy_price'): - self.strategy.update_buy_price(signal.stock_code, current_price) - - elif signal.action == 'BUY_ALL': - # 全仓买入操作 - target_value = self.portfolio.cash - shares = int(target_value / current_price / 100) * 100 # 向下取整到100的倍数 - - if shares > 0 and shares * current_price <= self.portfolio.cash: - success = self.portfolio.execute_trade( - timestamp, signal.stock_code, 'BUY', shares, current_price - ) - if success: - self.performance_analyzer.add_trade(self.portfolio.trades[-1]) - logger.info(f"🚀 全仓买入: {signal.stock_code} {shares}股 @{current_price:.3f}") - - # 通知策略更新买入价格 - if hasattr(self.strategy, 'update_buy_price'): - self.strategy.update_buy_price(signal.stock_code, current_price) - - elif signal.action == 'SELL': - # 使用信号中指定的股数,如果没有则部分卖出 - position = self.portfolio.get_position(signal.stock_code) - if position and position.shares > 0: - if hasattr(signal, 'shares') and signal.shares > 0: - # 使用指定股数,但不能超过持仓 - shares = min(signal.shares, position.shares) - elif hasattr(signal, 'amount') and signal.amount > 0: - # 按指定金额计算股数 - shares = int(signal.amount / current_price / 100) * 100 - shares = min(shares, position.shares) - else: - # 全部卖出 - shares = position.shares - - if shares > 0: - success = self.portfolio.execute_trade( - timestamp, signal.stock_code, 'SELL', shares, current_price - ) - if success: - self.performance_analyzer.add_trade(self.portfolio.trades[-1]) - logger.info(f"✅ 卖出: {signal.stock_code} {shares}股 @{current_price:.3f}") - - elif signal.action == 'SELL_ALL': - # 清仓操作 - position = self.portfolio.get_position(signal.stock_code) - if position and position.shares > 0: - success = self.portfolio.execute_trade( - timestamp, signal.stock_code, 'SELL', position.shares, current_price - ) - if success: - self.performance_analyzer.add_trade(self.portfolio.trades[-1]) - logger.info(f"🔥 清仓: {signal.stock_code} {position.shares}股 @{current_price:.3f}") - - except Exception as e: - logger.error(f"执行信号失败: {e}") - - # 清空已处理的信号 - self.strategy.signals = [s for s in self.strategy.signals - if s.timestamp != timestamp] - - def update_portfolio_values(self, timestamp: datetime): - """更新投资组合价值""" - try: - # 获取当前所有持仓的价格 - current_prices = {} - benchmark_price = None - - for stock_code in self.portfolio.positions.keys(): - if stock_code in self.data_cache: - df = self.data_cache[stock_code] - price_data = df[df.index == timestamp] - if not price_data.empty: - current_prices[stock_code] = price_data['close'].iloc[0] - # 使用第一只股票作为基准 - if benchmark_price is None: - benchmark_price = price_data['close'].iloc[0] - - # 如果没有持仓,使用第一只股票作为基准 - if benchmark_price is None and self.stock_codes: - stock_code = self.stock_codes[0] - if stock_code in self.data_cache: - df = self.data_cache[stock_code] - price_data = df[df.index == timestamp] - if not price_data.empty: - benchmark_price = price_data['close'].iloc[0] - - # 更新投资组合市值 - self.portfolio.update_market_values(current_prices) - - # 记录到性能分析器 - self.performance_analyzer.add_portfolio_value(timestamp, self.portfolio.total_value) - - # 记录基准价格 - if benchmark_price is not None: - self.performance_analyzer.add_benchmark_value(timestamp, benchmark_price) - - except Exception as e: - logger.error(f"更新投资组合价值失败: {e}") - - def run_backtest(self, progress_callback=None) -> bool: - """ - 运行回测 - - Args: - progress_callback: 进度回调函数,接收参数 (current, total, message) - - Returns: - bool: 回测是否成功完成 - """ - try: - logger.info("开始回测...") - self.is_running = True - self.progress_callback = progress_callback - - # 检查必要条件 - if not self.strategy: - logger.error("未设置交易策略") - return False - - # 加载数据 - if not self.load_data_from_database(): - logger.error("数据加载失败") - return False - - if not self.data_cache: - logger.error("未加载数据") - return False - - # 初始化策略 - self.strategy.initialize() - - # 获取所有交易日期 - trading_dates = self.get_trading_dates() - total_days = len(trading_dates) - - if total_days == 0: - logger.error("无交易数据") - return False - - logger.info(f"回测期间: {trading_dates[0]} ~ {trading_dates[-1]}") - logger.info(f"交易日数: {total_days}") - - # 记录初始投资组合价值 - self.performance_analyzer.add_portfolio_value(trading_dates[0], self.portfolio.total_value) - - # 记录初始基准价格 - initial_benchmark_price = None - if self.stock_codes: - stock_code = self.stock_codes[0] - if stock_code in self.data_cache: - df = self.data_cache[stock_code] - price_data = df[df.index == trading_dates[0]] - if not price_data.empty: - initial_benchmark_price = price_data['close'].iloc[0] - self.performance_analyzer.add_benchmark_value(trading_dates[0], initial_benchmark_price) - - # 逐日回测 - for i, current_date in enumerate(trading_dates): - try: - self.current_date = current_date - - # 更新进度 - if progress_callback: - progress_callback(i + 1, total_days, f"处理 {current_date.strftime('%Y-%m-%d')}") - - # 为每只股票准备数据并调用策略 - for stock_code in self.stock_codes: - if stock_code in self.data_cache: - # 获取历史数据 - historical_data = self.get_data_at_date(current_date, stock_code) - - if not historical_data.empty: - # 调用策略处理数据 - self.strategy.on_data(historical_data, current_date) - - # 执行交易信号 - self.execute_signals(current_date) - - # 更新投资组合价值 - self.update_portfolio_values(current_date) - - # 检查是否被中断 - if not self.is_running: - logger.info("回测被用户中断") - return False - - except Exception as e: - logger.error(f"处理 {current_date} 数据失败: {e}") - continue - - logger.info("回测完成") - return True - - except Exception as e: - logger.error(f"回测运行失败: {e}") - return False - finally: - self.is_running = False - - def stop_backtest(self): - """停止回测""" - self.is_running = False - logger.info("正在停止回测...") - - def get_results(self): - """获取回测结果""" - if not self.performance_analyzer.portfolio_values: - logger.warning("无回测结果") - return None - - return self.performance_analyzer.generate_report() - - def print_summary(self): - """打印回测摘要""" - report = self.get_results() - if report: - self.performance_analyzer.print_report(report) - else: - print("无可用的回测结果") - - def save_results(self, filepath: str): - """保存回测结果到文件""" - try: - report = self.get_results() - if not report: - logger.warning("无回测结果可保存") - return False - - # 创建结果字典 - results = { - 'summary': { - 'total_return': report.total_return, - 'annual_return': report.annual_return, - 'max_drawdown': report.max_drawdown, - 'sharpe_ratio': report.sharpe_ratio, - 'total_trades': report.total_trades, - 'win_rate': report.win_rate - }, - 'yearly_stats': [ - { - 'year': stats.year, - 'return_rate': stats.return_rate, - 'max_drawdown': stats.max_drawdown, - 'sharpe_ratio': stats.sharpe_ratio, - 'trades_count': stats.trades_count - } - for stats in report.yearly_stats - ], - 'portfolio_values': [ - {'timestamp': ts.isoformat(), 'value': val} - for ts, val in self.performance_analyzer.portfolio_values - ], - 'trades': [ - { - 'timestamp': trade.timestamp.isoformat(), - 'stock_code': trade.stock_code, - 'action': trade.action, - 'shares': trade.shares, - 'price': trade.price, - 'total_amount': trade.total_amount - } - for trade in self.performance_analyzer.trades - ] - } - - import json - with open(filepath, 'w', encoding='utf-8') as f: - json.dump(results, f, ensure_ascii=False, indent=2) - - logger.info(f"回测结果已保存到: {filepath}") - return True - - except Exception as e: - logger.error(f"保存回测结果失败: {e}") - return False - - -def create_simple_backtest() -> BacktestEngine: - """创建一个简单的回测引擎实例""" - engine = BacktestEngine(initial_capital=1000000.0) - return engine diff --git a/src/back_trader/multi_timeframe_ma_backtest_strategy.py b/src/back_trader/multi_timeframe_ma_backtest_strategy.py deleted file mode 100644 index de94359..0000000 --- a/src/back_trader/multi_timeframe_ma_backtest_strategy.py +++ /dev/null @@ -1,793 +0,0 @@ -#!/usr/bin/env python3 -""" -多时间周期MA策略 - 回测专用版本(最新优化版) -- 使用1分钟数据进行回测,买点每5分钟检查一次,卖点每15分钟检查一次 -- 评分系统:15/30/60分钟周期MA5/MA18交叉,金叉+1分,死叉-1分,起始分数为0 -- 买入条件:15分钟持续金叉且实时股价 > 日K5日线且分数>0且价格与当天分时均价差距<1% -- 卖出条件:分数≤0时清仓卖出 -- T+1限制:当天买入的股票不能卖出 -- 止盈机制:可选择达到止盈点时清仓并置0分 -""" - -import os -import sys -import pandas as pd -import logging -from datetime import datetime, timedelta -from typing import Dict, List, Optional -import numpy as np - -# 添加项目路径 -project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -sys.path.append(project_root) - -try: - from strategy_base import StrategyBase, Signal - from data_process_model.database_config import init_database - from data_process_model.stock_models import create_stock_kline_model, SUPPORTED_PERIODS -except ImportError as e: - print(f"导入错误: {e}") - sys.exit(1) - -logger = logging.getLogger(__name__) - -class MultiTimeframeMABacktestStrategy(StrategyBase): - """ - 多时间周期MA策略 - 回测版本(最新优化版) - - 特点: - - 回测数据:1分钟K线数据,买点每5分钟检查一次,卖点每15分钟检查一次 - - 评分系统:15/30/60分钟周期MA5/MA18交叉,金叉+1分,死叉-1分,起始分数0 - - 买入条件:15分钟金叉且实时股价 > 买入系数*日K5日线且分数>0且价格与分时均价差距<1% - - 卖出条件:分数≤0时清仓卖出 - - T+1限制:当天买入的股票不能卖出 - - 止盈机制:可选择达到止盈点时清仓并置0分 - """ - - def __init__(self, stock_code: str = "601398.SH", profit_target: Optional[float] = None, buy_low_ratio: float = 0.99): - """ - 初始化策略 - - Args: - stock_code: 股票代码 - profit_target: 止盈阈值(小数形式,如0.03表示3%),None表示不设置止盈 - buy_low_ratio: 买入条件系数,股价大于该系数*日K5日线时可买入,默认0.97 - """ - super().__init__(name="MultiTimeframeMABacktest") - - self.description = "多时间周期MA交叉策略 - 回测版本" - self.stock_code = stock_code - - # MA参数 - self.ma_periods = [5, 18] - - # 信号计算时间周期(用于计算交叉信号) - self.signal_timeframes = ['15m', '30m', '60m'] - - # 日线数据用于买点条件判断 - self.daily_timeframe = '1d' - - # 股票评分系统 - self.stock_scores = {stock_code: 0} - - # 持仓状态跟踪 - self.holding_stocks = {stock_code: False} # 跟踪是否持有股票 - self.buy_dates = {stock_code: None} # 记录买入日期(用于T+1限制) - self.buy_prices = {stock_code: 0.0} # 记录买入价格(用于止盈计算) - - # 止盈参数 - self.profit_target = profit_target # 止盈阈值,None表示不设置止盈 - - # 买入条件参数 - self.buy_low_ratio = buy_low_ratio # 买入条件系数,股价 > buy_low_ratio * 日K5日线 - - # 交易参数 - 全仓交易模式 - # 不再使用固定金额,改为全仓买卖 - - # 仓位管理参数 - 简化版本 - # 不再需要复杂的仓位管理,只有全仓买入和清仓 - - # 时间周期数据缓存 - self.timeframe_data = {} - self.model_cache = {} - - # 上次交叉状态记录(避免重复信号) - self.last_crossover_status = {} - - # 上次信号时的MA差值记录 - self.last_signal_diff = {} - - # 信号记录 - self.crossover_signals = [] - self.signal_stats = {tf: {'golden_cross': 0, 'death_cross': 0} for tf in self.signal_timeframes} - - # 数据更新时间记录 - self.last_update_times = {} - - def initialize(self) -> bool: - """初始化策略""" - try: - # 初始化数据库连接 - init_database() - - logger.info(f"[{self.name}] 初始化多时间周期MA回测策略") - logger.info(f"[{self.name}] 股票代码: {self.stock_code}") - logger.info(f"[{self.name}] 信号时间周期: {self.signal_timeframes}") - logger.info(f"[{self.name}] MA周期: {self.ma_periods}") - logger.info(f"[{self.name}] 买入判断: 每5分钟检查一次") - logger.info(f"[{self.name}] 卖出判断: 每15分钟检查一次") - logger.info(f"[{self.name}] 买入条件: 15分钟持续金叉且股价>日K5日线且分数>0且价格与分时均价差距<1%") - logger.info(f"[{self.name}] 卖出条件: 分数≤0时清仓") - logger.info(f"[{self.name}] T+1限制: 当天买入不能卖出") - if self.profit_target is not None: - logger.info(f"[{self.name}] 止盈设置: {self.profit_target*100:.1f}%") - else: - logger.info(f"[{self.name}] 止盈设置: 无止盈") - - # 创建各时间周期的数据库模型 - self._create_timeframe_models() - - # 初始化交叉状态 - for tf in self.signal_timeframes: - self.last_crossover_status[tf] = None - self.last_signal_diff[tf] = 0.0 - self.last_update_times[tf] = None - - return True - - except Exception as e: - logger.error(f"[{self.name}] 策略初始化失败: {e}") - return False - - def _create_timeframe_models(self): - """创建各时间周期的数据库模型""" - try: - # 创建分钟级别时间周期模型 - for tf in self.signal_timeframes: - self.model_cache[tf] = create_stock_kline_model(self.stock_code, tf) - logger.info(f"[{self.name}] 创建 {tf} 模型: {self.model_cache[tf]._meta.table_name}") - - # 创建日线模型用于5日均线计算 - self.model_cache[self.daily_timeframe] = create_stock_kline_model(self.stock_code, self.daily_timeframe) - logger.info(f"[{self.name}] 创建 {self.daily_timeframe} 模型: {self.model_cache[self.daily_timeframe]._meta.table_name}") - - except Exception as e: - logger.error(f"[{self.name}] 创建时间周期模型失败: {e}") - - def _get_timeframe_data(self, timeframe: str, end_time: datetime, lookback_periods: int = 50) -> pd.DataFrame: - """ - 获取指定时间周期的数据 - - Args: - timeframe: 时间周期 ('15m', '30m', '60m') - end_time: 结束时间 - lookback_periods: 向前查看的周期数 - - Returns: - pd.DataFrame: 包含MA5和MA18的数据 - """ - try: - if timeframe not in self.model_cache: - return pd.DataFrame() - - model_class = self.model_cache[timeframe] - - # 查询数据,获取end_time之前的数据 - query = model_class.select().where( - model_class.timestamp <= end_time - ).order_by(model_class.timestamp.desc()).limit(lookback_periods) - - # 转换为DataFrame - data = [] - for record in query: - data.append({ - 'timestamp': record.timestamp, - 'open': float(record.open), - 'high': float(record.high), - 'low': float(record.low), - 'close': float(record.close), - 'volume': record.volume - }) - - if not data: - return pd.DataFrame() - - df = pd.DataFrame(data) - df['timestamp'] = pd.to_datetime(df['timestamp']) - df = df.set_index('timestamp').sort_index() - - # 计算移动平均线 - df['MA5'] = df['close'].rolling(window=5, min_periods=5).mean() - df['MA18'] = df['close'].rolling(window=18, min_periods=18).mean() - - return df - - except Exception as e: - logger.error(f"[{self.name}] 获取{timeframe}数据失败: {e}") - return pd.DataFrame() - - def _detect_ma_crossover(self, df: pd.DataFrame, timeframe: str) -> Optional[str]: - """ - 检测MA交叉信号(无阈值判定) - - Args: - df: 包含MA5和MA18的数据 - timeframe: 时间周期 - - Returns: - str: 'golden_cross', 'death_cross', 或 None - """ - if len(df) < 5 or 'MA5' not in df.columns or 'MA18' not in df.columns: - return None - - # 获取最近5个数据点来判断趋势 - recent_data = df.tail(5) - if len(recent_data) < 5: - return None - - ma5_values = recent_data['MA5'].values - ma18_values = recent_data['MA18'].values - - # 检查是否有NaN值 - if np.isnan(ma5_values).any() or np.isnan(ma18_values).any(): - return None - - # 当前MA值 - curr_ma5, curr_ma18 = ma5_values[-1], ma18_values[-1] - - # 分析前几个点的MA关系,确定是否发生了真正的交叉 - # 检查前3个点的MA5和MA18关系 - prev_relations = [] - for i in range(len(ma5_values) - 1): # 不包括最后一个点 - if ma5_values[i] > ma18_values[i]: - prev_relations.append('above') - elif ma5_values[i] < ma18_values[i]: - prev_relations.append('below') - else: - prev_relations.append('equal') - - # 当前关系 - if curr_ma5 > curr_ma18: - curr_relation = 'above' - elif curr_ma5 < curr_ma18: - curr_relation = 'below' - else: - curr_relation = 'equal' - - # 判断是否发生了交叉(去掉阈值判断) - # 金叉:前面大部分时间MA5在MA18下方,现在MA5在MA18上方 - if curr_relation == 'above': - # 检查前面的点是否大部分时间MA5在MA18下方 - below_count = prev_relations.count('below') - if below_count >= len(prev_relations) * 0.6: # 至少60%的时间在下方 - return 'golden_cross' - - # 死叉:前面大部分时间MA5在MA18上方,现在MA5在MA18下方 - elif curr_relation == 'below': - # 检查前面的点是否大部分时间MA5在MA18上方 - above_count = prev_relations.count('above') - if above_count >= len(prev_relations) * 0.6: # 至少60%的时间在上方 - return 'death_cross' - - return None - - def _should_update_timeframe(self, timeframe: str, current_time: datetime) -> bool: - """ - 判断是否需要更新特定时间周期的数据 - - Args: - timeframe: 时间周期 - current_time: 当前时间 - - Returns: - bool: 是否需要更新 - """ - if timeframe not in self.last_update_times or self.last_update_times[timeframe] is None: - return True - - last_update = self.last_update_times[timeframe] - - # 根据时间周期确定更新间隔 - if timeframe == '15m': - interval = timedelta(minutes=15) - elif timeframe == '30m': - interval = timedelta(minutes=30) - elif timeframe == '60m': - interval = timedelta(minutes=60) - else: - interval = timedelta(minutes=1) - - return current_time >= last_update + interval - - def on_data(self, data: pd.DataFrame, timestamp: datetime): - """ - 处理新的1分钟数据 - - 买点策略:每5分钟判断一次,查看当前15分钟持续金叉状态,且价格大于日K5日线,且价格与分时均价差距<1% - 卖点策略:每15分钟判断一次,查看当前股票分数,若≤0则清仓卖出 - - Args: - data: 1分钟K线数据(用于回测) - timestamp: 当前时间戳 - """ - try: - stock_code = getattr(data, 'stock_code', self.stock_code) - - if stock_code not in self.stock_scores: - self.stock_scores[stock_code] = 0 - self.holding_stocks[stock_code] = False - self.buy_dates[stock_code] = None - self.buy_prices[stock_code] = 0.0 - - # 获取当前价格 - if data.empty: - return - current_price = data['close'].iloc[-1] - - # 每分钟都检查止盈条件(优先级最高) - if self._check_profit_target(stock_code, current_price, timestamp): - return # 已经执行止盈,直接返回 - - # 买点判断:每5分钟判断一次(0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55) - if timestamp.minute % 5 == 0: - self._check_buy_signals(stock_code, current_price, timestamp) - - # 卖点判断:每15分钟判断一次(0, 15, 30, 45) - if timestamp.minute % 15 == 0: - # 先更新分数(检查所有时间周期的交叉信号) - old_score = self.stock_scores[stock_code] - new_score = self._update_score(stock_code, timestamp) - self.stock_scores[stock_code] = new_score - - # 检查卖出条件 - self._check_sell_signals(stock_code, new_score, current_price, timestamp) - - except Exception as e: - logger.error(f"[{self.name}] 处理数据时出错: {e}") - - def _check_profit_target(self, stock_code: str, current_price: float, timestamp: datetime) -> bool: - """ - 检查止盈条件 - - Args: - stock_code: 股票代码 - current_price: 当前价格 - timestamp: 当前时间 - - Returns: - bool: 是否触发止盈 - """ - # 如果没有设置止盈,直接返回False - if self.profit_target is None: - return False - - if not self.holding_stocks[stock_code] or self.buy_prices[stock_code] <= 0: - return False - - buy_price = self.buy_prices[stock_code] - profit_rate = (current_price - buy_price) / buy_price - - if profit_rate >= self.profit_target: - # 检查T+1限制 - if self._can_sell_today(stock_code, timestamp): - # 触发止盈,清仓并置0分 - signal = Signal( - stock_code=stock_code, - action='SELL_ALL', - amount=0, - price=None, - timestamp=timestamp, - reason=f"profit_target_{profit_rate:.2%}_reached" - ) - self.signals.append(signal) - - # 重置状态 - self.holding_stocks[stock_code] = False - self.stock_scores[stock_code] = 0 - self.buy_dates[stock_code] = None - self.buy_prices[stock_code] = 0.0 - - return True - - return False - - def _check_price_above_ma5_daily(self, stock_code: str, current_price: float, timestamp: datetime) -> bool: - """ - 检查当前股价是否大于买入阈值*日K5日均线 - - Args: - stock_code: 股票代码 - current_price: 当前价格 - timestamp: 当前时间 - - Returns: - bool: 是否满足买入价格条件 - """ - try: - if self.daily_timeframe not in self.model_cache: - logger.warning(f"[{self.name}] 日线模型未创建,跳过5日均线检查") - return True # 如果没有日线数据,默认通过 - - # 获取日线数据 - daily_data = self._get_timeframe_data(self.daily_timeframe, timestamp, lookback_periods=10) - - if daily_data.empty or 'MA5' not in daily_data.columns: - logger.warning(f"[{self.name}] 无法获取日线MA5数据,跳过检查") - return True # 如果没有足够数据,默认通过 - - # 获取最新的5日均线值 - latest_ma5 = daily_data['MA5'].iloc[-1] - - if np.isnan(latest_ma5): - logger.warning(f"[{self.name}] 5日均线数据无效,跳过检查") - return True - - # 检查当前价格是否大于5日均线(去掉阈值判断) - is_above = current_price > latest_ma5 - - logger.info(f"[{self.name}] 价格条件检查: 当前价格={current_price:.4f}, 5日均线={latest_ma5:.4f}, 必须大于5日均线,满足条件={is_above}") - - return is_above - - except Exception as e: - logger.error(f"[{self.name}] 检查买入价格条件时出错: {e}") - return True # 出错时默认通过 - - def _check_price_vs_intraday_avg(self, stock_code: str, current_price: float, timestamp: datetime) -> bool: - """ - 检查实时股价与当天分时均价的差距 - - Args: - stock_code: 股票代码 - current_price: 当前价格 - timestamp: 当前时间 - - Returns: - bool: 差距是否小于均价的3% - """ - try: - # 获取当天开盘时间(9:30) - trade_date = timestamp.date() - market_open = datetime.combine(trade_date, datetime.strptime("09:30", "%H:%M").time()) - - # 如果当前时间在开盘前,无法计算分时均价 - if timestamp < market_open: - logger.info(f"[{self.name}] 未到开盘时间,跳过分时均价检查") - return True - - # 获取当天从开盘到当前时间的1分钟数据 - if '1m' not in self.model_cache: - logger.warning(f"[{self.name}] 1分钟模型未创建,跳过分时均价检查") - return True - - model = self.model_cache['1m'] - - # 查询当天的数据 - daily_records = (model.select() - .where( - (model.timestamp >= market_open) & - (model.timestamp <= timestamp) - ) - .order_by(model.timestamp)) - - if not daily_records.exists(): - logger.warning(f"[{self.name}] 没有找到当天的1分钟数据,跳过分时均价检查") - return True - - # 计算当天的分时均价 (VWAP - Volume Weighted Average Price) - total_volume = 0 - total_amount = 0 - - for record in daily_records: - if record.volume > 0: # 只计算有成交量的记录 - # 使用典型价格 (high + low + close) / 3 作为该分钟的代表价格 - typical_price = (record.high + record.low + record.close) / 3 - total_amount += typical_price * record.volume - total_volume += record.volume - - if total_volume <= 0: - logger.warning(f"[{self.name}] 当天无有效成交量数据,跳过分时均价检查") - return True - - # 计算分时均价(VWAP) - intraday_vwap = total_amount / total_volume - - # 计算当前价格与分时均价的差距 - price_diff = abs(current_price - intraday_vwap) - price_diff_ratio = price_diff / intraday_vwap - - # 检查差距是否小于均价的1%(更严格的条件) - threshold = 0.01 # 1% - is_close_enough = price_diff_ratio < threshold - - logger.info(f"[{self.name}] 分时均价检查: 当前价格={current_price:.4f}, 分时均价={intraday_vwap:.4f}, " - f"差距比例={price_diff_ratio:.4f}({price_diff_ratio*100:.2f}%), " - f"阈值={threshold*100:.1f}%, 满足条件={is_close_enough}") - - return is_close_enough - - except Exception as e: - logger.error(f"[{self.name}] 检查分时均价条件时出错: {e}") - return True # 出错时默认通过 - - def _update_score(self, stock_code: str, timestamp: datetime) -> int: - """ - 更新股票分数(检查所有时间周期) - - Args: - stock_code: 股票代码 - timestamp: 当前时间 - - Returns: - int: 新的分数 - """ - current_score = self.stock_scores[stock_code] - score_changes = [] - - # 检查所有时间周期 - for timeframe in self.signal_timeframes: - tf_data = self._get_timeframe_data(timeframe, timestamp, lookback_periods=100) - - if tf_data.empty: - continue - - # 检测交叉信号 - crossover = self._detect_ma_crossover(tf_data, timeframe) - - if crossover: - # 检查是否与上次信号重复 - last_status = self.last_crossover_status.get(timeframe, None) - if last_status == crossover: - continue # 重复信号,跳过 - - # 更新状态 - self.last_crossover_status[timeframe] = crossover - - # 记录信号 - self._record_crossover_signal(stock_code, timestamp, timeframe, crossover, tf_data) - - # 记录分数变化 - if crossover == 'golden_cross': - score_changes.append(1) # 金叉+1分 - elif crossover == 'death_cross': - score_changes.append(-1) # 死叉-1分 - - # 计算新分数(分数最低为0) - total_change = sum(score_changes) - new_score = max(0, current_score + total_change) - - return new_score - - def _check_buy_signals(self, stock_code: str, current_price: float, timestamp: datetime): - """ - 检查买入信号(每5分钟调用一次) - 买入条件:当前15分钟已金叉且持续金叉状态 且 股价大于日K5日线 - - Args: - stock_code: 股票代码 - current_price: 当前价格 - timestamp: 当前时间 - """ - # 如果已持仓,不需要再检查买入 - if self.holding_stocks[stock_code]: - return - - # 检查15分钟级别是否处于持续金叉状态 - tf_15m_data = self._get_timeframe_data('15m', timestamp, lookback_periods=50) - if tf_15m_data.empty or 'MA5' not in tf_15m_data.columns or 'MA18' not in tf_15m_data.columns: - return - - # 检查是否为有效金叉状态: - # 1. 当前MA5 > MA18 - # 2. 在最近的几个周期内都保持MA5 > MA18(确保金叉状态持续) - recent_periods = min(5, len(tf_15m_data)) # 检查最近5个周期或全部数据 - recent_data = tf_15m_data.tail(recent_periods) - - ma5_values = recent_data['MA5'].values - ma18_values = recent_data['MA18'].values - - # 检查是否为有效数值 - if np.isnan(ma5_values).any() or np.isnan(ma18_values).any(): - return - - # 当前必须是金叉状态 - current_is_golden = ma5_values[-1] > ma18_values[-1] - if not current_is_golden: - return # 当前不是金叉状态,不买入 - - # 检查金叉状态的持续性:至少在最近3个周期内MA5都大于MA18 - # 这确保不是刚刚发生的临时交叉 - if len(ma5_values) >= 3: - recent_3_periods = ma5_values[-3:] > ma18_values[-3:] - golden_persistence = np.sum(recent_3_periods) >= 2 # 至少3个周期中有2个是金叉 - - if not golden_persistence: - logger.info(f"[{self.name}] 15分钟金叉状态不够稳定,暂不买入") - return - - logger.info(f"[{self.name}] 15分钟确认持续金叉状态: MA5={ma5_values[-1]:.4f} > MA18={ma18_values[-1]:.4f}") - - # 检查股价是否大于日K5日线(去掉阈值判断) - if not self._check_price_above_ma5_daily(stock_code, current_price, timestamp): - return # 价格条件不满足,不买入 - - # 检查当前分数是否大于0 - if self.stock_scores[stock_code] <= 0: - return # 分数不够,不买入 - - # 检查实时股价与当天分时均价的差距(新增条件) - if not self._check_price_vs_intraday_avg(stock_code, current_price, timestamp): - return # 价格与分时均价差距过大,不买入 - - # 满足所有买入条件,执行买入 - signal = Signal( - stock_code=stock_code, - action='BUY_ALL', - amount=0, - price=None, - timestamp=timestamp, - reason=f"15m_golden_cross_and_price_above_ma5_and_close_to_vwap_1pct" - ) - self.signals.append(signal) - - # 更新持仓状态 - self.holding_stocks[stock_code] = True - self.buy_dates[stock_code] = timestamp - - logger.info(f"[{self.name}] 买入信号: 15分钟金叉状态且股价>日K5日线且分数={self.stock_scores[stock_code]}且价格与分时均价差距<1%") - - def _check_sell_signals(self, stock_code: str, current_score: int, current_price: float, timestamp: datetime): - """ - 检查卖出信号(每15分钟调用一次) - 卖出条件:当前股票分数≤0 - - Args: - stock_code: 股票代码 - current_score: 当前分数 - current_price: 当前价格 - timestamp: 当前时间 - """ - # 如果未持仓,不需要检查卖出 - if not self.holding_stocks[stock_code]: - return - - # 检查卖出条件:分数≤0 - if current_score <= 0: - # 检查T+1限制 - if self._can_sell_today(stock_code, timestamp): - signal = Signal( - stock_code=stock_code, - action='SELL_ALL', - amount=0, - price=None, - timestamp=timestamp, - reason=f"score_{current_score}_sell_all" - ) - self.signals.append(signal) - - # 更新持仓状态 - self.holding_stocks[stock_code] = False - self.buy_dates[stock_code] = None - self.buy_prices[stock_code] = 0.0 - - logger.info(f"[{self.name}] 卖出信号: 分数={current_score}≤0,清仓卖出") - else: - logger.info(f"[{self.name}] 卖出信号被T+1限制,暂不卖出") - - def _handle_trading_signals(self, stock_code: str, old_score: int, new_score: int, - current_price: float, timestamp: datetime): - """ - 处理交易信号 - - Args: - stock_code: 股票代码 - old_score: 旧分数 - new_score: 新分数 - current_price: 当前价格 - timestamp: 当前时间 - """ - # 更新分数 - self.stock_scores[stock_code] = new_score - - # 检查买入条件:分数>0且股价>买入阈值*日K5日线且未持仓 - if (new_score > 0 and - not self.holding_stocks[stock_code] and - self._check_price_above_ma5_daily(stock_code, current_price, timestamp)): - - # 执行买入 - signal = Signal( - stock_code=stock_code, - action='BUY_ALL', - amount=0, - price=None, - timestamp=timestamp, - reason=f"score_{new_score}_above_ma5_daily_buy" - ) - self.signals.append(signal) - - # 更新持仓状态 - self.holding_stocks[stock_code] = True - self.buy_dates[stock_code] = timestamp - - logger.info(f"[{self.name}] 买入信号: 分数={new_score}>0且股价满足买入条件") - - # 检查卖出条件:分数从>0变成0且持有股票 - elif (old_score > 0 and new_score == 0 and self.holding_stocks[stock_code]): - - # 检查T+1限制 - if self._can_sell_today(stock_code, timestamp): - signal = Signal( - stock_code=stock_code, - action='SELL_ALL', - amount=0, - price=None, - timestamp=timestamp, - reason=f"score_to_0_sell_all" - ) - self.signals.append(signal) - - # 更新持仓状态 - self.holding_stocks[stock_code] = False - self.buy_dates[stock_code] = None - self.buy_prices[stock_code] = 0.0 - - logger.info(f"[{self.name}] 卖出信号: 分数变为0") - else: - logger.info(f"[{self.name}] 卖出信号被T+1限制,暂不卖出") - - def _can_sell_today(self, stock_code: str, timestamp: datetime) -> bool: - """ - 检查是否可以在当天卖出(T+1限制) - - Args: - stock_code: 股票代码 - timestamp: 当前时间 - - Returns: - bool: 是否可以卖出 - """ - if stock_code not in self.buy_dates or self.buy_dates[stock_code] is None: - return True # 没有买入记录,可以卖出 - - buy_date = self.buy_dates[stock_code].date() - current_date = timestamp.date() - - return current_date > buy_date # 只有在买入日期之后才能卖出 - - def _record_crossover_signal(self, stock_code: str, timestamp: datetime, timeframe: str, crossover: str, tf_data: pd.DataFrame): - """记录交叉信号""" - ma5_val = tf_data['MA5'].iloc[-1] - ma18_val = tf_data['MA18'].iloc[-1] - diff_abs = abs(ma5_val - ma18_val) - - signal_record = { - 'timestamp': timestamp, - 'timeframe': timeframe, - 'signal_type': crossover, - 'stock_code': stock_code, - 'ma5': ma5_val, - 'ma18': ma18_val, - 'close_price': tf_data['close'].iloc[-1], - 'diff_abs': diff_abs - } - self.crossover_signals.append(signal_record) - self.signal_stats[timeframe][crossover] += 1 - - def update_buy_price(self, stock_code: str, buy_price: float): - """ - 更新买入价格(由回测引擎调用) - - Args: - stock_code: 股票代码 - buy_price: 买入价格 - """ - self.buy_prices[stock_code] = buy_price - - def get_signal_statistics(self) -> Dict: - """获取信号统计信息""" - return { - 'total_signals': len(self.crossover_signals), - 'timeframe_stats': self.signal_stats.copy(), - 'current_scores': self.stock_scores.copy(), - 'recent_signals': self.crossover_signals[-10:] if self.crossover_signals else [] - } diff --git a/src/back_trader/multi_timeframe_ma_score_strategy.py b/src/back_trader/multi_timeframe_ma_score_strategy.py deleted file mode 100644 index e69de29..0000000 diff --git a/src/back_trader/performance_analyzer.py b/src/back_trader/performance_analyzer.py deleted file mode 100644 index 07368f7..0000000 --- a/src/back_trader/performance_analyzer.py +++ /dev/null @@ -1,392 +0,0 @@ -""" -回测性能分析模块 - -计算和展示回测结果的各种性能指标 -""" - -import pandas as pd -import numpy as np -from datetime import datetime, timedelta -from typing import Dict, List, Any, Tuple -import logging -from dataclasses import dataclass - -logger = logging.getLogger(__name__) - - -@dataclass -class YearlyStats: - """年度统计数据""" - year: int - start_value: float - end_value: float - return_rate: float - max_drawdown: float - max_drawdown_duration: int # 最大回撤持续天数 - sharpe_ratio: float - trades_count: int - win_rate: float - - -@dataclass -class PerformanceReport: - """性能报告""" - # 总体指标 - total_return: float - annual_return: float - benchmark_return: float # 基准收益(股票涨跌幅) - max_drawdown: float - max_drawdown_duration: int - sharpe_ratio: float - calmar_ratio: float - - # 交易统计 - total_trades: int - win_rate: float - profit_factor: float - avg_win: float - avg_loss: float - - # 年度统计 - yearly_stats: List[YearlyStats] - - # 其他指标 - volatility: float - beta: float = 0.0 # 相对基准的贝塔值 - alpha: float = 0.0 # 相对基准的阿尔法值 - - -class PerformanceAnalyzer: - """性能分析器""" - - def __init__(self): - self.portfolio_values: List[Tuple[datetime, float]] = [] - self.trades: List[Any] = [] - self.benchmark_values: List[Tuple[datetime, float]] = [] - - def add_portfolio_value(self, timestamp: datetime, value: float): - """添加组合价值记录""" - self.portfolio_values.append((timestamp, value)) - - def add_trade(self, trade): - """添加交易记录""" - self.trades.append(trade) - - def add_benchmark_value(self, timestamp: datetime, value: float): - """添加基准价值记录""" - self.benchmark_values.append((timestamp, value)) - - def calculate_returns(self, values: List[Tuple[datetime, float]]) -> pd.Series: - """计算日收益率序列""" - if len(values) < 2: - return pd.Series() - - df = pd.DataFrame(values, columns=['timestamp', 'value']) - df.set_index('timestamp', inplace=True) - df.sort_index(inplace=True) - - # 按日重采样,取最后一个值 - daily_values = df.resample('D').last().dropna() - - # 计算日收益率 - if len(daily_values) < 2: - return pd.Series() - - returns = daily_values['value'].pct_change().dropna() - return returns - - def calculate_max_drawdown(self, values: List[Tuple[datetime, float]]) -> Tuple[float, int]: - """ - 计算最大回撤和持续时间 - - Returns: - tuple: (最大回撤比例, 最大回撤持续天数) - """ - if len(values) < 2: - return 0.0, 0 - - df = pd.DataFrame(values, columns=['timestamp', 'value']) - df.set_index('timestamp', inplace=True) - df.sort_index(inplace=True) - - # 计算累计最高值 - df['cummax'] = df['value'].cummax() - - # 计算回撤 - df['drawdown'] = (df['value'] - df['cummax']) / df['cummax'] - - # 最大回撤 - max_drawdown = df['drawdown'].min() - - # 计算最大回撤持续时间(以天为单位) - max_dd_duration = 0 - current_dd_start = None - in_drawdown = False - - for timestamp, dd in zip(df.index, df['drawdown']): - if dd < 0: # 处于回撤中 - if not in_drawdown: # 刚开始回撤 - current_dd_start = timestamp - in_drawdown = True - else: # 回撤结束 - if in_drawdown and current_dd_start is not None: - # 计算回撤持续天数 - duration_days = (timestamp - current_dd_start).days - max_dd_duration = max(max_dd_duration, duration_days) - in_drawdown = False - - # 处理回测结束时仍在回撤的情况 - if in_drawdown and current_dd_start is not None: - duration_days = (df.index[-1] - current_dd_start).days - max_dd_duration = max(max_dd_duration, duration_days) - - return abs(max_drawdown), max_dd_duration - - def calculate_sharpe_ratio(self, returns: pd.Series, risk_free_rate: float = 0.03) -> float: - """ - 计算夏普比率 - - Args: - returns: 收益率序列 - risk_free_rate: 无风险利率(年化) - - Returns: - float: 夏普比率 - """ - if len(returns) == 0 or returns.std() == 0: - return 0.0 - - # 转换为年化收益率和波动率 - annual_return = returns.mean() * 252 # 假设252个交易日 - annual_volatility = returns.std() * np.sqrt(252) - - if annual_volatility == 0: - return 0.0 - - sharpe = (annual_return - risk_free_rate) / annual_volatility - return sharpe - - def calculate_calmar_ratio(self, annual_return: float, max_drawdown: float) -> float: - """计算卡尔玛比率""" - if max_drawdown == 0: - return float('inf') if annual_return > 0 else 0.0 - return annual_return / max_drawdown - - def analyze_trades(self) -> Dict[str, float]: - """分析交易统计""" - if len(self.trades) == 0: - return { - 'total_trades': 0, - 'win_rate': 0.0, - 'profit_factor': 0.0, - 'avg_win': 0.0, - 'avg_loss': 0.0 - } - - # 计算每笔交易的盈亏 - trade_pnls = [] - buy_trades = {} # 存储买入交易 - - for trade in self.trades: - if trade.action == 'BUY': - # 存储买入交易 - if trade.stock_code not in buy_trades: - buy_trades[trade.stock_code] = [] - buy_trades[trade.stock_code].append(trade) - - elif trade.action == 'SELL': - # 匹配卖出和买入,计算盈亏 - if trade.stock_code in buy_trades and buy_trades[trade.stock_code]: - buy_trade = buy_trades[trade.stock_code].pop(0) # FIFO - pnl = (trade.price - buy_trade.price) * trade.shares - trade.commission - buy_trade.commission - trade_pnls.append(pnl) - - if len(trade_pnls) == 0: - return { - 'total_trades': len(self.trades), - 'win_rate': 0.0, - 'profit_factor': 0.0, - 'avg_win': 0.0, - 'avg_loss': 0.0 - } - - # 分类盈利和亏损交易 - wins = [pnl for pnl in trade_pnls if pnl > 0] - losses = [pnl for pnl in trade_pnls if pnl < 0] - - win_rate = len(wins) / len(trade_pnls) if trade_pnls else 0.0 - avg_win = np.mean(wins) if wins else 0.0 - avg_loss = np.mean(losses) if losses else 0.0 - - # 计算盈亏比 - total_profit = sum(wins) - total_loss = abs(sum(losses)) - profit_factor = total_profit / total_loss if total_loss > 0 else float('inf') - - return { - 'total_trades': len(trade_pnls), - 'win_rate': win_rate, - 'profit_factor': profit_factor, - 'avg_win': avg_win, - 'avg_loss': avg_loss - } - - def calculate_yearly_stats(self) -> List[YearlyStats]: - """计算年度统计数据""" - if len(self.portfolio_values) < 2: - return [] - - df = pd.DataFrame(self.portfolio_values, columns=['timestamp', 'value']) - df.set_index('timestamp', inplace=True) - df.sort_index(inplace=True) - - yearly_stats = [] - - # 按年分组 - for year in df.index.year.unique(): - year_data = df[df.index.year == year] - - if len(year_data) < 2: - continue - - start_value = year_data['value'].iloc[0] - end_value = year_data['value'].iloc[-1] - return_rate = (end_value - start_value) / start_value - - # 计算年度最大回撤 - year_values = [(ts, val) for ts, val in zip(year_data.index, year_data['value'])] - max_dd, max_dd_duration = self.calculate_max_drawdown(year_values) - - # 计算年度夏普比率 - year_returns = self.calculate_returns(year_values) - sharpe = self.calculate_sharpe_ratio(year_returns) - - # 统计年度交易 - year_trades = [t for t in self.trades - if t.timestamp.year == year and t.action == 'SELL'] - trades_count = len(year_trades) - - # 计算年度胜率(简化版) - if trades_count > 0: - # 这里简化处理,实际应该匹配买卖对 - win_rate = 0.5 # 占位值,实际应该计算 - else: - win_rate = 0.0 - - yearly_stats.append(YearlyStats( - year=int(year), - start_value=start_value, - end_value=end_value, - return_rate=return_rate, - max_drawdown=max_dd, - max_drawdown_duration=max_dd_duration, - sharpe_ratio=sharpe, - trades_count=trades_count, - win_rate=win_rate - )) - - return yearly_stats - - def generate_report(self) -> PerformanceReport: - """生成完整的性能报告""" - if len(self.portfolio_values) < 2: - logger.warning("数据不足,无法生成性能报告") - return None - - # 计算总体收益 - initial_value = self.portfolio_values[0][1] - final_value = self.portfolio_values[-1][1] - total_return = (final_value - initial_value) / initial_value - - # 计算年化收益 - start_date = self.portfolio_values[0][0] - end_date = self.portfolio_values[-1][0] - days = (end_date - start_date).days - years = days / 365.25 - annual_return = (1 + total_return) ** (1 / years) - 1 if years > 0 else 0 - - # 计算基准收益(股票涨跌幅) - benchmark_return = 0.0 - if len(self.benchmark_values) >= 2: - initial_benchmark = self.benchmark_values[0][1] - final_benchmark = self.benchmark_values[-1][1] - benchmark_return = (final_benchmark - initial_benchmark) / initial_benchmark - - # 计算最大回撤 - max_drawdown, max_dd_duration = self.calculate_max_drawdown(self.portfolio_values) - - # 计算夏普比率 - returns = self.calculate_returns(self.portfolio_values) - sharpe_ratio = self.calculate_sharpe_ratio(returns) - - # 计算卡尔玛比率 - calmar_ratio = self.calculate_calmar_ratio(annual_return, max_drawdown) - - # 分析交易 - trade_stats = self.analyze_trades() - - # 计算波动率 - volatility = returns.std() * np.sqrt(252) if len(returns) > 0 else 0.0 - - # 计算年度统计 - yearly_stats = self.calculate_yearly_stats() - - report = PerformanceReport( - total_return=total_return, - annual_return=annual_return, - benchmark_return=benchmark_return, - max_drawdown=max_drawdown, - max_drawdown_duration=max_dd_duration, - sharpe_ratio=sharpe_ratio, - calmar_ratio=calmar_ratio, - total_trades=trade_stats['total_trades'], - win_rate=trade_stats['win_rate'], - profit_factor=trade_stats['profit_factor'], - avg_win=trade_stats['avg_win'], - avg_loss=trade_stats['avg_loss'], - yearly_stats=yearly_stats, - volatility=volatility - ) - - return report - - def print_report(self, report: PerformanceReport): - """打印性能报告""" - if report is None: - print("无法生成性能报告") - return - - print("\n" + "="*60) - print(" 回测性能报告") - print("="*60) - - print(f"\n📊 总体指标:") - print(f"总收益率: {report.total_return*100:>8.2f}%") - print(f"基准收益: {report.benchmark_return*100:>8.2f}%") - print(f"年化收益率: {report.annual_return*100:>8.2f}%") - print(f"最大回撤: {report.max_drawdown*100:>8.2f}%") - print(f"回撤持续: {report.max_drawdown_duration:>8d} 天") - print(f"夏普比率: {report.sharpe_ratio:>8.2f}") - print(f"卡尔玛比率: {report.calmar_ratio:>8.2f}") - print(f"波动率: {report.volatility*100:>8.2f}%") - - print(f"\n📈 交易统计:") - print(f"总交易次数: {report.total_trades:>8d}") - print(f"胜率: {report.win_rate*100:>8.2f}%") - print(f"盈亏比: {report.profit_factor:>8.2f}") - print(f"平均盈利: {report.avg_win:>8.2f}") - print(f"平均亏损: {report.avg_loss:>8.2f}") - - if report.yearly_stats: - print(f"\n📅 年度统计:") - print(f"{'年份':>6} {'收益率':>10} {'最大回撤':>10} {'夏普比率':>10} {'交易次数':>8}") - print("-" * 60) - - for stats in report.yearly_stats: - print(f"{stats.year:>6d} " - f"{stats.return_rate*100:>9.2f}% " - f"{stats.max_drawdown*100:>9.2f}% " - f"{stats.sharpe_ratio:>9.2f} " - f"{stats.trades_count:>8d}") - - print("="*60) diff --git a/src/back_trader/real_backtest_demo.py b/src/back_trader/real_backtest_demo.py deleted file mode 100644 index 0587003..0000000 --- a/src/back_trader/real_backtest_demo.py +++ /dev/null @@ -1,715 +0,0 @@ -""" -真实数据库回测脚本 - -使用真实数据库数据对300339.SZ进行回测 -回测期间:2025年3月1日 - 2025年7月31日 -使用修改后的多时间周期MA评分策略 -""" - -import sys -import os -import logging -from datetime import datetime -import pandas as pd -import matplotlib.pyplot as plt -import matplotlib.dates as mdates -from matplotlib.patches import FancyBboxPatch -import numpy as np -import glob - -# 添加项目路径 -current_dir = os.path.dirname(os.path.abspath(__file__)) -src_dir = os.path.dirname(current_dir) -sys.path.insert(0, src_dir) -data_process_model_dir = os.path.join(src_dir, 'data_process_model') -sys.path.insert(0, data_process_model_dir) - -# 配置日志 -logging.basicConfig( - level=logging.INFO, - format='%(asctime)s - %(levelname)s - %(message)s', - handlers=[ - logging.StreamHandler(), - logging.FileHandler('real_backtest.log', encoding='utf-8') - ] -) - -logger = logging.getLogger(__name__) - - -def draw_kline_chart(engine, strategy, stock_code, save_path=None): - """ - 绘制K线图,包含MA5、MA18均线和买卖点标注 - X轴使用连续索引,避免非交易日的空白 - - Args: - engine: 回测引擎 - strategy: 交易策略 - stock_code: 股票代码 - save_path: 图片保存路径,默认为None表示显示而不保存 - """ - try: - print("\n🎨 绘制K线图...") - - # 设置中文字体 - plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei'] - plt.rcParams['axes.unicode_minus'] = False - - # 获取日线数据 - from data_process_model.stock_models import create_stock_kline_model - from data_process_model.database_config import init_database, close_database - - init_database() - daily_model = create_stock_kline_model(stock_code, "1d") - - # 查询回测期间的日线数据 - start_date = engine.start_date.date() - end_date = engine.end_date.date() - - daily_data = daily_model.select().where( - (daily_model.timestamp >= start_date) & - (daily_model.timestamp <= end_date) - ).order_by(daily_model.timestamp) - - # 转换为DataFrame - df_data = [] - for record in daily_data: - df_data.append({ - 'date': record.timestamp, - 'open': record.open, - 'high': record.high, - 'low': record.low, - 'close': record.close, - 'volume': record.volume - }) - - close_database() - - if not df_data: - print("❌ 没有找到日线数据") - return - - df = pd.DataFrame(df_data) - df['date'] = pd.to_datetime(df['date']) - - # 将Decimal类型的价格数据转换为float,避免类型混合运算错误 - numeric_cols = ['open', 'high', 'low', 'close'] - for col in numeric_cols: - df[col] = pd.to_numeric(df[col], errors='coerce') - - # 创建连续的索引,避免非交易日的空白 - df['index'] = range(len(df)) - - # 计算MA5和MA18 - df['ma5'] = df['close'].rolling(window=5).mean() - df['ma18'] = df['close'].rolling(window=18).mean() - - # 获取交易记录 - trades = engine.portfolio.trades - buy_trades = [] - sell_trades = [] - - for trade in trades: - if hasattr(trade, 'timestamp') and trade.timestamp: - trade_date = trade.timestamp.date() - # 查找对应的索引 - matching_rows = df[df['date'].dt.date == trade_date] - if not matching_rows.empty: - index = matching_rows.iloc[0]['index'] - if trade.action in ['BUY', 'BUY_ALL']: - buy_trades.append({'index': index, 'date': trade_date, 'price': trade.price}) - elif trade.action in ['SELL', 'SELL_ALL']: - sell_trades.append({'index': index, 'date': trade_date, 'price': trade.price}) - - # 创建图形 - fig, ax = plt.subplots(figsize=(16, 10)) - - # 绘制K线 - 使用索引作为X轴 - for i, row in df.iterrows(): - x_pos = row['index'] - open_price = row['open'] - high_price = row['high'] - low_price = row['low'] - close_price = row['close'] - - # 确定K线颜色(红涨绿跌) - color = 'red' if close_price >= open_price else 'green' - edge_color = 'red' if close_price >= open_price else 'green' - face_color = 'white' if close_price >= open_price else 'green' - - # 绘制影线 - ax.plot([x_pos, x_pos], [low_price, high_price], color='black', linewidth=0.8) - - # 绘制实体 - body_height = abs(close_price - open_price) - if body_height > 0: - body_bottom = min(open_price, close_price) - rect = plt.Rectangle((x_pos - 0.3, body_bottom), - 0.6, body_height, - facecolor=face_color, edgecolor=edge_color, linewidth=0.8) - ax.add_patch(rect) - else: - # 十字星 - ax.plot([x_pos - 0.3, x_pos + 0.3], - [close_price, close_price], color='black', linewidth=1) - - # 绘制MA5和MA18 - 使用索引作为X轴 - valid_ma5_mask = ~df['ma5'].isna() - if valid_ma5_mask.any(): - ma5_x = df.loc[valid_ma5_mask, 'index'] - ma5_y = df.loc[valid_ma5_mask, 'ma5'] - ax.plot(ma5_x, ma5_y, label='MA5', color='blue', linewidth=1.5, alpha=0.8) - - valid_ma18_mask = ~df['ma18'].isna() - if valid_ma18_mask.any(): - ma18_x = df.loc[valid_ma18_mask, 'index'] - ma18_y = df.loc[valid_ma18_mask, 'ma18'] - ax.plot(ma18_x, ma18_y, label='MA18', color='orange', linewidth=1.5, alpha=0.8) - - # 标注买卖点 - 使用索引位置 - for i, trade in enumerate(buy_trades): - x_pos = trade['index'] - # 获取对应K线的高价 - row = df[df['index'] == x_pos].iloc[0] - bar_high = row['high'] - - # 添加图例标记(仅第一个点) - if i == 0: - ax.scatter([], [], color='red', s=0, marker='s', label='买入', alpha=0) - - # 价格标注框位置在K线上方 - text_y_offset = (ax.get_ylim()[1] - ax.get_ylim()[0]) * 0.08 # 相对于价格范围的8% - - # 标注买入价格,箭头指向K线 - ax.annotate(f'买入: {trade["price"]:.2f}', - xy=(x_pos, bar_high), # 箭头指向K线最高点 - xytext=(x_pos, bar_high + text_y_offset), # 文字框位置 - fontsize=9, ha='center', va='bottom', color='red', weight='bold', - bbox=dict(boxstyle='round,pad=0.3', facecolor='white', - edgecolor='red', alpha=0.95, linewidth=1.5), - arrowprops=dict(arrowstyle='->', lw=1.2, color='red', alpha=0.8)) - - for i, trade in enumerate(sell_trades): - x_pos = trade['index'] - # 获取对应K线的低价 - row = df[df['index'] == x_pos].iloc[0] - bar_low = row['low'] - - # 添加图例标记(仅第一个点) - if i == 0: - ax.scatter([], [], color='green', s=0, marker='s', label='卖出', alpha=0) - - # 价格标注框位置在K线下方 - text_y_offset = (ax.get_ylim()[1] - ax.get_ylim()[0]) * 0.08 # 相对于价格范围的8% - - # 标注卖出价格,箭头指向K线 - ax.annotate(f'卖出: {trade["price"]:.2f}', - xy=(x_pos, bar_low), # 箭头指向K线最低点 - xytext=(x_pos, bar_low - text_y_offset), # 文字框位置 - fontsize=9, ha='center', va='top', color='green', weight='bold', - bbox=dict(boxstyle='round,pad=0.3', facecolor='white', - edgecolor='green', alpha=0.95, linewidth=1.5), - arrowprops=dict(arrowstyle='->', lw=1.2, color='green', alpha=0.8)) - - # 设置图形属性 - ax.set_title(f'{stock_code}日线K线图 - 多时间周期MA策略回测\n' - f'回测期间: {start_date} ~ {end_date}', fontsize=16, pad=20) - ax.set_xlabel('交易日期', fontsize=12) - ax.set_ylabel('价格 (元)', fontsize=12) - - # 设置X轴刻度 - 显示实际日期但使用连续索引 - # 每隔一定间隔显示日期 - n_ticks = min(10, len(df)) # 最多显示10个日期刻度 - if len(df) > 0: - step = max(1, len(df) // n_ticks) - tick_positions = range(0, len(df), step) - tick_labels = [df.iloc[i]['date'].strftime('%m-%d') for i in tick_positions if i < len(df)] - - ax.set_xticks(tick_positions) - ax.set_xticklabels(tick_labels, rotation=45) - - # 设置X轴范围 - ax.set_xlim(-1, len(df)) - - # 添加网格 - ax.grid(True, alpha=0.3) - - # 添加图例 - ax.legend(loc='upper left', fontsize=10) - - # 紧凑布局 - plt.tight_layout() - - # 保存或显示 - if save_path: - # 清理同名的旧图片 - if os.path.exists(save_path): - os.remove(save_path) - plt.savefig(save_path, dpi=300, bbox_inches='tight') - print(f"✅ K线图已保存到: {save_path}") - else: - # 获取当前脚本所在目录(back_trader目录) - script_dir = os.path.dirname(os.path.abspath(__file__)) - - # 清理旧的K线图文件 - pattern = os.path.join(script_dir, f"kline_chart_{stock_code}_*.png") - old_files = glob.glob(pattern) - for old_file in old_files: - try: - os.remove(old_file) - except: - pass # 忽略删除失败的情况 - - # 生成默认文件名,保存到back_trader目录 - timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') - filename = os.path.join(script_dir, f"kline_chart_{stock_code}_{timestamp}.png") - plt.savefig(filename, dpi=300, bbox_inches='tight') - print(f"✅ K线图已保存到: {filename}") - - # plt.show() # 注释掉显示,只保存文件 - - except Exception as e: - print(f"❌ K线图绘制失败: {e}") - import traceback - traceback.print_exc() - finally: - plt.close('all') # 关闭所有图形 - - -def progress_callback(current, total, message): - """进度回调函数 - 每5%输出一次""" - progress = (current / total) * 100 - - # 每5%输出一次,或者在开始和结束时输出 - if current == 1 or current == total or progress % 5 < (100 / total): - print(f"进度: {progress:.1f}% - {message}") - - # 结束时换行 - if current == total: - print("回测进度完成!") - - -def run_real_backtest(): - """运行真实数据库回测""" - try: - print("🚀 启动真实数据库回测") - print("="*60) - print("📊 测试股票: 300339.SZ") - print("📅 回测期间: 2025-01-01 ~ 2025-07-31") - print("🎯 策略: 多时间周期MA评分策略(修正版)") - print("="*60) - - # 回测配置参数 - # ===================================== - STOCK_CODE = "300339.SZ" # 股票代码 - INITIAL_CAPITAL = 100000 # 初始资金 - START_DATE = "2025-03-01 09:00" # 回测开始时间 - END_DATE = "2025-07-31 15:00" # 回测结束时间 - - # 止盈设置说明: - # None - 不设置止盈(默认) - # 0.03 - 3%止盈 - # 0.05 - 5%止盈 - # 0.08 - 8%止盈 - # 0.10 - 10%止盈 - PROFIT_TARGET = None # 止盈阈值(默认无止盈) - - # 买入条件系数说明: - # 股价 > buy_low_ratio * 日K5日均线 时可买入 - # 0.95 - 95%日K5日线 - # 0.99 - 99%日K5日线(默认) - # 1.00 - 100%日K5日线(原策略) - # 1.02 - 102%日K5日线 - BUY_LOW_RATIO = 0.99 # 买入条件系数(默认0.99) - # ===================================== - - # 1. 检查数据库连接 - print("\n1️⃣ 检查数据库连接...") - try: - from data_process_model.database_config import init_database, close_database - if not init_database(): - print("❌ 数据库连接失败,请检查配置") - return False - print("✅ 数据库连接成功") - except Exception as e: - print(f"❌ 数据库模块导入失败: {e}") - return False - - # 2. 导入回测引擎 - print("\n2️⃣ 导入回测引擎...") - try: - # 添加当前目录到Python路径 - current_back_trader_dir = os.path.dirname(os.path.abspath(__file__)) - sys.path.insert(0, current_back_trader_dir) - - from backtest_engine import BacktestEngine - from multi_timeframe_ma_backtest_strategy import MultiTimeframeMABacktestStrategy - print("✅ 回测引擎和回测专用策略导入成功") - except Exception as e: - print(f"❌ 回测引擎导入失败: {e}") - return False - - # 3. 创建回测引擎 - print("\n3️⃣ 创建回测引擎...") - engine = BacktestEngine(initial_capital=INITIAL_CAPITAL) - print(f"✅ 回测引擎创建成功,初始资金: {INITIAL_CAPITAL:,.2f} 元") - - # 4. 设置回测参数 - print("\n4️⃣ 设置回测参数...") - engine.set_universe([STOCK_CODE]) - engine.set_period(START_DATE.split()[0], END_DATE.split()[0], "1m") - print(f"✅ 股票池: ['{STOCK_CODE}']") - print(f"✅ 回测期间: {START_DATE.split()[0]} ~ {END_DATE.split()[0]}") - print(f"✅ 数据周期: 分钟线(1m)") - - # 5. 创建多时间周期MA回测策略 - print("\n5️⃣ 创建交易策略...") - # 使用配置的参数:止盈和买入条件系数 - strategy = MultiTimeframeMABacktestStrategy( - stock_code=STOCK_CODE, - profit_target=PROFIT_TARGET, - buy_low_ratio=BUY_LOW_RATIO - ) - engine.set_strategy(strategy) - - print(f"✅ 策略创建成功: {strategy.name}") - print(f" 信号时间周期: {strategy.signal_timeframes}") - print(f" MA周期: {strategy.ma_periods}") - print(f" 交易模式: 全仓买入 + 条件清仓") - - # 初始化策略 - if not strategy.initialize(): - print("❌ 策略初始化失败") - return False - - print("✅ 策略初始化成功") - - print("✅ 策略配置:") - print(f" - 策略名称: 多时间周期MA回测策略(最新优化版)") - print(f" - 移动平均线: MA5 和 MA18") - print(f" - 交叉判定: 无阈值限制(只要发生交叉就产生信号)") - print(f" - 买入检查: 每5分钟一次") - print(f" - 卖出检查: 每15分钟一次") - print(f" - 评分与交易规则:") - print(f" * 起始分数: 0分") - print(f" * 15/30/60分钟金叉: +1分,死叉: -1分(分数最低为0)") - print(f" * 买入条件: 15分钟持续金叉且股价>日K5日线且分数>0时全仓买入") - print(f" * 卖出条件: 分数≤0时清仓卖出") - print(f" * T+1限制: 当天买入的股票不能卖出") - if strategy.profit_target is not None: - print(f" * 止盈机制: 达到{strategy.profit_target*100:.1f}%止盈点时清仓并置0分") - else: - print(f" * 止盈机制: 无止盈设置") - print(f" - 📊 已启用信号记录功能") - - # 6. 加载历史数据 - print("\n6️⃣ 从数据库加载历史数据...") - if not engine.load_data_from_database(): - print("❌ 历史数据加载失败") - print(" 请确认:") - print(" - 数据库中存在对应的股票数据表") - print(" - 数据时间范围覆盖回测期间") - print(" - 股票代码格式正确(300339.SZ)") - return False - - print("✅ 历史数据加载成功") - - # 7. 执行回测 - print("\n7️⃣ 开始执行回测...") - print(" (这可能需要几分钟时间,请耐心等待)") - - # 临时调整日志级别,屏蔽详细日志,只显示进度 - import logging - original_levels = {} - loggers_to_silence = [ - 'src.back_trader.backtest_engine', - 'src.back_trader.multi_timeframe_ma_backtest_strategy', - 'data_process_model.database_config', - 'data_process_model.stock_models', - 'peewee' # 数据库ORM日志 - ] - - for logger_name in loggers_to_silence: - logger = logging.getLogger(logger_name) - original_levels[logger_name] = logger.level - logger.setLevel(logging.CRITICAL) # 只显示严重错误 - - # 设置根日志级别 - root_logger = logging.getLogger() - original_root_level = root_logger.level - root_logger.setLevel(logging.CRITICAL) - - start_time = datetime.now() - success = engine.run_backtest(progress_callback) - end_time = datetime.now() - - # 恢复原来的日志级别 - for logger_name, original_level in original_levels.items(): - logging.getLogger(logger_name).setLevel(original_level) - root_logger.setLevel(original_root_level) - - duration = (end_time - start_time).total_seconds() - - if success: - print(f"\n✅ 回测执行成功 (耗时: {duration:.1f}秒)") - - # 8. 显示回测结果 - print("\n8️⃣ 回测结果分析:") - print("="*60) - engine.print_summary() - - # 9. 保存详细结果 (暂时禁用JSON输出) - # print("\n9️⃣ 保存回测结果...") - # result_file = f"backtest_601288_SH_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json" - # if engine.save_results(result_file): - # print(f"✅ 详细结果已保存到: {result_file}") - - # 9. 显示投资组合最终状态 - print("\n9️⃣ 投资组合最终状态:") - print(f" 现金余额: {engine.portfolio.cash:,.2f} 元") - print(f" 总资产: {engine.portfolio.total_value:,.2f} 元") - total_return = ((engine.portfolio.total_value - 100000) / 100000) * 100 - print(f" 总收益率: {total_return:.2f}%") - print(f" 持仓情况:") - - if engine.portfolio.positions: - for stock_code, position in engine.portfolio.positions.items(): - if position.shares > 0: - print(f" {stock_code}: {position.shares}股, 市值: {position.market_value:,.2f}元") - else: - print(" 无持仓") - - # 显示策略分数 - if hasattr(strategy, 'stock_scores') and strategy.stock_scores: - print(f"\n🎯 策略分数状态:") - for stock_code, score in strategy.stock_scores.items(): - print(f" {stock_code}: {score}分") - - # 显示金叉/死叉信号统计 - if hasattr(strategy, 'get_signal_statistics'): - stats = strategy.get_signal_statistics() - print(f"\n📊 金叉/死叉信号统计:") - print(f"="*40) - - print(f"📈 总信号数量: {stats['total_signals']}个") - - # 按时间周期显示统计 - timeframe_stats = stats['timeframe_stats'] - for timeframe, counts in timeframe_stats.items(): - print(f"\n⏰ {timeframe} 级别:") - print(f" 🟢 金叉: {counts['golden_cross']}次") - print(f" 🔴 死叉: {counts['death_cross']}次") - - # 显示当前分数 - current_scores = stats['current_scores'] - print(f"\n🎯 当前策略分数:") - for stock_code, score in current_scores.items(): - print(f" {stock_code}: {score}分") - - # 显示最近信号记录 - recent_signals = stats['recent_signals'] - if recent_signals: - print(f"\n📋 金叉/死叉信号记录:") - print("="*120) - print(f"{'序号':<4} {'日期时间':<19} {'时间框架':<8} {'信号类型':<12} {'MA5':<10} {'MA18':<10} {'差值(元)':<10} {'价格':<10} {'分数变化':<10}") - print("-" * 120) - - for idx, signal in enumerate(recent_signals, 1): - timestamp = signal['timestamp'].strftime('%Y-%m-%d %H:%M:%S') - timeframe = signal['timeframe'] - signal_type = signal['signal_type'] - ma5 = f"{signal['ma5']:.4f}" - ma18 = f"{signal['ma18']:.4f}" - price = f"{signal['close_price']:.4f}" - diff_abs = f"{signal.get('diff_abs', 0):.4f}" - - signal_icon = "🟢" if signal_type == "golden_cross" else "🔴" - signal_text = "金叉" if signal_type == "golden_cross" else "死叉" - score_change = "+1" if signal_type == "golden_cross" else "-1" - - print(f"{idx:<4} {timestamp:<19} {timeframe:<8} {signal_icon}{signal_text:<11} {ma5:<10} {ma18:<10} {diff_abs:<10} {price:<10} {score_change:<10}") - - print("="*120) - - # 交易记录统计 - trades = engine.portfolio.trades - if trades: - buy_trades = [t for t in trades if t.action in ['BUY', 'BUY_ALL']] - sell_trades = [t for t in trades if t.action in ['SELL', 'SELL_ALL']] - print(f"\n📈 交易记录统计:") - print("="*80) - print(f" 总交易次数: {len(trades)}笔") - print(f" 买入交易: {len(buy_trades)}笔") - print(f" 卖出交易: {len(sell_trades)}笔") - - if trades: - try: - total_commission = sum(getattr(t, 'commission', 0) or 0 for t in trades) - print(f" 总手续费: {total_commission:,.2f}元") - except Exception as e: - print(f" 总手续费: 计算错误 - {e}") - - # 详细交易记录 - if len(trades) > 0: - print(f"\n💰 详细交易记录:") - print("="*120) - print(f"{'序号':<4} {'日期时间':<19} {'操作':<8} {'股票代码':<12} {'股数':<10} {'价格':<10} {'金额':<15} {'手续费':<10} {'原因':<20}") - print("-" * 120) - - for idx, trade in enumerate(trades, 1): - try: - timestamp = trade.timestamp.strftime('%Y-%m-%d %H:%M:%S') if hasattr(trade, 'timestamp') and trade.timestamp else "未知时间" - - # 根据操作类型设置显示文本 - if trade.action == 'BUY_ALL': - action = "全仓买入" - elif trade.action == 'BUY': - action = "普通买入" - elif trade.action == 'SELL_ALL': - action = "全仓卖出" - elif trade.action == 'SELL': - action = "普通卖出" - else: - action = trade.action - - stock_code = getattr(trade, 'stock_code', '未知') - shares = f"{trade.shares:,}" if hasattr(trade, 'shares') and trade.shares is not None else "0" - price = f"{trade.price:.4f}" if hasattr(trade, 'price') and trade.price is not None else "市价" - - # 计算金额:优先使用total_amount,其次是amount,最后计算 - if hasattr(trade, 'total_amount') and trade.total_amount is not None: - amount = f"{trade.total_amount:,.2f}" - elif hasattr(trade, 'amount') and trade.amount is not None: - amount = f"{trade.amount:,.2f}" - elif hasattr(trade, 'shares') and hasattr(trade, 'price') and trade.shares and trade.price: - calculated_amount = trade.shares * trade.price - amount = f"{calculated_amount:,.2f}" - else: - amount = "0.00" - - commission = f"{trade.commission:.2f}" if hasattr(trade, 'commission') and trade.commission is not None else "0.00" - reason = getattr(trade, 'reason', '策略信号') - - action_icon = "🟢" if trade.action in ['BUY', 'BUY_ALL'] else "🔴" - print(f"{idx:<4} {timestamp:<19} {action_icon}{action:<7} {stock_code:<12} {shares:<10} {price:<10} {amount:<15} {commission:<10} {reason:<20}") - except Exception as e: - print(f"{idx:<4} {'错误':<19} {'--':<8} {'数据异常':<12} {'--':<10} {'--':<10} {'--':<15} {'--':<10} {str(e):<20}") - - print("="*120) - - # 10. 绘制K线图 - print("\n🔟 绘制K线图...") - try: - # 直接使用已知的股票代码 - target_stock = STOCK_CODE # 使用配置的股票代码 - draw_kline_chart(engine, strategy, target_stock) - except Exception as e: - print(f"❌ K线图绘制过程出错: {e}") - - return True - - else: - print(f"\n❌ 回测执行失败 (耗时: {duration:.1f}秒)") - return False - - except Exception as e: - print(f"\n❌ 回测过程出错: {e}") - logger.error(f"回测异常: {e}", exc_info=True) - import traceback - traceback.print_exc() - return False - finally: - # 确保关闭数据库连接 - try: - close_database() - print("\n🔚 数据库连接已关闭") - except: - pass - - -def check_data_availability(): - """检查数据可用性""" - try: - print("🔍 检查数据可用性...") - - from data_process_model.database_config import init_database, close_database - from data_process_model.stock_models import create_stock_kline_model - - if not init_database(): - print("❌ 无法连接数据库") - return False - - # 检查是否存在配置股票的分钟数据 - stock_code = "300339.SZ" # 配置的股票代码 - try: - model_class = create_stock_kline_model(stock_code, "1m") - - # 检查表是否存在数据 - count = model_class.select().count() - print(f"✅ 找到 {stock_code} 分钟数据: {count} 条记录") - - if count == 0: - print("⚠️ 数据表为空,请先运行数据下载脚本") - return False - - # 对分钟数据,检查是否有足够的数据进行回测 - if count < 10000: # 至少需要1万条分钟数据 - print("⚠️ 分钟数据不足,请检查数据") - return False - - # 检查时间范围 - first_record = model_class.select().order_by(model_class.timestamp).first() - last_record = model_class.select().order_by(model_class.timestamp.desc()).first() - - if first_record and last_record: - print(f"📅 数据时间范围: {first_record.timestamp} ~ {last_record.timestamp}") - - # 检查时间范围 - from datetime import datetime - backtest_start = datetime(2025, 1, 1) - backtest_end = datetime(2025, 7, 31) - - if first_record.timestamp <= backtest_start and last_record.timestamp >= backtest_end: - print("✅ 数据时间范围覆盖回测期间") - return True - else: - print("⚠️ 数据时间范围不完全覆盖回测期间") - print(" 但继续进行回测") - return True - - except Exception as e: - print(f"❌ 检查数据时出错: {e}") - return False - finally: - close_database() - - except Exception as e: - print(f"❌ 数据检查失败: {e}") - return False - - -def main(): - """主函数""" - print("📈 300339.SZ真实数据回测") - print("="*60) - - # 首先检查数据可用性 - if not check_data_availability(): - print("\n💡 建议操作:") - print("1. 确认已运行数据下载脚本 (data_process_model/main.py)") - print("2. 确认数据库中存在 300339.SZ 的历史数据") - print("3. 确认数据时间范围覆盖 2025年1-7月") - return - - # 执行回测 - success = run_real_backtest() - - if success: - print("\n🎉 回测完成!") - # print(" 可以查看生成的 JSON 文件获取详细结果") # 暂时禁用JSON输出提示 - else: - print("\n😞 回测失败,请检查错误信息") - - -if __name__ == "__main__": - main() diff --git a/src/back_trader/simple_backtest_engine.py b/src/back_trader/simple_backtest_engine.py deleted file mode 100644 index e69de29..0000000 diff --git a/src/back_trader/strategy_base.py b/src/back_trader/strategy_base.py deleted file mode 100644 index 1c832ae..0000000 --- a/src/back_trader/strategy_base.py +++ /dev/null @@ -1,221 +0,0 @@ -""" -策略基类模块 - -定义所有交易策略的基础接口和通用功能 -""" - -from abc import ABC, abstractmethod -from typing import Dict, Any, Optional, List -from dataclasses import dataclass -from datetime import datetime -import pandas as pd -import logging - -logger = logging.getLogger(__name__) - - -@dataclass -class Position: - """持仓信息""" - stock_code: str - shares: int # 持股数量,正数为多头,负数为空头 - avg_price: float # 平均成本价 - market_value: float = 0.0 # 市值 - unrealized_pnl: float = 0.0 # 浮动盈亏 - - def update_market_value(self, current_price: float): - """更新市值和浮动盈亏""" - self.market_value = self.shares * current_price - self.unrealized_pnl = (current_price - self.avg_price) * self.shares - - -@dataclass -class Trade: - """交易记录""" - timestamp: datetime - stock_code: str - action: str # 'BUY' 或 'SELL' - shares: int - price: float - commission: float = 0.0 - total_amount: float = 0.0 - - def __post_init__(self): - """计算总金额""" - if self.total_amount == 0.0: - self.total_amount = self.shares * self.price + self.commission - - -@dataclass -class Signal: - """交易信号""" - timestamp: datetime - stock_code: str - action: str # 'BUY', 'SELL', 'SELL_ALL', 'HOLD' - strength: float = 1.0 # 信号强度,0-1之间 - reason: str = "" # 信号原因 - amount: Optional[float] = None # 交易金额(用于固定金额交易) - price: Optional[float] = None # 目标价格(None表示市价) - - -class Portfolio: - """投资组合管理器""" - - def __init__(self, initial_capital: float = 1000000.0): - self.initial_capital = initial_capital - self.cash = initial_capital - self.positions: Dict[str, Position] = {} - self.trades: List[Trade] = [] - self.total_value = initial_capital - self.commission_rate = 0.0003 # 默认手续费率0.03% - - def get_position(self, stock_code: str) -> Optional[Position]: - """获取持仓信息""" - return self.positions.get(stock_code) - - def update_market_values(self, prices: Dict[str, float]): - """更新所有持仓的市值""" - total_market_value = 0.0 - for stock_code, position in self.positions.items(): - if stock_code in prices: - position.update_market_value(prices[stock_code]) - total_market_value += position.market_value - - self.total_value = self.cash + total_market_value - - def execute_trade(self, timestamp: datetime, stock_code: str, - action: str, shares: int, price: float) -> bool: - """执行交易""" - try: - commission = shares * price * self.commission_rate - total_cost = shares * price + commission - - if action == 'BUY': - if self.cash < total_cost: - logger.warning(f"资金不足,无法买入 {stock_code}") - return False - - # 更新现金 - self.cash -= total_cost - - # 更新持仓 - if stock_code in self.positions: - pos = self.positions[stock_code] - total_shares = pos.shares + shares - total_cost_basis = pos.shares * pos.avg_price + shares * price - pos.avg_price = total_cost_basis / total_shares - pos.shares = total_shares - else: - self.positions[stock_code] = Position( - stock_code=stock_code, - shares=shares, - avg_price=price - ) - - elif action == 'SELL': - if stock_code not in self.positions or self.positions[stock_code].shares < shares: - logger.warning(f"持仓不足,无法卖出 {stock_code}") - return False - - # 更新现金 - self.cash += shares * price - commission - - # 更新持仓 - pos = self.positions[stock_code] - pos.shares -= shares - if pos.shares == 0: - del self.positions[stock_code] - - # 记录交易 - trade = Trade( - timestamp=timestamp, - stock_code=stock_code, - action=action, - shares=shares, - price=price, - commission=commission, - total_amount=total_cost if action == 'BUY' else shares * price - commission - ) - self.trades.append(trade) - - logger.info(f"交易执行: {action} {stock_code} {shares}股 @ {price:.2f}") - return True - - except Exception as e: - logger.error(f"交易执行失败: {e}") - return False - - def get_total_value(self) -> float: - """获取总资产价值""" - return self.total_value - - def get_return_rate(self) -> float: - """获取总收益率""" - return (self.total_value - self.initial_capital) / self.initial_capital - - -class StrategyBase(ABC): - """ - 交易策略基类 - - 所有具体策略都应该继承此类并实现抽象方法 - """ - - def __init__(self, name: str, params: Optional[Dict[str, Any]] = None): - self.name = name - self.params = params or {} - self.portfolio = Portfolio() - self.current_data: Optional[pd.DataFrame] = None - self.signals: List[Signal] = [] - - def set_portfolio(self, portfolio: Portfolio): - """设置投资组合""" - self.portfolio = portfolio - - @abstractmethod - def initialize(self): - """ - 策略初始化 - 在回测开始前调用,用于设置策略参数和初始状态 - """ - pass - - @abstractmethod - def on_data(self, data: pd.DataFrame, timestamp: datetime): - """ - 数据处理回调 - - Args: - data: 当前K线数据,包含OHLCV等字段 - timestamp: 当前时间戳 - """ - pass - - def generate_signal(self, timestamp: datetime, stock_code: str, - action: str, strength: float = 1.0, reason: str = "") -> Signal: - """生成交易信号""" - signal = Signal( - timestamp=timestamp, - stock_code=stock_code, - action=action, - strength=strength, - reason=reason - ) - self.signals.append(signal) - return signal - - def get_parameter(self, key: str, default_value: Any = None): - """获取策略参数""" - return self.params.get(key, default_value) - - def log_info(self, message: str): - """记录信息日志""" - logger.info(f"[{self.name}] {message}") - - def log_warning(self, message: str): - """记录警告日志""" - logger.warning(f"[{self.name}] {message}") - - def log_error(self, message: str): - """记录错误日志""" - logger.error(f"[{self.name}] {message}") diff --git a/src/core/__init__.py b/src/core/__init__.py new file mode 100644 index 0000000..b68fea1 --- /dev/null +++ b/src/core/__init__.py @@ -0,0 +1,15 @@ +""" +QTrade Core Module + +核心模块,提供所有服务共用的基础功能: +- 配置管理 (config) +- Redis 客户端 (redis_client) +- 数据库连接 (database) +- 日志模块 (logger) +- 数据模型 (models) +""" + +from .config import settings +from .logger import get_logger + +__all__ = ["settings", "get_logger"] diff --git a/src/core/config.py b/src/core/config.py new file mode 100644 index 0000000..642a8a7 --- /dev/null +++ b/src/core/config.py @@ -0,0 +1,294 @@ +""" +QTrade 配置管理模块 + +使用 Pydantic Settings 进行配置管理,支持: +- YAML 配置文件 +- 环境变量覆盖 +- 配置验证 +""" + +import os +from pathlib import Path +from typing import Any + +import yaml +from pydantic import BaseModel, Field +from pydantic_settings import BaseSettings, SettingsConfigDict + + +def get_project_root() -> Path: + """获取项目根目录""" + # 从当前文件向上查找,找到包含 configs 目录的位置 + current = Path(__file__).resolve() + for parent in [current] + list(current.parents): + if (parent / "configs").is_dir(): + return parent + # 如果找不到,返回当前工作目录 + return Path.cwd() + + +def load_yaml_config(config_path: Path) -> dict[str, Any]: + """加载 YAML 配置文件""" + if not config_path.exists(): + return {} + with open(config_path, "r", encoding="utf-8") as f: + return yaml.safe_load(f) or {} + + +# ========== 使用 BaseModel 定义嵌套配置 ========== + + +class RedisConfig(BaseModel): + """Redis 配置""" + + host: str = "127.0.0.1" + port: int = 6379 + password: str = "" + db: int = 0 + pool_size: int = 10 + pool_timeout: int = 30 + + @property + def url(self) -> str: + """生成 Redis URL""" + auth = f":{self.password}@" if self.password else "" + return f"redis://{auth}{self.host}:{self.port}/{self.db}" + + +class DatabaseConfig(BaseModel): + """数据库配置""" + + host: str = "127.0.0.1" + port: int = 3306 + user: str = "root" + password: str = "" + database: str = "qtrade" + pool_size: int = 5 + pool_recycle: int = 3600 + echo: bool = False + + @property + def url(self) -> str: + """生成数据库 URL (异步)""" + return ( + f"mysql+aiomysql://{self.user}:{self.password}@" + f"{self.host}:{self.port}/{self.database}?charset=utf8mb4" + ) + + @property + def sync_url(self) -> str: + """生成数据库 URL (同步,用于迁移)""" + return ( + f"mysql+pymysql://{self.user}:{self.password}@" + f"{self.host}:{self.port}/{self.database}?charset=utf8mb4" + ) + + +class ServiceConfig(BaseModel): + """单个服务配置""" + + host: str = "0.0.0.0" + port: int + + +class ServicesConfig(BaseModel): + """所有服务配置""" + + gateway: ServiceConfig = ServiceConfig(port=8001) + core_service: ServiceConfig = ServiceConfig(port=8010) + data_service: ServiceConfig = ServiceConfig(port=8020) + strategy_engine: ServiceConfig = ServiceConfig(port=8030) + + +class LoggingFileConfig(BaseModel): + """日志文件配置""" + + enabled: bool = True + path: str = "logs" + max_size: int = 10485760 # 10MB + backup_count: int = 5 + + +class LoggingConfig(BaseModel): + """日志配置""" + + level: str = "INFO" + format: str = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + file: LoggingFileConfig = LoggingFileConfig() + + +class MarketConfig(BaseModel): + """行情配置""" + + kline_periods: list[str] = ["1m", "5m", "15m", "30m", "60m", "1d", "1w"] + cache_ttl: int = 60 + + +class TradingSessionConfig(BaseModel): + """交易时段配置""" + + start: str + end: str + + +class TradingSessionsConfig(BaseModel): + """交易时段集合""" + + morning: TradingSessionConfig = TradingSessionConfig(start="09:30", end="11:30") + afternoon: TradingSessionConfig = TradingSessionConfig(start="13:00", end="15:00") + + +class RiskConfig(BaseModel): + """风控配置""" + + max_position_ratio: float = 0.3 + max_order_value: float = 1000000 + + +class TradingConfig(BaseModel): + """交易配置""" + + sessions: TradingSessionsConfig = TradingSessionsConfig() + risk: RiskConfig = RiskConfig() + + +class AppConfig(BaseModel): + """应用配置""" + + name: str = "QTrade" + version: str = "2.0.0" + env: str = "development" + debug: bool = True + + @property + def is_production(self) -> bool: + return self.env == "production" + + +# ========== 主配置类 ========== + + +class Settings(BaseSettings): + """ + 主配置类 + + 配置优先级(从高到低): + 1. 环境变量 + 2. YAML 配置文件 + 3. 默认值 + + 环境变量映射: + - QTRADE_ENV -> app.env + - REDIS_HOST -> redis.host + - DB_HOST -> database.host + - LOG_LEVEL -> logging.level + """ + + model_config = SettingsConfigDict( + env_file=".env", + env_file_encoding="utf-8", + extra="ignore", + ) + + # 嵌套配置 + app: AppConfig = AppConfig() + redis: RedisConfig = RedisConfig() + database: DatabaseConfig = DatabaseConfig() + services: ServicesConfig = ServicesConfig() + logging: LoggingConfig = LoggingConfig() + market: MarketConfig = MarketConfig() + trading: TradingConfig = TradingConfig() + + # 项目路径 + project_root: Path = Field(default_factory=get_project_root) + + def __init__(self, **kwargs): + # 先加载 YAML 配置 + yaml_config = _load_yaml_config() + + # 处理环境变量覆盖 + env_overrides = _get_env_overrides() + + # 合并配置: 默认值 < YAML < 环境变量 < kwargs + merged = _deep_merge(yaml_config, env_overrides) + merged = _deep_merge(merged, kwargs) + + super().__init__(**merged) + + @property + def logs_dir(self) -> Path: + """日志目录""" + logs_path = self.project_root / self.logging.file.path + logs_path.mkdir(parents=True, exist_ok=True) + return logs_path + + +def _load_yaml_config() -> dict[str, Any]: + """加载 YAML 配置""" + config_path = get_project_root() / "configs" / "settings.yaml" + return load_yaml_config(config_path) + + +def _get_env_overrides() -> dict[str, Any]: + """从环境变量获取配置覆盖""" + overrides: dict[str, Any] = {} + + # 应用环境 + if env := os.getenv("QTRADE_ENV"): + overrides.setdefault("app", {})["env"] = env + + # Redis + if host := os.getenv("REDIS_HOST"): + overrides.setdefault("redis", {})["host"] = host + if port := os.getenv("REDIS_PORT"): + overrides.setdefault("redis", {})["port"] = int(port) + if password := os.getenv("REDIS_PASSWORD"): + overrides.setdefault("redis", {})["password"] = password + if db := os.getenv("REDIS_DB"): + overrides.setdefault("redis", {})["db"] = int(db) + + # 数据库 + if host := os.getenv("DB_HOST"): + overrides.setdefault("database", {})["host"] = host + if port := os.getenv("DB_PORT"): + overrides.setdefault("database", {})["port"] = int(port) + if user := os.getenv("DB_USER"): + overrides.setdefault("database", {})["user"] = user + if password := os.getenv("DB_PASSWORD"): + overrides.setdefault("database", {})["password"] = password + if name := os.getenv("DB_NAME"): + overrides.setdefault("database", {})["database"] = name + + # 日志 + if level := os.getenv("LOG_LEVEL"): + overrides.setdefault("logging", {})["level"] = level + + return overrides + + +def _deep_merge(base: dict, override: dict) -> dict: + """深度合并字典""" + result = base.copy() + for key, value in override.items(): + if key in result and isinstance(result[key], dict) and isinstance(value, dict): + result[key] = _deep_merge(result[key], value) + else: + result[key] = value + return result + + +# 全局配置实例 +settings = Settings() + + +# 便捷访问 +def get_settings() -> Settings: + """获取配置实例""" + return settings + + +def reload_settings() -> Settings: + """重新加载配置""" + global settings + settings = Settings() + return settings diff --git a/src/core/database.py b/src/core/database.py new file mode 100644 index 0000000..33d35bc --- /dev/null +++ b/src/core/database.py @@ -0,0 +1,194 @@ +""" +QTrade 数据库模块 + +提供 SQLAlchemy 2.0 异步数据库操作: +- 异步会话管理 +- 连接池配置 +- 基础模型定义 +""" + +from contextlib import asynccontextmanager +from datetime import datetime +from typing import Any, AsyncIterator, Optional + +from sqlalchemy import MetaData, text +from sqlalchemy.ext.asyncio import ( + AsyncEngine, + AsyncSession, + async_sessionmaker, + create_async_engine, +) +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column + +from .config import settings +from .logger import get_logger + +logger = get_logger(__name__) + + +# 表命名规范 +convention = { + "ix": "ix_%(column_0_label)s", + "uq": "uq_%(table_name)s_%(column_0_name)s", + "ck": "ck_%(table_name)s_%(constraint_name)s", + "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", + "pk": "pk_%(table_name)s", +} + +metadata = MetaData(naming_convention=convention) + + +class Base(DeclarativeBase): + """ + ORM 基类 + + 所有数据模型继承此类 + """ + + metadata = metadata + + +class TimestampMixin: + """ + 时间戳混入类 + + 提供 created_at 和 updated_at 字段 + """ + + created_at: Mapped[datetime] = mapped_column( + default=datetime.now, + comment="创建时间", + ) + updated_at: Mapped[datetime] = mapped_column( + default=datetime.now, + onupdate=datetime.now, + comment="更新时间", + ) + + +class Database: + """ + 异步数据库管理器 + + 提供连接池管理和会话管理 + """ + + _instance: Optional["Database"] = None + _engine: Optional[AsyncEngine] = None + _session_factory: Optional[async_sessionmaker[AsyncSession]] = None + + def __new__(cls): + if cls._instance is None: + cls._instance = super().__new__(cls) + return cls._instance + + async def connect(self) -> None: + """建立数据库连接""" + if self._engine is not None: + return + + self._engine = create_async_engine( + settings.database.url, + pool_size=settings.database.pool_size, + pool_recycle=settings.database.pool_recycle, + echo=settings.database.echo, + pool_pre_ping=True, # 连接健康检查 + ) + + self._session_factory = async_sessionmaker( + bind=self._engine, + class_=AsyncSession, + expire_on_commit=False, + autoflush=False, + ) + + # 测试连接 + try: + async with self._engine.begin() as conn: + await conn.execute(text("SELECT 1")) + logger.info( + f"数据库连接成功: {settings.database.host}:{settings.database.port}" + f"/{settings.database.database}" + ) + except Exception as e: + logger.error(f"数据库连接失败: {e}") + raise + + async def disconnect(self) -> None: + """断开数据库连接""" + if self._engine: + await self._engine.dispose() + self._engine = None + self._session_factory = None + logger.info("数据库连接已断开") + + @property + def engine(self) -> AsyncEngine: + """获取数据库引擎""" + if self._engine is None: + raise RuntimeError("数据库未连接,请先调用 connect()") + return self._engine + + @property + def session_factory(self) -> async_sessionmaker[AsyncSession]: + """获取会话工厂""" + if self._session_factory is None: + raise RuntimeError("数据库未连接,请先调用 connect()") + return self._session_factory + + @asynccontextmanager + async def session(self) -> AsyncIterator[AsyncSession]: + """ + 获取数据库会话(上下文管理器) + + 使用方法: + async with db.session() as session: + result = await session.execute(select(User)) + """ + session = self.session_factory() + try: + yield session + await session.commit() + except Exception: + await session.rollback() + raise + finally: + await session.close() + + async def create_tables(self) -> None: + """创建所有表""" + async with self.engine.begin() as conn: + await conn.run_sync(Base.metadata.create_all) + logger.info("数据库表创建完成") + + async def drop_tables(self) -> None: + """删除所有表(危险操作,仅用于测试)""" + async with self.engine.begin() as conn: + await conn.run_sync(Base.metadata.drop_all) + logger.warning("数据库表已删除") + + +# 全局数据库实例 +db = Database() + + +# 便捷函数 +async def get_db() -> Database: + """获取数据库实例(确保已连接)""" + if db._engine is None: + await db.connect() + return db + + +async def get_session() -> AsyncIterator[AsyncSession]: + """ + 获取数据库会话(用于 FastAPI 依赖注入) + + 使用方法: + @app.get("/users") + async def get_users(session: AsyncSession = Depends(get_session)): + result = await session.execute(select(User)) + return result.scalars().all() + """ + async with db.session() as session: + yield session diff --git a/src/core/logger.py b/src/core/logger.py new file mode 100644 index 0000000..5c57c89 --- /dev/null +++ b/src/core/logger.py @@ -0,0 +1,109 @@ +""" +QTrade 日志模块 + +提供统一的日志配置: +- 控制台输出 +- 文件输出(按大小轮转) +- 自定义格式 +""" + +import logging +import sys +from logging.handlers import RotatingFileHandler +from pathlib import Path +from typing import Optional + +from .config import settings + + +def setup_logging( + name: Optional[str] = None, + level: Optional[str] = None, +) -> logging.Logger: + """ + 配置日志 + + Args: + name: 日志名称,为 None 时返回根日志 + level: 日志级别,为 None 时使用配置文件设置 + + Returns: + 配置好的 Logger 实例 + """ + # 获取日志配置 + log_level = level or settings.logging.level + log_format = settings.logging.format + + # 创建日志器 + logger = logging.getLogger(name) + + # 如果已经配置过,直接返回 + if logger.handlers: + return logger + + logger.setLevel(getattr(logging, log_level.upper())) + + # 创建格式化器 + formatter = logging.Formatter(log_format) + + # 控制台处理器 + console_handler = logging.StreamHandler(sys.stdout) + console_handler.setFormatter(formatter) + logger.addHandler(console_handler) + + # 文件处理器 + if settings.logging.file.enabled: + logs_dir = settings.logs_dir + log_file = logs_dir / f"{name or 'qtrade'}.log" + + file_handler = RotatingFileHandler( + log_file, + maxBytes=settings.logging.file.max_size, + backupCount=settings.logging.file.backup_count, + encoding="utf-8", + ) + file_handler.setFormatter(formatter) + logger.addHandler(file_handler) + + # 防止日志向上传递 + logger.propagate = False + + return logger + + +def get_logger(name: str) -> logging.Logger: + """ + 获取日志器 + + Args: + name: 日志名称,通常使用 __name__ + + Returns: + Logger 实例 + + 使用示例: + from core.logger import get_logger + + logger = get_logger(__name__) + logger.info("Hello World") + """ + return setup_logging(name) + + +class LoggerMixin: + """ + 日志混入类 + + 为类提供便捷的日志访问 + + 使用示例: + class MyClass(LoggerMixin): + def do_something(self): + self.logger.info("Doing something") + """ + + @property + def logger(self) -> logging.Logger: + if not hasattr(self, "_logger"): + self._logger = get_logger(self.__class__.__name__) + return self._logger diff --git a/src/core/models/__init__.py b/src/core/models/__init__.py new file mode 100644 index 0000000..5d43cb4 --- /dev/null +++ b/src/core/models/__init__.py @@ -0,0 +1,14 @@ +""" +QTrade Data Models + +数据模型模块,定义所有业务数据结构: +- market: 行情数据模型 +- order: 订单模型 +- position: 持仓模型 +- symbol_strategy: 股票-策略配对模型 +""" + +from .market import * +from .order import * +from .position import * +from .symbol_strategy import * diff --git a/src/core/models/market.py b/src/core/models/market.py new file mode 100644 index 0000000..e0160cd --- /dev/null +++ b/src/core/models/market.py @@ -0,0 +1,100 @@ +""" +行情数据模型 + +包含: +- Quote: 实时行情 +- KlineData: K线数据 +""" + +from datetime import datetime +from decimal import Decimal +from typing import Optional + +from pydantic import BaseModel, Field + + +class Quote(BaseModel): + """ + 实时行情数据 + + 来源: QMT 推送 / 回测数据回放 + """ + + symbol: str = Field(..., description="股票代码") + name: Optional[str] = Field(None, description="股票名称") + + # 价格 + price: Decimal = Field(..., description="最新价") + open: Decimal = Field(..., description="开盘价") + high: Decimal = Field(..., description="最高价") + low: Decimal = Field(..., description="最低价") + pre_close: Decimal = Field(..., description="昨收价") + + # 成交 + volume: int = Field(..., description="成交量") + amount: Decimal = Field(..., description="成交额") + + # 买卖盘 + bid_price1: Optional[Decimal] = Field(None, description="买一价") + bid_volume1: Optional[int] = Field(None, description="买一量") + ask_price1: Optional[Decimal] = Field(None, description="卖一价") + ask_volume1: Optional[int] = Field(None, description="卖一量") + + # 时间 + timestamp: datetime = Field(default_factory=datetime.now, description="行情时间") + + @property + def change(self) -> Decimal: + """涨跌额""" + return self.price - self.pre_close + + @property + def change_pct(self) -> Decimal: + """涨跌幅 (%)""" + if self.pre_close == 0: + return Decimal(0) + return (self.price - self.pre_close) / self.pre_close * 100 + + class Config: + json_encoders = { + Decimal: lambda v: float(v), + datetime: lambda v: v.isoformat(), + } + + +class KlineData(BaseModel): + """ + K线数据 + + 按周期分表存储: klines_1m, klines_5m, klines_15m, klines_30m, klines_60m, klines_1d, klines_1w + """ + + symbol: str = Field(..., description="股票代码") + period: str = Field(..., description="周期: 1m, 5m, 15m, 30m, 60m, 1d, 1w") + + # OHLCV + open: Decimal = Field(..., description="开盘价") + high: Decimal = Field(..., description="最高价") + low: Decimal = Field(..., description="最低价") + close: Decimal = Field(..., description="收盘价") + volume: int = Field(..., description="成交量") + amount: Decimal = Field(..., description="成交额") + + # 时间 + datetime: datetime = Field(..., description="K线时间") + + class Config: + json_encoders = { + Decimal: lambda v: float(v), + datetime: lambda v: v.isoformat(), + } + + +class KlineQuery(BaseModel): + """K线查询参数""" + + symbol: str = Field(..., description="股票代码") + period: str = Field(..., description="周期") + start_time: Optional[datetime] = Field(None, description="开始时间") + end_time: Optional[datetime] = Field(None, description="结束时间") + limit: int = Field(default=100, ge=1, le=1000, description="返回数量") diff --git a/src/core/models/order.py b/src/core/models/order.py new file mode 100644 index 0000000..7d22121 --- /dev/null +++ b/src/core/models/order.py @@ -0,0 +1,136 @@ +""" +订单数据模型 + +包含: +- Order: 订单 +- OrderCreate: 创建订单请求 +- OrderUpdate: 更新订单请求 +""" + +from datetime import datetime +from decimal import Decimal +from enum import Enum +from typing import Optional + +from pydantic import BaseModel, Field + + +class OrderSide(str, Enum): + """订单方向""" + + BUY = "BUY" # 买入 + SELL = "SELL" # 卖出 + + +class OrderType(str, Enum): + """订单类型""" + + LIMIT = "LIMIT" # 限价单 + MARKET = "MARKET" # 市价单 + + +class OrderStatus(str, Enum): + """订单状态""" + + PENDING = "PENDING" # 待提交 + SUBMITTED = "SUBMITTED" # 已提交 + PARTIAL = "PARTIAL" # 部分成交 + FILLED = "FILLED" # 全部成交 + CANCELLED = "CANCELLED" # 已撤销 + REJECTED = "REJECTED" # 已拒绝 + FAILED = "FAILED" # 失败 + + +class Order(BaseModel): + """ + 订单数据 + """ + + # 订单标识 + id: str = Field(..., description="订单ID") + external_id: Optional[str] = Field(None, description="外部订单ID (QMT)") + + # 配对关系 + pairing_id: str = Field(..., description="配对ID") + strategy_id: str = Field(..., description="策略ID") + + # 订单内容 + symbol: str = Field(..., description="股票代码") + side: OrderSide = Field(..., description="订单方向") + order_type: OrderType = Field(OrderType.LIMIT, description="订单类型") + price: Decimal = Field(..., description="委托价格") + quantity: int = Field(..., description="委托数量") + + # 成交信息 + filled_quantity: int = Field(default=0, description="成交数量") + filled_amount: Decimal = Field(default=Decimal(0), description="成交金额") + avg_price: Optional[Decimal] = Field(None, description="成交均价") + + # 状态 + status: OrderStatus = Field(default=OrderStatus.PENDING, description="订单状态") + message: Optional[str] = Field(None, description="状态消息") + + # 时间 + created_at: datetime = Field(default_factory=datetime.now, description="创建时间") + updated_at: datetime = Field(default_factory=datetime.now, description="更新时间") + submitted_at: Optional[datetime] = Field(None, description="提交时间") + filled_at: Optional[datetime] = Field(None, description="成交时间") + + @property + def is_active(self) -> bool: + """订单是否活跃""" + return self.status in ( + OrderStatus.PENDING, + OrderStatus.SUBMITTED, + OrderStatus.PARTIAL, + ) + + @property + def is_finished(self) -> bool: + """订单是否已结束""" + return self.status in ( + OrderStatus.FILLED, + OrderStatus.CANCELLED, + OrderStatus.REJECTED, + OrderStatus.FAILED, + ) + + @property + def unfilled_quantity(self) -> int: + """未成交数量""" + return self.quantity - self.filled_quantity + + class Config: + json_encoders = { + Decimal: lambda v: float(v), + datetime: lambda v: v.isoformat(), + } + + +class OrderCreate(BaseModel): + """创建订单请求""" + + pairing_id: str = Field(..., description="配对ID") + symbol: str = Field(..., description="股票代码") + side: OrderSide = Field(..., description="订单方向") + order_type: OrderType = Field(default=OrderType.LIMIT, description="订单类型") + price: Decimal = Field(..., description="委托价格") + quantity: int = Field(..., gt=0, description="委托数量") + + +class OrderUpdate(BaseModel): + """更新订单请求""" + + status: Optional[OrderStatus] = Field(None, description="订单状态") + filled_quantity: Optional[int] = Field(None, description="成交数量") + filled_amount: Optional[Decimal] = Field(None, description="成交金额") + avg_price: Optional[Decimal] = Field(None, description="成交均价") + external_id: Optional[str] = Field(None, description="外部订单ID") + message: Optional[str] = Field(None, description="状态消息") + + +class OrderCancel(BaseModel): + """撤销订单请求""" + + order_id: str = Field(..., description="订单ID") + reason: Optional[str] = Field(None, description="撤销原因") diff --git a/src/core/models/position.py b/src/core/models/position.py new file mode 100644 index 0000000..8e46b0f --- /dev/null +++ b/src/core/models/position.py @@ -0,0 +1,92 @@ +""" +持仓数据模型 + +包含: +- Position: 持仓 +- PositionUpdate: 更新持仓请求 +""" + +from datetime import datetime +from decimal import Decimal +from typing import Optional + +from pydantic import BaseModel, Field + + +class Position(BaseModel): + """ + 持仓数据 + + 注意: 持仓是按 pairing_id 独立管理的 + 同一股票在不同配对下有独立的持仓记录 + """ + + # 标识 + id: str = Field(..., description="持仓ID") + pairing_id: str = Field(..., description="配对ID") + strategy_id: str = Field(..., description="策略ID") + symbol: str = Field(..., description="股票代码") + + # 持仓数量 + quantity: int = Field(default=0, description="持仓数量") + available: int = Field(default=0, description="可用数量 (T+1)") + frozen: int = Field(default=0, description="冻结数量") + + # 成本与盈亏 + avg_cost: Decimal = Field(default=Decimal(0), description="持仓成本") + total_cost: Decimal = Field(default=Decimal(0), description="总成本") + market_value: Optional[Decimal] = Field(None, description="市值") + unrealized_pnl: Optional[Decimal] = Field(None, description="浮动盈亏") + realized_pnl: Decimal = Field(default=Decimal(0), description="已实现盈亏") + + # 时间 + created_at: datetime = Field(default_factory=datetime.now, description="创建时间") + updated_at: datetime = Field(default_factory=datetime.now, description="更新时间") + + @property + def pnl_ratio(self) -> Optional[Decimal]: + """盈亏比例 (%)""" + if self.total_cost == 0: + return None + if self.unrealized_pnl is None: + return None + return self.unrealized_pnl / self.total_cost * 100 + + def calculate_market_value(self, current_price: Decimal) -> Decimal: + """计算市值""" + self.market_value = current_price * self.quantity + return self.market_value + + def calculate_unrealized_pnl(self, current_price: Decimal) -> Decimal: + """计算浮动盈亏""" + self.unrealized_pnl = current_price * self.quantity - self.total_cost + return self.unrealized_pnl + + class Config: + json_encoders = { + Decimal: lambda v: float(v), + datetime: lambda v: v.isoformat(), + } + + +class PositionUpdate(BaseModel): + """更新持仓请求""" + + quantity: Optional[int] = Field(None, description="持仓数量") + available: Optional[int] = Field(None, description="可用数量") + frozen: Optional[int] = Field(None, description="冻结数量") + avg_cost: Optional[Decimal] = Field(None, description="持仓成本") + total_cost: Optional[Decimal] = Field(None, description="总成本") + realized_pnl: Optional[Decimal] = Field(None, description="已实现盈亏") + + +class PositionSummary(BaseModel): + """持仓汇总""" + + pairing_id: str = Field(..., description="配对ID") + strategy_id: str = Field(..., description="策略ID") + total_market_value: Decimal = Field(default=Decimal(0), description="总市值") + total_cost: Decimal = Field(default=Decimal(0), description="总成本") + total_unrealized_pnl: Decimal = Field(default=Decimal(0), description="总浮动盈亏") + total_realized_pnl: Decimal = Field(default=Decimal(0), description="总已实现盈亏") + position_count: int = Field(default=0, description="持仓品种数") diff --git a/src/core/models/symbol_strategy.py b/src/core/models/symbol_strategy.py new file mode 100644 index 0000000..54b2260 --- /dev/null +++ b/src/core/models/symbol_strategy.py @@ -0,0 +1,113 @@ +""" +股票-策略配对模型 + +包含: +- SymbolStrategy: 配对关系 +- PairingCreate: 创建配对请求 +""" + +from datetime import datetime +from decimal import Decimal +from enum import Enum +from typing import Optional + +from pydantic import BaseModel, Field + + +class PairingStatus(str, Enum): + """配对状态""" + + ACTIVE = "ACTIVE" # 活跃 + PAUSED = "PAUSED" # 暂停 + STOPPED = "STOPPED" # 停止 + + +class SymbolStrategy(BaseModel): + """ + 股票-策略配对 + + 一只股票可以配对多个策略 + 每个配对有独立的持仓和资金管理 + """ + + # 标识 + id: str = Field(..., description="配对ID") + symbol: str = Field(..., description="股票代码") + symbol_name: Optional[str] = Field(None, description="股票名称") + strategy_id: str = Field(..., description="策略ID") + strategy_name: Optional[str] = Field(None, description="策略名称") + + # 资金配置 + initial_capital: Decimal = Field(..., description="初始资金") + current_capital: Decimal = Field(..., description="当前资金") + available_capital: Decimal = Field(..., description="可用资金") + frozen_capital: Decimal = Field(default=Decimal(0), description="冻结资金") + + # 状态 + status: PairingStatus = Field(default=PairingStatus.ACTIVE, description="配对状态") + + # 策略参数 + params: dict = Field(default_factory=dict, description="策略参数") + + # 统计 + total_trades: int = Field(default=0, description="总交易次数") + win_trades: int = Field(default=0, description="盈利次数") + loss_trades: int = Field(default=0, description="亏损次数") + total_pnl: Decimal = Field(default=Decimal(0), description="总盈亏") + max_drawdown: Decimal = Field(default=Decimal(0), description="最大回撤") + + # 时间 + created_at: datetime = Field(default_factory=datetime.now, description="创建时间") + updated_at: datetime = Field(default_factory=datetime.now, description="更新时间") + + @property + def win_rate(self) -> Optional[float]: + """胜率""" + if self.total_trades == 0: + return None + return self.win_trades / self.total_trades + + @property + def return_rate(self) -> Decimal: + """收益率 (%)""" + if self.initial_capital == 0: + return Decimal(0) + return ( + (self.current_capital - self.initial_capital) / self.initial_capital * 100 + ) + + class Config: + json_encoders = { + Decimal: lambda v: float(v), + datetime: lambda v: v.isoformat(), + } + + +class PairingCreate(BaseModel): + """创建配对请求""" + + symbol: str = Field(..., description="股票代码") + symbol_name: Optional[str] = Field(None, description="股票名称") + strategy_id: str = Field(..., description="策略ID") + strategy_name: Optional[str] = Field(None, description="策略名称") + initial_capital: Decimal = Field(..., gt=0, description="初始资金") + params: dict = Field(default_factory=dict, description="策略参数") + + +class PairingUpdate(BaseModel): + """更新配对请求""" + + status: Optional[PairingStatus] = Field(None, description="配对状态") + params: Optional[dict] = Field(None, description="策略参数") + current_capital: Optional[Decimal] = Field(None, description="当前资金") + available_capital: Optional[Decimal] = Field(None, description="可用资金") + + +class PairingQuery(BaseModel): + """查询配对请求""" + + symbol: Optional[str] = Field(None, description="股票代码") + strategy_id: Optional[str] = Field(None, description="策略ID") + status: Optional[PairingStatus] = Field(None, description="配对状态") + page: int = Field(default=1, ge=1, description="页码") + page_size: int = Field(default=20, ge=1, le=100, description="每页数量") diff --git a/src/core/redis_client.py b/src/core/redis_client.py new file mode 100644 index 0000000..c79500b --- /dev/null +++ b/src/core/redis_client.py @@ -0,0 +1,319 @@ +""" +QTrade Redis 客户端模块 + +提供异步 Redis 操作封装: +- 连接池管理 +- Pub/Sub 订阅 +- 常用操作封装 +""" + +import asyncio +import json +from contextlib import asynccontextmanager +from typing import Any, AsyncIterator, Callable, Optional + +import redis.asyncio as redis +from redis.asyncio import Redis +from redis.asyncio.client import PubSub + +from .config import settings +from .logger import get_logger + +logger = get_logger(__name__) + + +class RedisClient: + """ + 异步 Redis 客户端 + + 提供连接池管理和常用操作封装 + """ + + _instance: Optional["RedisClient"] = None + _pool: Optional[redis.ConnectionPool] = None + _client: Optional[Redis] = None + + def __new__(cls): + if cls._instance is None: + cls._instance = super().__new__(cls) + return cls._instance + + async def connect(self) -> None: + """建立 Redis 连接""" + if self._client is not None: + return + + self._pool = redis.ConnectionPool.from_url( + settings.redis.url, + max_connections=settings.redis.pool_size, + socket_timeout=settings.redis.pool_timeout, + decode_responses=True, + ) + self._client = Redis(connection_pool=self._pool) + + # 测试连接 + try: + await self._client.ping() + logger.info(f"Redis 连接成功: {settings.redis.host}:{settings.redis.port}") + except Exception as e: + logger.error(f"Redis 连接失败: {e}") + raise + + async def disconnect(self) -> None: + """断开 Redis 连接""" + if self._client: + await self._client.close() + self._client = None + if self._pool: + await self._pool.disconnect() + self._pool = None + logger.info("Redis 连接已断开") + + @property + def client(self) -> Redis: + """获取 Redis 客户端实例""" + if self._client is None: + raise RuntimeError("Redis 客户端未连接,请先调用 connect()") + return self._client + + # ========== 基础操作 ========== + + async def get(self, key: str) -> Optional[str]: + """获取值""" + return await self.client.get(key) + + async def set( + self, + key: str, + value: str, + ex: Optional[int] = None, + px: Optional[int] = None, + ) -> bool: + """设置值""" + return await self.client.set(key, value, ex=ex, px=px) + + async def delete(self, *keys: str) -> int: + """删除键""" + return await self.client.delete(*keys) + + async def exists(self, *keys: str) -> int: + """检查键是否存在""" + return await self.client.exists(*keys) + + async def expire(self, key: str, seconds: int) -> bool: + """设置过期时间""" + return await self.client.expire(key, seconds) + + # ========== JSON 操作 ========== + + async def get_json(self, key: str) -> Optional[Any]: + """获取 JSON 对象""" + value = await self.get(key) + if value is None: + return None + return json.loads(value) + + async def set_json( + self, + key: str, + value: Any, + ex: Optional[int] = None, + ) -> bool: + """设置 JSON 对象""" + return await self.set(key, json.dumps(value, ensure_ascii=False), ex=ex) + + # ========== Hash 操作 ========== + + async def hget(self, name: str, key: str) -> Optional[str]: + """获取 Hash 字段""" + return await self.client.hget(name, key) + + async def hset(self, name: str, key: str, value: str) -> int: + """设置 Hash 字段""" + return await self.client.hset(name, key, value) + + async def hgetall(self, name: str) -> dict[str, str]: + """获取整个 Hash""" + return await self.client.hgetall(name) + + async def hdel(self, name: str, *keys: str) -> int: + """删除 Hash 字段""" + return await self.client.hdel(name, *keys) + + # ========== List 操作 ========== + + async def lpush(self, name: str, *values: str) -> int: + """左端入队""" + return await self.client.lpush(name, *values) + + async def rpush(self, name: str, *values: str) -> int: + """右端入队""" + return await self.client.rpush(name, *values) + + async def lpop(self, name: str) -> Optional[str]: + """左端出队""" + return await self.client.lpop(name) + + async def rpop(self, name: str) -> Optional[str]: + """右端出队""" + return await self.client.rpop(name) + + async def lrange(self, name: str, start: int, end: int) -> list[str]: + """获取列表范围""" + return await self.client.lrange(name, start, end) + + async def llen(self, name: str) -> int: + """获取列表长度""" + return await self.client.llen(name) + + # ========== Pub/Sub 操作 ========== + + async def publish(self, channel: str, message: Any) -> int: + """ + 发布消息 + + Args: + channel: 频道名称 + message: 消息内容(自动 JSON 序列化) + + Returns: + 接收者数量 + """ + if not isinstance(message, str): + message = json.dumps(message, ensure_ascii=False) + return await self.client.publish(channel, message) + + @asynccontextmanager + async def subscribe( + self, + *channels: str, + ) -> AsyncIterator[PubSub]: + """ + 订阅频道(上下文管理器) + + 使用方法: + async with redis_client.subscribe("channel1", "channel2") as pubsub: + async for message in pubsub.listen(): + if message["type"] == "message": + print(message["data"]) + """ + pubsub = self.client.pubsub() + try: + await pubsub.subscribe(*channels) + yield pubsub + finally: + await pubsub.unsubscribe(*channels) + await pubsub.close() + + async def subscribe_handler( + self, + channel: str, + handler: Callable[[dict], Any], + stop_event: Optional[asyncio.Event] = None, + ) -> None: + """ + 订阅频道并处理消息 + + Args: + channel: 频道名称 + handler: 消息处理函数 + stop_event: 停止事件 + """ + async with self.subscribe(channel) as pubsub: + logger.info(f"开始订阅频道: {channel}") + async for message in pubsub.listen(): + if stop_event and stop_event.is_set(): + break + if message["type"] == "message": + try: + data = json.loads(message["data"]) + await handler(data) if asyncio.iscoroutinefunction( + handler + ) else handler(data) + except json.JSONDecodeError: + # 非 JSON 消息,直接传递 + await handler(message["data"]) if asyncio.iscoroutinefunction( + handler + ) else handler(message["data"]) + except Exception as e: + logger.error(f"处理消息失败: {e}") + + +# ========== 预定义的 Redis Key 和 Channel ========== + + +class RedisKeys: + """Redis Key 常量""" + + # 行情数据 + QUOTE_PREFIX = "quote:" # quote:{symbol} - 实时行情 + KLINE_PREFIX = "kline:" # kline:{symbol}:{period} - K线数据 + + # 订单 + ORDER_PREFIX = "order:" # order:{order_id} + ORDER_PENDING = "orders:pending" # 待处理订单队列 + + # 持仓 + POSITION_PREFIX = "position:" # position:{pairing_id} + + # 配对 + PAIRING_PREFIX = "pairing:" # pairing:{id} + PAIRING_LIST = "pairings:active" # 活跃配对列表 + + # 策略 + STRATEGY_PREFIX = "strategy:" # strategy:{id} + + # 账户 + ACCOUNT_PREFIX = "account:" # account:{account_id} + + @staticmethod + def quote(symbol: str) -> str: + return f"{RedisKeys.QUOTE_PREFIX}{symbol}" + + @staticmethod + def kline(symbol: str, period: str) -> str: + return f"{RedisKeys.KLINE_PREFIX}{symbol}:{period}" + + @staticmethod + def order(order_id: str) -> str: + return f"{RedisKeys.ORDER_PREFIX}{order_id}" + + @staticmethod + def position(pairing_id: str) -> str: + return f"{RedisKeys.POSITION_PREFIX}{pairing_id}" + + @staticmethod + def pairing(pairing_id: str) -> str: + return f"{RedisKeys.PAIRING_PREFIX}{pairing_id}" + + +class RedisChannels: + """Redis Pub/Sub 频道常量""" + + # 行情频道 + MARKET_QUOTE = "market:quote" # 实时行情推送 + MARKET_KLINE = "market:kline" # K线推送 + + # 交易频道 + TRADE_ORDER = "trade:order" # 订单事件 + TRADE_SIGNAL = "trade:signal" # 交易信号 + TRADE_EXEC = "trade:exec" # 交易执行(发给 QMT) + + # 账户频道 + ACCOUNT_UPDATE = "account:update" # 账户更新 + POSITION_UPDATE = "position:update" # 持仓更新 + + # 系统频道 + SYSTEM_STATUS = "system:status" # 系统状态 + + +# 全局客户端实例 +redis_client = RedisClient() + + +# 便捷函数 +async def get_redis() -> RedisClient: + """获取 Redis 客户端(确保已连接)""" + if redis_client._client is None: + await redis_client.connect() + return redis_client diff --git a/src/data_process_model/README.md b/src/data_process_model/README.md deleted file mode 100644 index d9d281f..0000000 --- a/src/data_process_model/README.md +++ /dev/null @@ -1,393 +0,0 @@ -# 数据处理模块 (Data Process Model) - -数据处理模块是QTrade量化交易系统的核心数据处理组件,负责股票历史数据的获取、处理、格式化和存储。支持多种数据源集成和双重存储方案(CSV + MySQL)。 - -## 🚀 主要功能 - -- **数据获取**: 集成xtquant数据源,支持A股、港股、美股数据 -- **数据处理**: 自动化数据清洗、格式化和时间戳转换 -- **双重存储**: 同时支持CSV文件和MySQL数据库存储 -- **批量处理**: 支持多个股票代码并行处理 -- **增量更新**: 支持增量数据下载,避免重复获取 -- **数据验证**: 自动数据完整性检查和异常处理 - -## 📁 模块结构 - -``` -data_process_model/ -├── README.md # 本文档 -├── main.py # 主程序入口 ⭐ -├── database_config.py # MySQL数据库配置 -├── stock_models.py # 股票数据模型 (Peewee ORM) -└── data/ # 本地数据存储目录 - ├── *.csv # CSV格式的股票数据文件 - └── ... -``` - -## 🛠️ 快速开始 - -### 1. 环境准备 - -```bash -# 安装依赖包 -pip install pandas numpy peewee pymysql xtquant - -# 确保MySQL服务器运行 (可选) -# Windows: 启动MySQL服务 -# Linux: sudo service mysql start -``` - -### 2. 配置数据库 - -编辑 `database_config.py` 文件: - -```python -DATABASE_CONFIG = { - 'host': 'localhost', # MySQL服务器地址 - 'port': 3306, # MySQL端口 - 'user': 'root', # 用户名 - 'password': 'your_password', # 修改为您的密码 - 'database': 'qtrade_stock_data', # 数据库名 - 'charset': 'utf8mb4' -} -``` - -### 3. 配置股票参数 - -在 `main.py` 中修改全局配置: - -```python -g_stock_code_list = ["601658.SH", "510310.SH", "601398.SH"] # 股票代码 -g_period = "1m" # 数据周期 -g_start_date = "20250501" # 开始日期 -g_end_date = "20250721" # 结束日期 -``` - -### 4. 运行程序 - -```bash -# 进入模块目录 -cd src/data_process_model - -# 运行数据处理程序 -python main.py -``` - -## 📊 支持的数据格式 - -### 股票代码格式 -- **A股**: `600000.SH`, `000001.SZ` -- **港股**: `00700.HK` -- **ETF**: `510300.SH`, `159919.SZ` -- **期货**: `IF2312.CFX` - -### 数据周期 -- **分钟线**: `1m`, `5m`, `15m`, `30m`, `60m` -- **日线**: `1d` -- **周线**: `1w` -- **月线**: `1M` - -### 数据字段 -```python -g_fields = [ - "time", # 时间戳 - "open", # 开盘价 - "high", # 最高价 - "low", # 最低价 - "close", # 收盘价 - "volume", # 成交量 - "amount" # 成交额 -] -``` - -## 🏗️ 核心功能详解 - -### 数据下载 (`download_stock_data`) - -```python -def download_stock_data(stock_codes, period, start_date, end_date): - """ - 从xtquant数据源下载股票历史数据 - - 支持: - - 多股票并行下载 - - 增量下载模式 - - 自动重试机制 - """ -``` - -**使用示例**: -```python -codes = ["601658.SH", "000001.SZ"] -data = download_stock_data(codes, "1d", "20240101", "20241231") -``` - -### 数据处理 (`process_stock_data`) - -```python -def process_stock_data(stock_code, stock_data): - """ - 处理单个股票的原始数据 - - 功能: - - 时间戳格式化 - - DataFrame转换 - - 数据索引设置 - """ -``` - -**时间转换流程**: -1. Unix时间戳 → `conv_time()` → 格式化字符串 -2. 格式化字符串 → `pd.to_datetime()` → Pandas时间索引 - -### CSV存储 (`save_dataframe_to_csv`) - -```python -def save_dataframe_to_csv(df, stock_code, period, output_dir="data"): - """ - 保存DataFrame为CSV文件 - - 特点: - - 自动文件命名 (包含时间戳) - - UTF-8编码支持 - - 数据预览和统计 - """ -``` - -**文件命名规则**: -``` -{股票代码}_{周期}_{时间戳}.csv -例如: 601658_SH_1m_20250722_161844_000211.csv -``` - -### MySQL存储 (`save_all_to_mysql`) - -```python -def save_all_to_mysql(processed_data, stock_models): - """ - 批量保存数据到MySQL数据库 - - 特点: - - 动态表创建 - - 批量插入优化 - - 数据精度保证 - """ -``` - -**数据库表结构**: -```sql -CREATE TABLE kline_{股票代码}_{周期} ( - timestamp DATETIME PRIMARY KEY, - open_price DECIMAL(10,3), - high_price DECIMAL(10,3), - low_price DECIMAL(10,3), - close_price DECIMAL(10,3), - volume BIGINT, - amount DECIMAL(20,2), - created_at DATETIME, - updated_at DATETIME -); -``` - -## 📈 程序执行流程 - -``` -1. 初始化数据库连接 - ├── 创建数据库 (如果不存在) - ├── 建立Peewee连接 - └── 验证连接状态 - -2. 下载股票数据 - ├── 调用xtquant API - ├── 增量下载模式 - └── 返回原始数据字典 - -3. 数据处理和转换 - ├── 批量处理多个股票 - ├── 时间戳格式化 - ├── DataFrame转换 - └── 数据验证 - -4. 双重存储 - ├── CSV文件保存 - │ ├── 创建输出目录 - │ ├── 生成唯一文件名 - │ └── UTF-8编码保存 - └── MySQL数据库保存 - ├── 动态创建表结构 - ├── 批量插入数据 - └── 记录统计信息 - -5. 结果统计和清理 - ├── 显示处理统计 - ├── 输出文件路径 - └── 关闭数据库连接 -``` - -## 🔧 配置选项 - -### 全局配置参数 - -| 参数 | 默认值 | 说明 | -|------|--------|------| -| `g_stock_code_list` | `["601658.SH", "510310.SH", "601398.SH"]` | 股票代码列表 | -| `g_period` | `"1m"` | 数据周期 | -| `g_start_date` | `"20250501"` | 开始日期 | -| `g_end_date` | `"20250721"` | 结束日期 | -| `g_fields` | `["time", "open", ...]` | 数据字段列表 | - -### 数据库配置 - -```python -DATABASE_CONFIG = { - 'host': 'localhost', # 数据库主机 - 'port': 3306, # 数据库端口 - 'user': 'root', # 用户名 - 'password': '1234', # 密码 - 'database': 'qtrade_stock_data', # 数据库名 - 'charset': 'utf8mb4' # 字符编码 -} -``` - -## 🧪 测试和验证 - -### 1. 基本功能测试 - -```bash -# 运行数据处理程序 -python main.py - -# 检查CSV文件 -ls data/*.csv - -# 验证MySQL数据 -mysql -u root -p -USE qtrade_stock_data; -SHOW TABLES; -SELECT COUNT(*) FROM kline_601658_sh_1m; -``` - -### 2. 数据验证 - -```python -import pandas as pd - -# 读取CSV文件验证 -df = pd.read_csv('data/601658_SH_1m_*.csv', index_col=0, parse_dates=True) -print(f"数据形状: {df.shape}") -print(f"时间范围: {df.index.min()} ~ {df.index.max()}") -print(f"数据预览:\n{df.head()}") -``` - -### 3. 性能监控 - -```python -import time - -start_time = time.time() -# 运行数据处理 -# ... -end_time = time.time() - -print(f"处理时间: {end_time - start_time:.2f} 秒") -``` - -## 🔍 故障排查 - -### 常见问题 - -1. **xtquant连接失败** - ```bash - # 检查网络连接 - ping api.xtdata.cn - - # 验证API权限 - # 确认xtquant账户状态 - ``` - -2. **MySQL连接失败** - ```bash - # 检查MySQL服务状态 - # Windows: services.msc 查看MySQL服务 - # Linux: sudo service mysql status - - # 测试数据库连接 - mysql -h localhost -u root -p - ``` - -3. **数据处理异常** - ```python - # 检查数据格式 - print(f"数据类型: {type(history_data)}") - print(f"数据键: {list(history_data.keys()) if history_data else 'None'}") - - # 验证时间戳格式 - if 'time' in stock_data: - print(f"时间戳示例: {stock_data['time'][:5]}") - ``` - -### 日志和调试 - -程序运行时会输出详细的处理日志: - -``` -🎯 数据处理模型主程序 (支持MySQL长连接) -============================================================ -🔗 正在初始化MySQL数据库连接... -✅ MySQL数据库连接成功,保持长连接状态 -🔄 正在下载历史数据... -📊 正在获取市场数据... -💾 开始处理 3 个股票的数据... -🔍 处理股票: 601658.SH -✅ 601658.SH 数据处理完成: (1234, 6) -... -``` - -## 📚 API参考 - -### 主要函数 - -| 函数 | 说明 | 返回值 | -|------|------|--------| -| `main()` | 主程序入口 | None | -| `download_stock_data()` | 下载股票数据 | dict | -| `process_stock_data()` | 处理单个股票数据 | DataFrame | -| `process_all_stocks()` | 批量处理股票数据 | dict | -| `save_dataframe_to_csv()` | 保存CSV文件 | str or None | -| `save_all_to_csv()` | 批量保存CSV | list | -| `save_all_to_mysql()` | 保存到MySQL | dict | -| `conv_time()` | 时间戳转换 | str | - -### 工具函数 - -```python -# 时间转换 -timestamp_str = conv_time(1640995200000) - -# 文件保存 -csv_path = save_dataframe_to_csv(df, "601658.SH", "1m") - -# 数据处理 -processed_df = process_stock_data("601658.SH", raw_data) -``` - -## 🔗 相关文档 - -- [项目主README](../../README.md) - 项目总体介绍 -- [数据库配置说明](database_config.py) - 数据库连接配置 -- [数据模型文档](stock_models.py) - Peewee ORM模型定义 -- [xtquant文档](https://xtdata.cn/) - 数据源API文档 - -## 📝 更新日志 - -### v2.1.0 (当前版本) -- ✅ 集成xtquant数据源 -- ✅ 添加MySQL数据库支持 -- ✅ 实现CSV和数据库双重存储 -- ✅ 支持批量股票处理 -- ✅ 添加完整的错误处理和日志 -- ✅ 优化数据处理流水线 - ---- - -💡 **提示**: 首次运行前请确保已正确配置数据库连接参数,并且MySQL服务正在运行。如需要技术支持,请参考项目主文档或联系开发团队。 diff --git a/src/data_process_model/common.py b/src/data_process_model/common.py deleted file mode 100644 index be805ef..0000000 --- a/src/data_process_model/common.py +++ /dev/null @@ -1,411 +0,0 @@ -""" -数据处理模型公共配置文件 (common.py) -类似于C++中的common.h头文件,定义所有模块共同遵守的数据结构、约定和常量 - -本文件包含: -- 股票数据结构定义 -- 数据库表结构约定 -- 时间格式标准 -- 字段命名约定 -- 数据验证规则 -- 常用枚举和常量 -""" - -from typing import List, Dict, Any, Optional, Union -from datetime import datetime -from enum import Enum -import pandas as pd - -# ============================= 基础常量定义 ============================= - -# 支持的股票市场 -class StockMarket(Enum): - """股票市场枚举""" - SH = "SH" # 上海证券交易所 - SZ = "SZ" # 深圳证券交易所 - -# 支持的时间周期 -class TimeFrame(Enum): - """时间周期枚举""" - MINUTE_1 = "1m" # 1分钟 - MINUTE_5 = "5m" # 5分钟 - MINUTE_15 = "15m" # 15分钟 - MINUTE_30 = "30m" # 30分钟 - MINUTE_60 = "60m" # 60分钟 (1小时) - DAILY = "1d" # 日线 - WEEKLY = "1w" # 周线 - MONTHLY = "1M" # 月线 - -# 数据来源 -class DataSource(Enum): - """数据来源枚举""" - DATABASE = "database" # 数据库原始数据 - EXTERNAL = "external" # 外部添加数据 - CALCULATED = "calculated" # 计算生成数据 - REALTIME = "realtime" # 实时数据 - -# 交易方向 -class TradeDirection(Enum): - """交易方向枚举""" - BUY = "BUY" - SELL = "SELL" - -# 委托类型 -class OrderType(Enum): - """委托类型枚举""" - MARKET = "MARKET" # 市价单 - LIMIT = "LIMIT" # 限价单 - -# 委托状态 -class OrderStatus(Enum): - """委托状态枚举""" - PENDING = "PENDING" # 待成交 - FILLED = "FILLED" # 全部成交 - PARTIAL = "PARTIAL" # 部分成交 - CANCELLED = "CANCELLED" # 已撤销 - -# ============================= 数据结构约定 ============================= - -# 标准K线数据字段名约定 -KLINE_COLUMNS = { - 'timestamp': 'timestamp', # 时间戳 (datetime类型) - 'open': 'open', # 开盘价 (float) - 'high': 'high', # 最高价 (float) - 'low': 'low', # 最低价 (float) - 'close': 'close', # 收盘价 (float) - 'volume': 'volume', # 成交量 (int) -} - -# 交易记录相关字段名约定 -TRADE_COLUMNS = { - 'order_id': 'order_id', - 'execution_id': 'execution_id', - 'stockcode': 'stockcode', # 统一使用 stockcode - 'order_time': 'order_time', - 'execution_time': 'execution_time', - 'direction': 'direction', - 'price': 'price', - 'quantity': 'quantity', - 'amount': 'amount', - 'commission': 'commission', - 'order_type': 'order_type', - 'status': 'status' -} - -# 标准K线数据字段类型约定 -KLINE_DTYPES = { - 'timestamp': 'datetime64[ns]', - 'open': 'float64', - 'high': 'float64', - 'low': 'float64', - 'close': 'float64', - 'volume': 'int64' -} - -# 技术指标字段命名约定 -INDICATOR_COLUMNS = { - # 移动平均线 - 'ma5': 'ma5', 'ma10': 'ma10', 'ma20': 'ma20', 'ma60': 'ma60', - 'ema5': 'ema5', 'ema10': 'ema10', 'ema20': 'ema20', 'ema60': 'ema60', - - # MACD指标 - 'macd': 'macd', # MACD线 - 'macd_signal': 'signal', # 信号线 - 'macd_hist': 'histogram', # 柱状图 - - # RSI指标 - 'rsi': 'rsi', - 'rsi_14': 'rsi_14', - - # 布林带 - 'bb_upper': 'bb_upper', # 上轨 - 'bb_middle': 'bb_middle', # 中轨 - 'bb_lower': 'bb_lower', # 下轨 - - # KDJ指标 - 'kdj_k': 'k', - 'kdj_d': 'd', - 'kdj_j': 'j' -} - -# ============================= 股票代码处理约定 ============================= - -# 股票代码识别规则 -STOCK_CODE_PATTERNS = { - # 上海市场 - 'SH_PATTERNS': [ - r'^60[0-9]{4}$', # 主板: 600xxx, 601xxx, 603xxx, 605xxx - r'^68[0-9]{4}$', # 科创板: 688xxx - r'^51[0-9]{4}$', # ETF: 510xxx, 511xxx, 512xxx, 513xxx, 515xxx, 516xxx, 518xxx - r'^50[0-9]{4}$', # 其他: 500xxx - ], - # 深圳市场 - 'SZ_PATTERNS': [ - r'^00[0-9]{4}$', # 主板: 000xxx, 001xxx, 002xxx, 003xxx - r'^30[0-9]{4}$', # 创业板: 300xxx, 301xxx - r'^15[0-9]{4}$', # ETF: 150xxx, 159xxx - r'^16[0-9]{4}$', # 可转债等: 160xxx - ] -} - -def normalize_stock_code(stock_code: str) -> str: - """ - 标准化股票代码格式 - - 规则: - - 输入: "601658" -> 输出: "601658.SH" - - 输入: "000001" -> 输出: "000001.SZ" - - 输入: "601658.SH" -> 输出: "601658.SH" - - Args: - stock_code (str): 原始股票代码 - - Returns: - str: 标准化后的股票代码 - """ - if not stock_code: - return stock_code - - # 如果已经包含市场后缀,直接返回大写格式 - if '.' in stock_code: - return stock_code.upper() - - # 导入re用于模式匹配 - import re - - # 检查是否匹配上海市场 - for pattern in STOCK_CODE_PATTERNS['SH_PATTERNS']: - if re.match(pattern, stock_code): - return f"{stock_code}.SH" - - # 检查是否匹配深圳市场 - for pattern in STOCK_CODE_PATTERNS['SZ_PATTERNS']: - if re.match(pattern, stock_code): - return f"{stock_code}.SZ" - - # 默认为上海市场 - return f"{stock_code}.SH" - -def get_table_name(stock_code: str, period: str) -> str: - """ - 获取数据库表名 - - 约定:kline_{stock_code}_{period} - - Args: - stock_code (str): 股票代码 (如: "601658.SH") - period (str): 时间周期 (如: "1m", "1d") - - Returns: - str: 数据库表名 (如: "kline_601658_sh_1m") - """ - # 标准化股票代码 - normalized_code = normalize_stock_code(stock_code) - - # 转换为表名格式: 601658.SH -> 601658_sh - code_part = normalized_code.lower().replace('.', '_') - - return f"kline_{code_part}_{period}" - -# ============================= 时间格式约定 ============================= - -# 标准时间格式 -TIME_FORMATS = { - 'STANDARD': '%Y-%m-%d %H:%M:%S', # 2024-07-22 09:30:00 - 'DATE_ONLY': '%Y-%m-%d', # 2024-07-22 - 'TIME_ONLY': '%H:%M:%S', # 09:30:00 - 'ISO_FORMAT': '%Y-%m-%dT%H:%M:%S', # 2024-07-22T09:30:00 - 'COMPACT': '%Y%m%d_%H%M%S', # 20240722_093000 -} - -def standardize_timestamp(timestamp: Union[str, datetime, pd.Timestamp]) -> pd.Timestamp: - """ - 标准化时间戳格式 - - Args: - timestamp: 时间戳,支持多种格式 - - Returns: - pd.Timestamp: 标准化后的时间戳 - """ - if isinstance(timestamp, str): - return pd.to_datetime(timestamp) - elif isinstance(timestamp, datetime): - return pd.Timestamp(timestamp) - elif isinstance(timestamp, pd.Timestamp): - return timestamp - else: - raise ValueError(f"不支持的时间戳类型: {type(timestamp)}") - -# ============================= 数据验证规则 ============================= - -def validate_kline_data(df: pd.DataFrame) -> Dict[str, Any]: - """ - 验证K线数据格式是否符合约定 - - Args: - df (pd.DataFrame): K线数据 - - Returns: - Dict[str, Any]: 验证结果 - """ - result = { - 'valid': True, - 'errors': [], - 'warnings': [], - 'info': {} - } - - # 检查必需的列 - required_columns = set(KLINE_COLUMNS.values()) - actual_columns = set(df.columns) - - missing_columns = required_columns - actual_columns - if missing_columns: - result['valid'] = False - result['errors'].append(f"缺少必需的列: {missing_columns}") - - # 检查数据类型 - if result['valid']: - for col in KLINE_COLUMNS.values(): - if col in df.columns: - expected_dtype = KLINE_DTYPES[col] - actual_dtype = str(df[col].dtype) - - if col == 'timestamp': - if not pd.api.types.is_datetime64_any_dtype(df[col]): - result['warnings'].append(f"时间列 '{col}' 类型不是datetime: {actual_dtype}") - elif col in ['open', 'high', 'low', 'close']: - if not pd.api.types.is_numeric_dtype(df[col]): - result['errors'].append(f"价格列 '{col}' 类型不是数值型: {actual_dtype}") - result['valid'] = False - elif col == 'volume': - if not pd.api.types.is_integer_dtype(df[col]) and not pd.api.types.is_numeric_dtype(df[col]): - result['warnings'].append(f"成交量列 '{col}' 类型不是整型: {actual_dtype}") - - # 检查数据逻辑性 - if result['valid'] and len(df) > 0: - # 检查价格逻辑 (high >= max(open, close), low <= min(open, close)) - price_logic_error = ( - (df['high'] < df[['open', 'close']].max(axis=1)) | - (df['low'] > df[['open', 'close']].min(axis=1)) - ).any() - - if price_logic_error: - result['warnings'].append("存在价格逻辑错误的记录 (high < max(open,close) 或 low > min(open,close))") - - # 检查成交量为负 - if (df['volume'] < 0).any(): - result['warnings'].append("存在负成交量的记录") - - # 统计信息 - result['info'] = { - 'total_records': len(df), - 'columns': list(df.columns), - 'date_range': None - } - - if 'timestamp' in df.columns and len(df) > 0: - result['info']['date_range'] = { - 'start': df['timestamp'].min(), - 'end': df['timestamp'].max() - } - - return result - -# ============================= 缓存键约定 ============================= - -def get_cache_key(stock_code: str, period: str) -> str: - """ - 获取缓存键名 - - 约定:{stock_code}_{period} - - Args: - stock_code (str): 标准化后的股票代码 - period (str): 时间周期 - - Returns: - str: 缓存键名 - """ - normalized_code = normalize_stock_code(stock_code) - return f"{normalized_code}_{period}" - -# ============================= 内存管理约定 ============================= - -# 内存缓存配置 -MEMORY_CONFIG = { - 'MAX_CACHE_SIZE_MB': 1024, # 最大缓存大小(MB) - 'MAX_RECORDS_PER_CACHE': 10000, # 每个缓存最大记录数 - 'CLEANUP_THRESHOLD': 0.8, # 清理阈值(80%) - 'DEFAULT_LIMIT': 1000, # 默认查询限制 -} - -# 共享内存配置 -SHARED_MEMORY_CONFIG = { - 'CACHE_NAME': 'qtrade_kline_cache', - 'DEFAULT_SIZE_MB': 100, - 'CLEANUP_INTERVAL_SECONDS': 300, # 5分钟清理一次 -} - -# ============================= 数据库约定 ============================= - -# 数据库表前缀 -TABLE_PREFIXES = { - 'KLINE': 'kline_', # K线数据表 - 'INDICATOR': 'indicator_', # 技术指标表 - 'TEST': 'test_', # 测试表 - 'TEMP': 'temp_', # 临时表 -} - -# 数据库字段长度限制 -FIELD_LIMITS = { - 'STOCK_CODE': 20, # 股票代码字段长度 - 'PERIOD': 10, # 周期字段长度 - 'SOURCE': 50, # 数据源字段长度 - 'COMMENT': 255, # 注释字段长度 -} - -# ============================= 日志约定 ============================= - -# 日志前缀约定 -LOG_PREFIXES = { - 'SUCCESS': '✅', # 成功操作 - 'ERROR': '❌', # 错误 - 'WARNING': '⚠️', # 警告 - 'INFO': 'ℹ️', # 信息 - 'DEBUG': '🔍', # 调试 - 'DATABASE': '📊', # 数据库操作 - 'CACHE': '🗄️', # 缓存操作 - 'NETWORK': '🌐', # 网络操作 - 'FILE': '📁', # 文件操作 - 'MEMORY': '💾', # 内存操作 - 'TIME': '⏰', # 时间相关 - 'CALCULATION': '🧮', # 计算相关 - 'ANALYSIS': '📈', # 技术分析 - 'TOOL': '🔧', # 工具相关 - 'CLEANING': '🧹', # 清理操作 -} - -# ============================= 导出所有公共约定 ============================= - -__all__ = [ - # 枚举类 - 'StockMarket', 'TimeFrame', 'DataSource', - - # 常量 - 'KLINE_COLUMNS', 'KLINE_DTYPES', 'INDICATOR_COLUMNS', - 'STOCK_CODE_PATTERNS', 'TIME_FORMATS', 'MEMORY_CONFIG', - 'SHARED_MEMORY_CONFIG', 'TABLE_PREFIXES', 'FIELD_LIMITS', - 'LOG_PREFIXES', - - # 函数 - 'normalize_stock_code', 'get_table_name', 'standardize_timestamp', - 'validate_kline_data', 'get_cache_key', -] - -# ============================= 版本信息 ============================= - -__version__ = "1.0.0" -__author__ = "QTrade Team" -__description__ = "数据处理模型公共配置和约定" diff --git a/src/data_process_model/database_config.py b/src/data_process_model/database_config.py deleted file mode 100644 index 5e7697e..0000000 --- a/src/data_process_model/database_config.py +++ /dev/null @@ -1,150 +0,0 @@ -""" -数据库配置模块 -使用peewee ORM连接MySQL数据库,管理股票K线数据 -""" - -from peewee import MySQLDatabase, Model -import logging - -# 导入公共配置 -from common import LOG_PREFIXES - -# 配置日志 -logging.basicConfig(level=logging.INFO) -logger = logging.getLogger(__name__) - -# 数据库连接配置 -DATABASE_CONFIG = { - 'host': 'localhost', # MySQL服务器地址 - 'port': 3306, # MySQL端口 - 'user': 'root', # 用户名 - 'password': '1234', # 密码 - 请根据实际情况修改 - 'database': 'qtrade_stock_data', # 数据库名 - 'charset': 'utf8mb4' -} - -# 创建MySQL数据库连接 -# 注意:这里暂时不连接,等待init_database()时再连接 -mysql_db = None - -def init_database(): - """ - 初始化数据库连接和创建数据库(如果不存在) - - Returns: - bool: 初始化成功返回True,失败返回False - """ - global mysql_db - try: - # 先用pymysql直接连接创建数据库 - import pymysql - - temp_config = DATABASE_CONFIG.copy() - temp_config.pop('database', None) # 移除database参数 - - # 使用pymysql创建数据库 - conn = pymysql.connect(**temp_config) - cursor = conn.cursor() - cursor.execute(f"CREATE DATABASE IF NOT EXISTS {DATABASE_CONFIG['database']} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci") - cursor.close() - conn.close() - - # 创建peewee数据库连接 - mysql_db = MySQLDatabase( - DATABASE_CONFIG['database'], - host=DATABASE_CONFIG['host'], - port=DATABASE_CONFIG['port'], - user=DATABASE_CONFIG['user'], - password=DATABASE_CONFIG['password'], - charset=DATABASE_CONFIG['charset'] - ) - - # 测试peewee连接 - mysql_db.connect() - logger.info(f"{LOG_PREFIXES['SUCCESS']} 数据库连接成功: {DATABASE_CONFIG['host']}:{DATABASE_CONFIG['port']}/{DATABASE_CONFIG['database']}") - return True - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接失败: {e}") - return False - -def close_database(): - """ - 关闭数据库连接 - """ - global mysql_db - try: - if mysql_db and not mysql_db.is_closed(): - mysql_db.close() - logger.info(f"{LOG_PREFIXES['DATABASE']} 数据库连接已关闭") - mysql_db = None - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 关闭数据库连接时出错: {e}") - -def get_database(): - """ - 获取数据库连接实例 - - Returns: - MySQLDatabase: 数据库连接实例,如果未初始化则返回None - """ - return mysql_db - -def get_database_connection(): - """ - 获取原始的MySQL数据库连接(用于K线查看器) - - Returns: - pymysql.Connection: PyMySQL数据库连接实例 - """ - try: - import pymysql - - # 确保数据库已初始化 - if not mysql_db: - init_database() - - # 创建原始的pymysql连接 - connection = pymysql.connect( - host=DATABASE_CONFIG['host'], - port=DATABASE_CONFIG['port'], - user=DATABASE_CONFIG['user'], - password=DATABASE_CONFIG['password'], - database=DATABASE_CONFIG['database'], - charset=DATABASE_CONFIG['charset'] - ) - - logger.info(f"{LOG_PREFIXES['SUCCESS']} 原始MySQL连接创建成功") - return connection - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 创建原始MySQL连接失败: {e}") - return None - -# 基础模型类 -class BaseModel(Model): - """ - 基础模型类,所有数据表模型的父类 - """ - class Meta: - pass # 数据库连接将在子类中设置 - -def test_connection(): - """ - 测试数据库连接 - - Returns: - bool: 连接成功返回True,失败返回False - """ - try: - if init_database(): - # 执行简单查询测试连接 - if mysql_db: - result = mysql_db.execute_sql("SELECT VERSION()") - version = result.fetchone()[0] - logger.info(f"{LOG_PREFIXES['DATABASE']} MySQL版本: {version}") - return True - return False - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接测试失败: {e}") - return False diff --git a/src/data_process_model/database_manager.py b/src/data_process_model/database_manager.py deleted file mode 100644 index 5d038af..0000000 --- a/src/data_process_model/database_manager.py +++ /dev/null @@ -1,416 +0,0 @@ -""" -数据库管理器 - 统一的数据库连接和操作管理 -包含数据库配置、连接管理、原生SQL操作等底层功能 -""" - -from peewee import MySQLDatabase, Model -import logging -from typing import Dict, List, Optional, Any, Union -from decimal import Decimal -from datetime import datetime -import pandas as pd - -# 导入公共配置 -from common import LOG_PREFIXES, normalize_stock_code, get_table_name - -logger = logging.getLogger(__name__) - -# ================================ 数据库配置 ================================ - -DATABASE_CONFIG = { - 'host': 'localhost', # MySQL服务器地址 - 'port': 3306, # MySQL端口 - 'user': 'root', # 用户名 - 'password': '1234', # 密码 - 'database': 'qtrade_stock_data', # 数据库名 - 'charset': 'utf8mb4' -} - -# ================================ 数据库连接管理 ================================ - -class DatabaseManager: - """ - 数据库管理器 - 单例模式 - 负责数据库连接、原生SQL操作、事务管理等底层功能 - """ - - _instance: Optional['DatabaseManager'] = None - _database: Optional[MySQLDatabase] = None - _is_connected: bool = False - - def __new__(cls): - if cls._instance is None: - cls._instance = super(DatabaseManager, cls).__new__(cls) - return cls._instance - - def __init__(self): - if not hasattr(self, '_initialized'): - self._initialized = True - self._database: Optional[MySQLDatabase] = None - self._is_connected = False - - @property - def database(self) -> MySQLDatabase: - """获取数据库连接实例""" - if self._database is None: - self._create_connection() - - # 确保数据库连接已创建 - if self._database is None: - raise RuntimeError("数据库连接初始化失败") - - return self._database - - def _create_connection(self): - """创建数据库连接""" - try: - # 先创建数据库(如果不存在) - self._ensure_database_exists() - - # 创建 Peewee 数据库连接 - self._database = MySQLDatabase( - DATABASE_CONFIG['database'], - host=DATABASE_CONFIG['host'], - port=DATABASE_CONFIG['port'], - user=DATABASE_CONFIG['user'], - password=DATABASE_CONFIG['password'], - charset=DATABASE_CONFIG['charset'] - ) - - logger.info(f"{LOG_PREFIXES['SUCCESS']} 数据库管理器初始化成功") - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接创建失败: {e}") - raise - - def _ensure_database_exists(self): - """确保数据库存在,如果不存在则创建""" - try: - import pymysql - - temp_config = DATABASE_CONFIG.copy() - temp_config.pop('database', None) - - # 使用 pymysql 创建数据库 - conn = pymysql.connect(**temp_config) - cursor = conn.cursor() - cursor.execute(f"CREATE DATABASE IF NOT EXISTS {DATABASE_CONFIG['database']} CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci") - cursor.close() - conn.close() - - logger.info(f"{LOG_PREFIXES['DATABASE']} 数据库 {DATABASE_CONFIG['database']} 准备就绪") - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 数据库创建失败: {e}") - raise - - def connect(self) -> bool: - """连接数据库""" - try: - if not self._is_connected: - self.database.connect() - self._is_connected = True - logger.info(f"{LOG_PREFIXES['SUCCESS']} 数据库连接成功") - return True - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接失败: {e}") - return False - - def disconnect(self): - """断开数据库连接""" - try: - if self._is_connected and self._database is not None: - # 安全检查连接状态 - is_closed = self._database.is_closed() - if not (is_closed if is_closed is not None else False): - self._database.close() - self._is_connected = False - logger.info(f"{LOG_PREFIXES['DATABASE']} 数据库连接已关闭") - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 关闭数据库连接失败: {e}") - - def is_connected(self) -> bool: - """检查数据库连接状态""" - try: - if not self._is_connected or self._database is None: - return False - - # 确保 is_closed() 返回值是布尔类型 - is_closed = self._database.is_closed() - return not (is_closed if is_closed is not None else True) - except Exception: - return False - - def test_connection(self) -> bool: - """测试数据库连接""" - try: - if not self.is_connected(): - self.connect() - - if self._database is None: - logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接未初始化") - return False - - result = self._database.execute_sql("SELECT VERSION()") - version = result.fetchone()[0] - logger.info(f"{LOG_PREFIXES['DATABASE']} MySQL版本: {version}") - return True - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接测试失败: {e}") - return False - - # ================================ 表管理操作 ================================ - - def create_table(self, model_class, safe: bool = True) -> bool: - """ - 创建数据表 - - Args: - model_class: Peewee模型类 - safe: 是否安全创建(表存在时不报错) - - Returns: - bool: 创建成功返回True - """ - try: - if not self.is_connected(): - self.connect() - - model_class.create_table(safe=safe) - table_name = model_class._meta.table_name - logger.info(f"{LOG_PREFIXES['SUCCESS']} 创建表成功: {table_name}") - return True - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 创建表失败: {e}") - return False - - def drop_table(self, model_class, safe: bool = True) -> bool: - """ - 删除数据表 - - Args: - model_class: Peewee模型类 - safe: 是否安全删除(表不存在时不报错) - - Returns: - bool: 删除成功返回True - """ - try: - if not self.is_connected(): - self.connect() - - model_class.drop_table(safe=safe) - table_name = model_class._meta.table_name - logger.info(f"{LOG_PREFIXES['SUCCESS']} 删除表成功: {table_name}") - return True - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 删除表失败: {e}") - return False - - def table_exists(self, table_name: str) -> bool: - """检查表是否存在""" - try: - if not self.is_connected(): - self.connect() - - if self._database is None: - logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接未初始化") - return False - - result = self._database.execute_sql( - "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = %s AND table_name = %s", - (DATABASE_CONFIG['database'], table_name) - ) - count = result.fetchone()[0] - return count > 0 - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 检查表存在性失败: {e}") - return False - - def get_table_info(self, table_name: str) -> Dict[str, Any]: - """获取表信息""" - try: - if not self.is_connected(): - self.connect() - - if self._database is None: - logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接未初始化") - return {} - - # 获取表结构 - result = self._database.execute_sql(f"DESCRIBE {table_name}") - columns = result.fetchall() - - # 获取记录数 - count_result = self._database.execute_sql(f"SELECT COUNT(*) FROM {table_name}") - record_count = count_result.fetchone()[0] - - return { - 'table_name': table_name, - 'columns': columns, - 'record_count': record_count - } - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 获取表信息失败: {e}") - return {} - - # ================================ 数据操作 ================================ - - def batch_insert(self, model_class, data_list: List[Dict], batch_size: int = 1000) -> int: - """ - 批量插入数据 - - Args: - model_class: Peewee模型类 - data_list: 数据列表 - batch_size: 批量大小 - - Returns: - int: 成功插入的记录数 - """ - try: - if not self.is_connected(): - self.connect() - - if self._database is None: - logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接未初始化") - return 0 - - success_count = 0 - total_batches = (len(data_list) + batch_size - 1) // batch_size - - for i in range(0, len(data_list), batch_size): - batch = data_list[i:i + batch_size] - batch_num = i // batch_size + 1 - - try: - with self._database.atomic(): - model_class.insert_many(batch).execute() - success_count += len(batch) - logger.debug(f"{LOG_PREFIXES['SUCCESS']} 批次 {batch_num}/{total_batches}: 插入 {len(batch)} 条记录") - - except Exception as batch_error: - logger.warning(f"{LOG_PREFIXES['WARNING']} 批次 {batch_num} 插入失败,尝试逐条插入: {batch_error}") - - # 逐条插入 - for record in batch: - try: - with self._database.atomic(): - model_class.insert(**record).execute() - success_count += 1 - except Exception as single_error: - if "Duplicate entry" in str(single_error): - continue # 跳过重复记录 - else: - logger.warning(f"{LOG_PREFIXES['WARNING']} 单条插入失败: {single_error}") - - logger.info(f"{LOG_PREFIXES['SUCCESS']} 批量插入完成: {success_count}/{len(data_list)} 条记录") - return success_count - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 批量插入失败: {e}") - raise - - def clear_table(self, model_class) -> int: - """ - 清空表数据 - - Args: - model_class: Peewee模型类 - - Returns: - int: 删除的记录数 - """ - try: - if not self.is_connected(): - self.connect() - - table_name = model_class._meta.table_name - count_before = model_class.select().count() - - if count_before > 0: - logger.info(f"{LOG_PREFIXES['CLEANING']} 正在清空表 {table_name},当前记录数: {count_before}") - deleted_count = model_class.delete().execute() - logger.info(f"{LOG_PREFIXES['SUCCESS']} 成功清空表 {table_name},删除了 {deleted_count} 条记录") - return deleted_count - else: - logger.info(f"{LOG_PREFIXES['INFO']} 表 {table_name} 已经是空的") - return 0 - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 清空表失败: {e}") - raise - - def execute_sql(self, sql: str, params: Optional[tuple] = None) -> Any: - """ - 执行原生SQL - - Args: - sql: SQL语句 - params: 参数 - - Returns: - 查询结果 - """ - try: - if not self.is_connected(): - self.connect() - - if self._database is None: - logger.error(f"{LOG_PREFIXES['ERROR']} 数据库连接未初始化") - return None - - if params: - result = self._database.execute_sql(sql, params) - else: - result = self._database.execute_sql(sql) - - return result - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} SQL执行失败: {e}") - raise - -# ================================ 全局实例 ================================ - -# 创建全局数据库管理器实例 -db_manager = DatabaseManager() - -# 基础模型类 -class BaseModel(Model): - """基础模型类,所有数据表模型的父类""" - class Meta: - database = db_manager.database - -# 导出函数 -def get_database(): - """获取数据库实例""" - return db_manager.database - -def get_database_manager(): - """获取数据库管理器实例""" - return db_manager - -def init_database(): - """初始化数据库""" - return db_manager.test_connection() - -def close_database(): - """关闭数据库连接""" - db_manager.disconnect() - -if __name__ == "__main__": - # 测试数据库管理器 - print(f"{LOG_PREFIXES['DATABASE']} 测试数据库管理器...") - - if db_manager.test_connection(): - print(f"{LOG_PREFIXES['SUCCESS']} 数据库管理器测试成功") - else: - print(f"{LOG_PREFIXES['ERROR']} 数据库管理器测试失败") - - db_manager.disconnect() diff --git a/src/data_process_model/main.py b/src/data_process_model/main.py deleted file mode 100644 index 0f7616c..0000000 --- a/src/data_process_model/main.py +++ /dev/null @@ -1,584 +0,0 @@ -import datetime -import pandas as pd -from xtquant import xtdata -import time - -# 导入公共配置 -from common import ( - normalize_stock_code, - LOG_PREFIXES, KLINE_COLUMNS, TimeFrame, - TIME_FORMATS -) - -# 导入新的双层架构模块 -from stockdata_manager import get_stock_data_manager - -# ============== 全局配置参数 ============== -# 使用标准化的股票代码格式 -g_stock_code_list = [ - #normalize_stock_code("601658.SH"), - #normalize_stock_code("510310.SH"), - #normalize_stock_code("601398.SH"), - #normalize_stock_code("601288.SH"), - #normalize_stock_code("601609.SH"), - #normalize_stock_code("601288.SH"), - normalize_stock_code("300339.SZ") -] # 标准化后的股票代码 - -# 调整时间范围到最近的一个月,避免跨度过大导致数据获取问题 -# xtquant API 要求:支持格式 YYYYMMDD 或 YYYYMMDDhhmmss -# 若取某日全量历史数据,时间需要具体到秒,如 "20200427093000" - -# 开始时间:7月1日 09:30:00 (交易开始时间) -g_start_date = "20250101093000" - -# 结束时间选项 -# 选项1: 使用当前日期时间,精确到秒 (推荐用于获取最新数据) -current_time = datetime.datetime.now() -g_end_date = current_time.strftime("%Y%m%d%H%M%S") - -# 选项2: 手动指定确切日期时间 (推荐用于调试和稳定获取数据) -# g_end_date = "20250731150000" # 7月31日 15:00:00 (交易结束时间) - -# 选项3: 只使用日期格式(适用于日线及以上周期) -# g_start_date = "20250701" -# g_end_date = "20250731" - -print(f"{LOG_PREFIXES['TIME']} 数据范围: {g_start_date} ~ {g_end_date}") - -# 数据库插入模式配置 -# 说明:控制数据保存策略,提升插入性能 -# - "incremental": 增量模式,只插入新数据,跳过已存在的记录 (推荐) -# - "replace": 替换模式,清空表后重新插入所有数据 (适用于数据修正) -g_insert_mode = "incremental" # 恢复增量插入模式 - - -'''' - "1m", # 1分钟 - "5m", # 5分钟 - "15m", # 15分钟 - "30m", # 30分钟 - "60m", # 60分钟 - "1d", # 日线 - "1w", # 周线 - "1mon", # 月线 - "1q", # 季线 - "1hy", # 半年线 - "1y", # 年线 -]''' -# 使用公共配置中的时间周期定义 -g_period_list = [ - TimeFrame.MINUTE_1.value, # "1m" - 1分钟 - TimeFrame.MINUTE_5.value, # "5m" - 5分钟 - TimeFrame.MINUTE_15.value, # "15m" - 15分钟 - TimeFrame.MINUTE_30.value, # "30m" - 30分钟 - TimeFrame.MINUTE_60.value, # "60m" - 60分钟 (1小时) - TimeFrame.DAILY.value # "1d" - 日线 -] - -""" -'time' #时间戳 -'open' #开盘价 -'high' #最高价 -'low' #最低价 -'close' #收盘价 -'volume' #成交量 -'amount' #成交额 -'settelementPrice' #今结算 -'openInterest' #持仓量 -'preClose' #前收价 -'suspendFlag' #停牌标记 0 - 正常 1 - 停牌 -1 - 当日起复牌 -""" -g_fields = ["time", "open", "high", "low", "close", "volume", "amount"] - - -def format_time_for_xtquant(dt=None, format_type="full"): - """ - 为 xtquant API 格式化时间 - - Args: - dt (datetime): 时间对象,None 则使用当前时间 - format_type (str): 格式类型 - - "full": YYYYMMDDhhmmss (完整时间,推荐用于分钟级数据) - - "date": YYYYMMDD (仅日期,适用于日线及以上周期) - - "trading_start": 当日交易开始时间 (09:30:00) - - "trading_end": 当日交易结束时间 (15:00:00) - - Returns: - str: 格式化的时间字符串 - - Example: - >>> format_time_for_xtquant() - '20250805131045' - >>> format_time_for_xtquant(format_type="date") - '20250805' - >>> format_time_for_xtquant(format_type="trading_start") - '20250805093000' - """ - if dt is None: - dt = datetime.datetime.now() - - if format_type == "full": - return dt.strftime("%Y%m%d%H%M%S") - elif format_type == "date": - return dt.strftime("%Y%m%d") - elif format_type == "trading_start": - return dt.strftime("%Y%m%d") + "093000" - elif format_type == "trading_end": - return dt.strftime("%Y%m%d") + "150000" - else: - return dt.strftime("%Y%m%d%H%M%S") - - -def get_trading_time_range(start_date_str, end_date_str=None, time_format="full"): - """ - 获取交易时间范围 - - Args: - start_date_str (str): 开始日期,如 "20240101" - end_date_str (str): 结束日期,None 则使用当前日期 - time_format (str): 时间格式类型 - - Returns: - tuple: (start_time, end_time) 时间字符串元组 - """ - # 解析开始日期 - start_dt = datetime.datetime.strptime(start_date_str, "%Y%m%d") - start_time = format_time_for_xtquant(start_dt, "trading_start") - - # 解析结束日期 - if end_date_str: - end_dt = datetime.datetime.strptime(end_date_str, "%Y%m%d") - else: - end_dt = datetime.datetime.now() - - if time_format == "full": - end_time = format_time_for_xtquant(end_dt, "trading_end") - else: - end_time = format_time_for_xtquant(end_dt, "date") - - return start_time, end_time - - -def conv_time(ct): - """ - 将时间戳转换为格式化时间字符串 - - 将Unix毫秒时间戳转换为标准时间格式 - 使用公共配置中定义的时间格式标准 - - Args: - ct (float): Unix时间戳(毫秒),如 1476374400000 - - Returns: - str: 格式化的时间字符串,如 '20161014000000.000' - - Example: - >>> conv_time(1476374400000) - '20161014000000.000' - """ - local_time = time.localtime(ct / 1000) - data_head = time.strftime(TIME_FORMATS['COMPACT'].replace('_', ''), local_time) - data_secs = (ct - int(ct)) * 1000 - time_stamp = "%s.%03d" % (data_head, data_secs) - return time_stamp - - -def download_stock_data(stock_code, period, start_date, end_date): - """ - 下载单个股票的历史数据 - - 从xtquant数据中心下载指定股票的历史行情数据, - 支持增量下载模式,可获取指定时间段内的完整历史数据 - - Args: - stock_code (str): 单个股票代码,如 "601658.SH", "000001.SZ", "300750.SZ" - period (str): 数据周期标识,支持格式: - - 分钟级: "1m", "5m", "15m", "30m", "60m" - - 日级: "1d" - - 其他: "1w", "1M" - start_date (str): 开始日期,格式为 "YYYYMMDD" - 如 "20240101", "20231201" - end_date (str): 结束日期,格式为 "YYYYMMDD" - 如 "20241231", "20240131" - - Returns: - dict: 历史数据字典,结构如下: - { - "stock_code": { - 'time': [timestamp1, timestamp2, ...], - 'open': [price1, price2, ...], - 'high': [price1, price2, ...], - 'low': [price1, price2, ...], - 'close': [price1, price2, ...], - 'volume': [vol1, vol2, ...], - 'amount': [amt1, amt2, ...] - } - } - 如果下载失败,返回空字典或包含None值的字典 - - Raises: - Exception: 当网络连接失败或API调用异常时抛出 - - Example: - >>> data = download_stock_data("601658.SH", "1d", "20240101", "20241231") - >>> if data and "601658.SH" in data: - >>> print(f"601658.SH: {len(data['601658.SH']['time'])} 条数据") - """ - # 尝试下载数据 - try: - xtdata.download_history_data( - stock_code, - period, - start_date, - end_date, - incrementally=False, # 改为False,强制下载完整历史数据 - ) - except Exception: - try: - xtdata.download_history_data( - stock_code, - period, - start_date, - end_date, - incrementally=True, # 备用增量模式 - ) - except Exception as e: - print(f"{LOG_PREFIXES['ERROR']} {stock_code} 下载失败: {e}") - return {} - - # 获取市场数据并验证 - history_data = xtdata.get_market_data_ex( - g_fields, - [stock_code], - period=period, - start_time=start_date, - end_time=end_date, - ) - - # 简单数据验证 - if history_data and stock_code in history_data: - data = history_data[stock_code] - # 修复DataFrame布尔判断问题 - 检查数据不为空且包含必要字段 - if data is not None and 'time' in data and len(data['time']) > 0: - data_count = len(data['time']) - print(f"{LOG_PREFIXES['SUCCESS']} {stock_code}({period}): {data_count} 条记录") - - # 只显示严重的时间范围问题 - last_time = conv_time(data['time'].iloc[-1]) - actual_end = last_time[:8] - if actual_end < end_date: - print(f"{LOG_PREFIXES['WARNING']} {stock_code} 数据到 {actual_end},请求到 {end_date}") - else: - print(f"{LOG_PREFIXES['ERROR']} {stock_code} 无有效数据") - return {} - else: - print(f"{LOG_PREFIXES['ERROR']} {stock_code} 下载失败") - return {} - - return history_data - - -def process_stock_data(stock_code, stock_data): - """ - 处理单个股票的原始数据并转换为pandas DataFrame - 使用公共配置的标准时间格式和列名约定 - - Args: - stock_code (str): 股票代码,用于日志输出和错误追踪 - stock_data: 股票原始数据 - - Returns: - pd.DataFrame: 处理后的pandas DataFrame,符合公共配置的标准格式 - """ - # 转换为DataFrame(如果还不是的话) - if isinstance(stock_data, pd.DataFrame): - df = stock_data.copy() # 直接使用现有的DataFrame - else: - df = pd.DataFrame(stock_data) # 转换为DataFrame - - # 如果有时间索引,使用conv_time转换时间格式 - if not df.empty and "time" in df.columns: - # 使用conv_time函数转换时间戳 - df["time"] = df["time"].apply(conv_time) - # 再转换为pandas datetime格式并重命名为标准列名 - df[KLINE_COLUMNS['timestamp']] = pd.to_datetime(df["time"], format="%Y%m%d%H%M%S.%f") - df.set_index(KLINE_COLUMNS['timestamp'], inplace=True) - # 删除原始time列 - if "time" in df.columns: - df.drop("time", axis=1, inplace=True) - - return df - - -def save_all_to_mysql(processed_data, data_manager, current_period): - """ - 将所有处理过的股票数据保存到MySQL数据库 - 使用新的双层架构 - - Args: - processed_data (dict): 处理过的股票数据字典 {stock_code: DataFrame} - data_manager: StockDataManager实例 - current_period: 当前数据周期 - - Returns: - dict: 保存结果字典 {stock_code: record_count} - """ - mysql_records = {} - - for stock_code, df in processed_data.items(): - try: - # 使用新的架构保存数据 - count = data_manager.save_dataframe(df, stock_code, current_period, mode=g_insert_mode) - - if count > 0: - mysql_records[stock_code] = count - print(f"{LOG_PREFIXES['SUCCESS']} {stock_code} 保存 {count} 条记录到数据库") - else: - print(f"{LOG_PREFIXES['WARNING']} {stock_code} 没有新数据保存") - - except Exception as e: - print(f"{LOG_PREFIXES['ERROR']} {stock_code} 数据保存失败: {e}") - continue - - return mysql_records - - -def process_all_stocks(history_data, stock_codes): - """ - 批量处理所有股票数据,转换为DataFrame格式 - - 对历史数据字典中的每个股票进行数据处理和格式化, - 转换为标准的pandas DataFrame格式,但不进行保存操作 - - Args: - history_data (dict): 历史数据字典,包含多个股票的原始数据 - 格式: {stock_code: raw_data, ...} - 其中raw_data包含time, open, high, low, close等字段 - stock_codes (list): 需要处理的股票代码列表 - 如 ["601658.SH", "000001.SZ", "300750.SZ"] - 用于遍历和验证数据完整性 - - Returns: - dict: 处理过的股票数据字典,格式如下: - { - 'stock1': DataFrame1, - 'stock2': DataFrame2, - ... - } - 如果某个股票处理失败,对应的结果不会出现在字典中 - - Example: - >>> history_data = { - >>> "601658.SH": {"time": [123456], "close": [10.5]}, - >>> "000001.SZ": {"time": [123457], "close": [15.2]} - >>> } - >>> codes = ["601658.SH", "000001.SZ"] - >>> processed = process_all_stocks(history_data, codes) - >>> print(f"处理了 {len(processed)} 个股票") - """ - processed_data = {} - - if not history_data: - return processed_data - - for stock_code in stock_codes: - if stock_code in history_data: - stock_data = history_data[stock_code] - - # 处理单个股票数据 - df = process_stock_data(stock_code, stock_data) - - if not df.empty: - processed_data[stock_code] = df - - return processed_data - - -# 订阅行情 -def subscribe_stocks_periods(stock_codes, periods, start_time='', end_time='', count=-1): - """ - 订阅指定股票和周期的行情数据 - - Args: - stock_codes (list): 股票代码列表,如 ["601658.SH", "000001.SZ"] - periods (list): 数据周期列表,如 ["1m", "5m", "1d"] - start_time (str): 开始时间,支持格式: - - YYYYMMDD,如 "20250701" - - YYYYMMDDhhmmss,如 "20250701093000" - end_time (str): 结束时间,支持格式: - - YYYYMMDD,如 "20250731" - - YYYYMMDDhhmmss,如 "20250731150000" - count (int): 数据条数,-1表示全部数据 - - Returns: - None - """ - for stock_code in stock_codes: - for period in periods: - # xtdata.subscribe_quote(stock_code, period, start_time, end_time, count) - print(f"{LOG_PREFIXES['INFO']} 已订阅 {stock_code} 的 {period} 行情") - - -def on_data(datas): - """ - 行情数据回调函数 - - Args: - datas (dict): 接收到的行情数据 - """ - for stock_code in datas: - print(f"{LOG_PREFIXES['INFO']} 收到 {stock_code} 行情:", datas[stock_code]) - - - -def main(): - """ - 数据处理模型主程序入口函数 (批量周期模式) - 使用新的双层架构 - - 执行完整的股票数据处理流程,支持批量下载多个周期的数据, - 包括数据下载、格式化处理和MySQL数据库存储 - - 主要执行步骤: - 1. 初始化StockDataManager - 2. 循环处理所有配置的数据周期 - 3. 对每个周期下载指定股票的历史数据 - 4. 对每个股票的数据进行格式化处理(时间转换、DataFrame化) - 5. 将处理后的数据保存到MySQL数据库 - 6. 输出处理结果统计和信息 - - 全局配置依赖: - - g_stock_code_list: 股票代码列表,如 ["601658.SH", "000001.SZ"] - - g_period_list: 数据周期列表,如 ["1m", "5m", "1d", "1w"] - - g_start_date: 开始日期,如 "20240101" - - g_end_date: 结束日期,如 "20241231" - - Args: - 无参数,使用全局配置变量 - - Returns: - None: 该函数不返回值,所有结果通过控制台输出 - - Side Effects: - - 在控制台输出详细的处理进度和结果 - - 建立xtquant数据连接和MySQL数据库连接 - - 为每个周期创建对应的数据库表 - - Raises: - KeyboardInterrupt: 用户手动中断程序执行 - Exception: 数据下载、处理或数据库保存过程中的任何异常 - - Example: - >>> # 设置全局配置 - >>> g_stock_code_list = ["601658.SH", "000001.SZ"] - >>> g_period_list = ["1m", "1d", "1w"] - >>> g_start_date = "20240101" - >>> g_end_date = "20240131" - >>> - >>> # 执行主程序 - >>> main() - 🎯 数据处理模型主程序 (批量周期模式) - 📥 开始下载 3 个周期的历史数据... - ✅ 成功处理所有周期数据 - """ - data_manager = None - try: - print(f"{LOG_PREFIXES['INFO']} 数据处理启动...") - - # 演示不同的时间格式选项 - print(f"{LOG_PREFIXES['INFO']} xtquant 时间格式示例:") - print(f" - 完整时间格式: {format_time_for_xtquant(format_type='full')}") - print(f" - 日期格式: {format_time_for_xtquant(format_type='date')}") - print(f" - 交易开始时间: {format_time_for_xtquant(format_type='trading_start')}") - print(f" - 交易结束时间: {format_time_for_xtquant(format_type='trading_end')}") - - # 根据数据周期推荐时间格式 - print(f"{LOG_PREFIXES['INFO']} 推荐时间格式:") - print(" - 分钟级数据: YYYYMMDDhhmmss (具体到秒)") - print(" - 小时级数据: YYYYMMDDhhmmss 或 YYYYMMDD") - print(" - 日线及以上: YYYYMMDD (仅日期即可)") - - # 初始化股票数据管理器 - data_manager = get_stock_data_manager() - print(f"{LOG_PREFIXES['SUCCESS']} 数据管理器初始化完成") - - # 统计结果 - all_mysql_records = {} - total_periods_processed = 0 - failed_periods = [] - - # 先订阅股票 - subscribe_stocks_periods(g_stock_code_list, g_period_list, g_start_date, g_end_date) - - # 处理每个周期 - for current_period in g_period_list: - try: - print(f"\n{LOG_PREFIXES['DATABASE']} 处理周期: {current_period}") - - # 下载数据 - history_data = {} - for stock_code in g_stock_code_list: - try: - stock_history_data = download_stock_data( - stock_code, current_period, g_start_date, g_end_date - ) - # 修复DataFrame布尔判断问题 - 检查字典不为空 - if stock_history_data and isinstance(stock_history_data, dict): - history_data.update(stock_history_data) - except Exception as e: - print(f"{LOG_PREFIXES['ERROR']} {stock_code} 下载失败: {e}") - continue - - # 处理数据 - processed_data = process_all_stocks(history_data, g_stock_code_list) - if not processed_data: - failed_periods.append(current_period) - continue - - # 批量创建表 - create_results = data_manager.create_tables_for_stocks(g_stock_code_list, current_period) - success_count = sum(create_results.values()) - print(f"{LOG_PREFIXES['DATABASE']} 创建表: {success_count}/{len(g_stock_code_list)} 成功") - - # 保存到数据库 - mysql_records = save_all_to_mysql(processed_data, data_manager, current_period) - - # 统计记录 - for stock_code, count in mysql_records.items(): - key = f"{stock_code}_{current_period}" - all_mysql_records[key] = count - - total_periods_processed += 1 - - except Exception as e: - print(f"{LOG_PREFIXES['ERROR']} {current_period} 周期处理失败: {e}") - failed_periods.append(current_period) - continue - - # 显示最终结果 - if total_periods_processed > 0: - mysql_total = sum(all_mysql_records.values()) - print(f"\n{LOG_PREFIXES['SUCCESS']} 处理完成: {total_periods_processed} 周期, {mysql_total} 条记录") - else: - print(f"\n{LOG_PREFIXES['ERROR']} 所有周期处理失败") - - if failed_periods: - print(f"{LOG_PREFIXES['WARNING']} 失败周期: {', '.join(failed_periods)}") - - except KeyboardInterrupt: - print(f"\n{LOG_PREFIXES['WARNING']} 用户中断") - except Exception as e: - print(f"\n{LOG_PREFIXES['ERROR']} 程序异常: {e}") - import traceback - traceback.print_exc() - finally: - if data_manager: - data_manager.close() - print(f"{LOG_PREFIXES['DATABASE']} 数据管理器已关闭") - - - # 程序不结束 - #xtdata.run() - - -if __name__ == "__main__": - main() diff --git a/src/data_process_model/shared_memory_cache.py b/src/data_process_model/shared_memory_cache.py deleted file mode 100644 index 443ea58..0000000 --- a/src/data_process_model/shared_memory_cache.py +++ /dev/null @@ -1,423 +0,0 @@ -""" -共享内存K线数据缓存模块 -支持多进程间K线数据共享,供数据库写入程序使用 -""" - -import json -import pickle -import threading -from multiprocessing import shared_memory -from typing import Dict, Optional, Any -import pandas as pd -from datetime import datetime -import time -import logging - -# 导入公共配置 -from common import LOG_PREFIXES, get_cache_key, normalize_stock_code - -# 配置日志 -logger = logging.getLogger(__name__) - - -class SharedMemoryKlineCache: - """共享内存K线数据缓存管理器""" - - def __init__(self, cache_name: str = "qtrade_kline_cache", max_size_mb: int = 100): - """ - 初始化共享内存缓存 - - Args: - cache_name: 共享内存名称 - max_size_mb: 最大内存大小(MB) - """ - self.cache_name = cache_name - self.max_size_bytes = max_size_mb * 1024 * 1024 - self.lock = threading.Lock() - - # 尝试连接现有共享内存,如果不存在则创建 - try: - self.shm = shared_memory.SharedMemory(name=cache_name) - logger.info(f"{LOG_PREFIXES['CACHE']} 连接到现有共享内存: {cache_name}") - except FileNotFoundError: - # 创建新的共享内存 - self.shm = shared_memory.SharedMemory(name=cache_name, create=True, size=self.max_size_bytes) - # 初始化空的数据结构 - initial_data = { - 'metadata': { - 'created_time': datetime.now().isoformat(), - 'last_update': datetime.now().isoformat(), - 'version': '1.0.0' - }, - 'kline_data': {}, # {stock_code: [kline_records]} - 'status': 'initialized' - } - self._write_data_to_memory(initial_data) - logger.info(f"{LOG_PREFIXES['CACHE']} 创建新共享内存: {cache_name}, 大小: {max_size_mb}MB") - - def _write_data_to_memory(self, data: dict): - """将数据写入共享内存,支持动态扩展""" - try: - # 序列化数据 - serialized_data = pickle.dumps(data) - data_size = len(serialized_data) - - # 如果数据大小超过当前共享内存,尝试扩展 - if data_size > self.max_size_bytes: - old_size_mb = self.max_size_bytes // (1024 * 1024) - new_size_mb = max(old_size_mb * 2, (data_size // (1024 * 1024)) + 10) - logger.info(f"{LOG_PREFIXES['CACHE']} 共享内存不足,从 {old_size_mb}MB 扩展到 {new_size_mb}MB") - - if self._expand_shared_memory(new_size_mb): - logger.info(f"{LOG_PREFIXES['SUCCESS']} 共享内存扩展成功") - else: - raise ValueError(f"共享内存扩展失败,数据大小 {data_size/1024/1024:.2f}MB 超过最大限制") - - # 清空共享内存 - self.shm.buf[:] = b'\x00' * len(self.shm.buf) - - # 写入数据大小(前8字节) - size_bytes = data_size.to_bytes(8, byteorder='little') - self.shm.buf[:8] = size_bytes - - # 写入实际数据 - self.shm.buf[8:8+data_size] = serialized_data - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 写入共享内存失败: {e}") - raise - - def _expand_shared_memory(self, new_size_mb: int) -> bool: - """扩展共享内存大小""" - try: - # 保存现有数据 - existing_data = self._read_data_from_memory() - - # 关闭当前共享内存 - old_name = self.cache_name - self.shm.close() - self.shm.unlink() # 删除旧的共享内存 - - # 创建新的更大的共享内存 - self.max_size_bytes = new_size_mb * 1024 * 1024 - self.shm = shared_memory.SharedMemory( - name=old_name, - create=True, - size=self.max_size_bytes - ) - - # 恢复数据 - if existing_data: - self._write_data_to_memory(existing_data) - - return True - - except Exception as e: - print(f"❌ 扩展共享内存失败: {e}") - return False - - def _read_data_from_memory(self) -> dict: - """从共享内存读取数据""" - try: - # 读取数据大小 - size_bytes = bytes(self.shm.buf[:8]) - data_size = int.from_bytes(size_bytes, byteorder='little') - - if data_size == 0: - return {} - - # 读取实际数据 - serialized_data = bytes(self.shm.buf[8:8+data_size]) - data = pickle.loads(serialized_data) - - return data - - except Exception as e: - print(f"❌ 读取共享内存失败: {e}") - return {} - - def add_kline_data(self, stock_code: str, kline_record: dict) -> bool: - """ - 添加K线数据到共享内存 - - Args: - stock_code: 股票代码 - kline_record: K线记录字典 - - Returns: - 是否添加成功 - """ - with self.lock: - try: - # 读取现有数据 - data = self._read_data_from_memory() - - # 确保数据结构存在 - if 'kline_data' not in data: - data['kline_data'] = {} - if 'metadata' not in data: - data['metadata'] = {} - - # 添加或更新K线数据 - if stock_code not in data['kline_data']: - data['kline_data'][stock_code] = [] - - # 添加时间戳用于排序和去重 - kline_record['_added_time'] = datetime.now().isoformat() - - # 检查是否重复(基于timestamp) - existing_timestamps = { - record.get('timestamp') for record in data['kline_data'][stock_code] - } - - if kline_record.get('timestamp') not in existing_timestamps: - data['kline_data'][stock_code].append(kline_record) - - # 限制每只股票的记录数量(保留最新1000条) - if len(data['kline_data'][stock_code]) > 1000: - # 按时间戳排序并保留最新的 - data['kline_data'][stock_code].sort( - key=lambda x: x.get('timestamp', ''), reverse=True - ) - data['kline_data'][stock_code] = data['kline_data'][stock_code][:1000] - - # 更新元数据 - data['metadata']['last_update'] = datetime.now().isoformat() - data['metadata']['total_stocks'] = len(data['kline_data']) - data['metadata']['total_records'] = sum( - len(records) for records in data['kline_data'].values() - ) - - # 写回共享内存 - self._write_data_to_memory(data) - - return True - else: - return False - - except Exception as e: - print(f"❌ 添加K线数据到共享内存失败: {e}") - return False - - def add_kline_data_batch(self, stock_code: str, kline_records: list) -> int: - """ - 批量添加K线数据到共享内存(性能优化版本) - - Args: - stock_code: 股票代码 - kline_records: K线记录列表 - - Returns: - 成功添加的记录数量 - """ - with self.lock: - try: - # 读取现有数据 - data = self._read_data_from_memory() - - # 确保数据结构存在 - if 'kline_data' not in data: - data['kline_data'] = {} - if 'metadata' not in data: - data['metadata'] = {} - - if stock_code not in data['kline_data']: - data['kline_data'][stock_code] = [] - - # 获取现有时间戳集合(优化重复检查) - existing_timestamps = { - record.get('timestamp') for record in data['kline_data'][stock_code] - } - - # 批量处理新记录 - new_records = [] - for kline_record in kline_records: - if kline_record.get('timestamp') not in existing_timestamps: - # 添加时间戳用于排序 - kline_record['_added_time'] = datetime.now().isoformat() - new_records.append(kline_record) - existing_timestamps.add(kline_record.get('timestamp')) - - # 批量添加新记录 - data['kline_data'][stock_code].extend(new_records) - - # 如果记录过多,只排序一次并限制数量 - if len(data['kline_data'][stock_code]) > 1000: - data['kline_data'][stock_code].sort( - key=lambda x: x.get('timestamp', ''), reverse=True - ) - data['kline_data'][stock_code] = data['kline_data'][stock_code][:1000] - - # 更新元数据 - data['metadata']['last_update'] = datetime.now().isoformat() - data['metadata']['total_stocks'] = len(data['kline_data']) - data['metadata']['total_records'] = sum( - len(records) for records in data['kline_data'].values() - ) - - # 一次性写回共享内存 - self._write_data_to_memory(data) - - return len(new_records) - - except Exception as e: - print(f"❌ 批量添加K线数据到共享内存失败: {e}") - return 0 - - def get_kline_data(self, stock_code: Optional[str] = None, limit: int = 100) -> dict: - """ - 从共享内存获取K线数据 - - Args: - stock_code: 股票代码,None表示获取所有 - limit: 每只股票的记录限制 - - Returns: - K线数据字典 - """ - with self.lock: - try: - data = self._read_data_from_memory() - - if not data or 'kline_data' not in data: - return {} - - if stock_code: - # 获取指定股票数据 - if stock_code in data['kline_data']: - records = data['kline_data'][stock_code] - # 按时间戳排序并限制数量 - sorted_records = sorted( - records, - key=lambda x: x.get('timestamp', ''), - reverse=True - ) - return {stock_code: sorted_records[:limit]} - else: - return {} - else: - # 获取所有股票数据 - result = {} - for code, records in data['kline_data'].items(): - sorted_records = sorted( - records, - key=lambda x: x.get('timestamp', ''), - reverse=True - ) - result[code] = sorted_records[:limit] - return result - - except Exception as e: - print(f"❌ 从共享内存获取K线数据失败: {e}") - return {} - - def get_cache_status(self) -> dict: - """获取缓存状态""" - with self.lock: - try: - data = self._read_data_from_memory() - - if not data: - return {'status': 'empty', 'error': 'No data in shared memory'} - - metadata = data.get('metadata', {}) - kline_data = data.get('kline_data', {}) - - total_records = sum(len(records) for records in kline_data.values()) if kline_data else 0 - - status = { - 'status': 'active', - 'created_time': metadata.get('created_time'), - 'last_update': metadata.get('last_update'), - 'total_stocks': len(kline_data), - 'total_records': total_records, - 'memory_usage': len(pickle.dumps(data)), - 'memory_limit': self.max_size_bytes, - 'stocks_info': {} - } - - # 统计每只股票的信息 - for stock_code, records in kline_data.items(): - if records: - latest_record = max(records, key=lambda x: x.get('timestamp', '')) - status['stocks_info'][stock_code] = { - 'record_count': len(records), - 'latest_timestamp': latest_record.get('timestamp'), - 'latest_price': latest_record.get('close') - } - - return status - - except Exception as e: - return {'status': 'error', 'error': str(e)} - - def clear_cache(self, stock_code: Optional[str] = None) -> bool: - """清理缓存数据""" - with self.lock: - try: - data = self._read_data_from_memory() - - if not data or 'kline_data' not in data: - return True - - if stock_code: - # 清理指定股票 - if stock_code in data['kline_data']: - del data['kline_data'][stock_code] - print(f"🗑️ 清理共享内存中 {stock_code} 的数据") - else: - # 清理所有数据 - data['kline_data'] = {} - print("🗑️ 清理共享内存中所有K线数据") - - # 更新元数据 - data['metadata']['last_update'] = datetime.now().isoformat() - data['metadata']['total_stocks'] = len(data['kline_data']) - data['metadata']['total_records'] = sum( - len(records) for records in data['kline_data'].values() - ) - - self._write_data_to_memory(data) - return True - - except Exception as e: - print(f"❌ 清理共享内存缓存失败: {e}") - return False - - def close(self): - """关闭共享内存连接""" - try: - self.shm.close() - print(f"🔒 已关闭共享内存连接: {self.cache_name}") - except Exception as e: - print(f"❌ 关闭共享内存连接失败: {e}") - - def cleanup(self): - """清理并删除共享内存""" - try: - self.shm.close() - self.shm.unlink() - print(f"🗑️ 已删除共享内存: {self.cache_name}") - except Exception as e: - print(f"❌ 删除共享内存失败: {e}") - - -# 全局共享内存缓存实例 -shared_cache = None - - -def init_shared_cache(cache_name: str = "qtrade_kline_cache", max_size_mb: int = 100): - """初始化全局共享内存缓存""" - global shared_cache - if shared_cache is None: - shared_cache = SharedMemoryKlineCache(cache_name, max_size_mb) - print(f"🚀 初始化共享内存缓存: {cache_name}") - return shared_cache - - -def get_shared_cache(): - """获取全局共享内存缓存实例""" - global shared_cache - if shared_cache is None: - shared_cache = init_shared_cache() - return shared_cache diff --git a/src/data_process_model/stock_kline_viewer.py b/src/data_process_model/stock_kline_viewer.py deleted file mode 100644 index ea2c70b..0000000 --- a/src/data_process_model/stock_kline_viewer.py +++ /dev/null @@ -1,606 +0,0 @@ -""" -股票K线图查看器 - 重构版本,使用新的双层架构 -支持从数据库加载股票数据并绘制交互式K线图,包含技术指标 -直接使用 stockdata_manager.py 的双层架构接口 -""" - -import pandas as pd -import matplotlib.pyplot as plt -from matplotlib.patches import Rectangle -import logging -from datetime import datetime, timedelta -from typing import Dict - -# 导入新的双层架构模块 -from stockdata_manager import get_stock_data_manager -from technical_indicators import TechnicalIndicators, IndicatorParams -from common import LOG_PREFIXES - -# 配置日志 -logging.basicConfig(level=logging.INFO) -logger = logging.getLogger(__name__) - - -class KlineChartRenderer: - """ - K线图表渲染器 - 重构版本 - 专门负责图表的绘制和显示,通过参数接收预计算的技术指标数据 - """ - - def __init__(self): - """初始化图表渲染器""" - # 设置中文字体 - plt.rcParams['font.sans-serif'] = ['SimHei'] - plt.rcParams['axes.unicode_minus'] = False - - # 设置黑色背景主题 - plt.rcParams['figure.facecolor'] = 'black' # 图表整体背景 - plt.rcParams['axes.facecolor'] = 'black' # 子图背景 - plt.rcParams['axes.edgecolor'] = 'white' # 坐标轴边框颜色 - plt.rcParams['axes.labelcolor'] = 'white' # 坐标轴标签颜色 - plt.rcParams['xtick.color'] = 'white' # x轴刻度颜色 - plt.rcParams['ytick.color'] = 'white' # y轴刻度颜色 - plt.rcParams['text.color'] = 'white' # 文本颜色 - plt.rcParams['grid.color'] = 'gray' # 网格线颜色 - plt.rcParams['grid.alpha'] = 0.3 # 网格线透明度 - - # 图表配置 - self.figure_size = (15, 10) - - logger.info("🎨 KlineChartRenderer 初始化完成") - - def render_chart(self, df, stock_code, period, indicators_data=None, - show_volume=True, show_macd=True, show_ma=True, - params=None, default_window=100): - """ - 渲染K线图表 - 重构版本,接收预计算的技术指标数据 - - Args: - df (pd.DataFrame): K线数据 - stock_code (str): 股票代码 - period (str): 据周期 - indicators_data (Dict): 预计算的技术指标数据 - show_volume (bool): 是否显示成交量 - show_macd (bool): 是否显示MACD指标 - show_ma (bool): 是否显示移动平均线 - params (IndicatorParams): 技术指标参数配置,None则使用默认参数 - default_window (int): 默认显示的K线数量,0表示显示全部 - - Returns: - bool: 渲染是否成功 - """ - try: - if df is None or df.empty: - logger.error("❌ 没有数据可绘制") - return False - - logger.info(f"🎨 开始绘制K线图 - {stock_code} ({period})") - - # 设置默认参数 - if params is None and IndicatorParams is not None: - params = IndicatorParams() - - # 使用传入的技术指标数据 - if indicators_data is None: - indicators_data = {} - - # 创建画布和子图布局 - subplot_count = 1 + (1 if show_volume else 0) + (1 if show_macd else 0) - fig, axes = plt.subplots(subplot_count, 1, figsize=self.figure_size, - gridspec_kw={'height_ratios': [3, 1, 1][:subplot_count]}) - - if subplot_count == 1: - axes = [axes] - plt.subplots_adjust(hspace=0.3) - - # 绘制K线图 (主图) - ax_main = axes[0] - self._plot_candlestick(ax_main, df) - - # 绘制移动平均线 - if show_ma and 'ma' in indicators_data: - self._plot_ma_lines_simple(ax_main, indicators_data['ma'], params) - - # 设置主图标题和标签 - title = f'{stock_code} K线图 ({period}周期) - 数据总数: {len(df)}条' - if show_macd and params: - title += f' | MACD({params.macd_fast},{params.macd_slow},{params.macd_signal})' - ax_main.set_title(title, fontsize=16, fontweight='bold') - ax_main.set_ylabel('价格 (元)', fontsize=12) - ax_main.grid(True, alpha=0.3) - - # 绘制成交量 - axis_idx = 1 - if show_volume: - self._plot_volume(axes[axis_idx], df) - axes[axis_idx].set_ylabel('成交量', fontsize=12) - axes[axis_idx].grid(True, alpha=0.3) - axis_idx += 1 - - # 绘制MACD - if show_macd and 'macd' in indicators_data: - self._plot_macd_simple(axes[axis_idx], indicators_data['macd'], params) - axes[axis_idx].set_ylabel('MACD', fontsize=12) - axes[axis_idx].grid(True, alpha=0.3) - - # 设置时间轴 - 为所有子图设置时间轴 - for i, ax in enumerate(axes): - self._setup_time_axis(ax, df.index, is_last_subplot=(i == len(axes)-1)) - - # 确保所有子图的x轴范围一致 - x_min, x_max = -0.5, len(df) - 0.5 - for ax in axes: - ax.set_xlim(x_min, x_max) - - # 设置默认显示窗口 - if default_window > 0 and len(df) > default_window: - start_idx = len(df) - default_window - end_idx = len(df) - 1 - for ax in axes: - ax.set_xlim(start_idx, end_idx) - logger.info(f"📊 默认显示最近 {default_window} 根K线 (共{len(df)}根)") - - # 显示图表 - plt.tight_layout() - logger.info("📈 K线图已显示") - - # 显示提示信息 - self._show_usage_tips(stock_code, default_window, len(df), params) - - plt.show(block=False) - input("\n按回车键关闭图表窗口...") - plt.close() - - logger.info("✅ K线图绘制完成") - return True - - except Exception as e: - logger.error(f"❌ 绘制K线图失败: {e}") - import traceback - traceback.print_exc() - return False - - def _plot_candlestick(self, ax, df): - """绘制蜡烛图(K线)""" - df_reset = df.reset_index() - - for i, row in df_reset.iterrows(): - # 确定K线颜色 (红涨绿跌) - if row['close'] >= row['open']: - color = 'red' - height = row['close'] - row['open'] - body_bottom = row['open'] - else: - color = 'green' - height = row['open'] - row['close'] - body_bottom = row['close'] - - # 绘制K线实体 - if height > 0: - ax.add_patch(Rectangle((i-0.3, body_bottom), 0.6, height, - facecolor=color, edgecolor=color, alpha=0.8)) - else: - ax.plot([i-0.3, i+0.3], [row['open'], row['open']], color=color, linewidth=2) - - # 绘制上下影线 - if row['high'] > max(row['open'], row['close']): - ax.plot([i, i], [max(row['open'], row['close']), row['high']], color=color, linewidth=1) - if row['low'] < min(row['open'], row['close']): - ax.plot([i, i], [row['low'], min(row['open'], row['close'])], color=color, linewidth=1) - - # 设置坐标轴范围 - 不在这里设置xlim,由主函数统一设置 - price_min = df['low'].min() - price_max = df['high'].max() - price_range = price_max - price_min - ax.set_ylim(price_min - price_range * 0.05, price_max + price_range * 0.05) - - def _plot_ma_lines_simple(self, ax, ma_dict, params): - """绘制移动平均线 - 简化版本""" - if not ma_dict: - return - - # MA线颜色配置:5日白色,10日黄色,20日粉色,30日荧光绿,60日荧光蓝 - ma_colors = { - 5: 'white', # 5日线:白色 - 10: 'yellow', # 10日线:黄色 - 20: 'magenta', # 20日线:粉色 - 30: 'lime', # 30日线:荧光绿 - 60: 'cyan' # 60日线:荧光蓝 - } - ma_periods = params.ma_periods if params else [5, 10, 20, 30, 60] - - for i, period_val in enumerate(ma_periods): - ma_key = f'ma{period_val}' - if ma_key in ma_dict: - # 使用预定义的颜色,如果没有则使用默认颜色 - color = ma_colors.get(period_val, 'gray') - ma_series = ma_dict[ma_key] - - # 处理不同的数据类型(numpy array 或 pandas Series) - if hasattr(ma_series, 'values'): - # pandas Series - ma_values = ma_series.values - else: - # numpy array - ma_values = ma_series - - # 过滤掉NaN值 - valid_mask = ~pd.isna(ma_values) - if valid_mask.any(): - x_indices = range(len(ma_values)) - ax.plot([x for x, valid in zip(x_indices, valid_mask) if valid], - [val for val, valid in zip(ma_values, valid_mask) if valid], - color=color, linewidth=1.5, alpha=0.8, label=f'MA{period_val}') - - # 添加图例 - ax.legend(loc='upper left', fontsize=9) - - def _plot_volume(self, ax, df): - """绘制成交量柱状图""" - df_reset = df.reset_index() - colors = ['red' if close >= open_price else 'green' - for close, open_price in zip(df_reset['close'], df_reset['open'])] - - ax.bar(range(len(df_reset)), df_reset['volume'], color=colors, alpha=0.6, width=0.8) - # 不在这里设置xlim,由主函数统一设置 - - def _plot_macd_simple(self, ax, macd_dict, params): - """绘制MACD指标 - 简化版本""" - if not macd_dict: - return - - macd_line = macd_dict['macd'] - signal_line = macd_dict['signal'] - histogram = macd_dict['histogram'] - - x_range = range(len(macd_line)) - - # 绘制MACD线和信号线 - ax.plot(x_range, macd_line, label='MACD', color='white', linewidth=1.5) - ax.plot(x_range, signal_line, label='Signal', color='yellow', linewidth=1.5) - - # 绘制MACD柱状图 - colors = ['red' if h >= 0 else 'green' for h in histogram] - ax.bar(x_range, histogram, color=colors, alpha=0.6, width=0.8, label='Histogram') - - # 添加零轴线 - ax.axhline(y=0, color='white', linestyle='-', alpha=0.5) - - # 设置图例 - if params: - legend_label = f"MACD({params.macd_fast},{params.macd_slow},{params.macd_signal})" - else: - legend_label = "MACD(12,26,9)" - ax.legend([legend_label, 'Signal', 'Histogram'], loc='upper left', fontsize=10) - # 不在这里设置xlim,由主函数统一设置 - - def _setup_time_axis(self, ax, time_index, is_last_subplot=True): - """设置时间轴格式""" - step = max(1, len(time_index) // 8) - time_labels = [] - tick_positions = [] - - for i in range(0, len(time_index), step): - if i < len(time_index): - time_val = time_index[i] - if hasattr(time_val, 'strftime'): - # 根据数据密度调整时间格式 - if step > 20: # 数据较多时只显示月-日 - time_labels.append(time_val.strftime('%m-%d')) - else: # 数据较少时显示月-日 - time_labels.append(time_val.strftime('%m-%d')) - else: - time_labels.append(str(time_val)) - tick_positions.append(i) - - ax.set_xticks(tick_positions) - - # 所有子图都显示时间标签,但只在最后一个显示xlabel - if is_last_subplot: - ax.set_xticklabels(time_labels, rotation=45, ha='right', fontsize=10) - ax.set_xlabel('时间', fontsize=12) - else: - # 上面的子图显示简化的时间标签 - ax.set_xticklabels(time_labels, rotation=45, ha='right', fontsize=9) - ax.tick_params(axis='x', which='major', labelsize=9) - - def _show_usage_tips(self, stock_code, default_window, total_count, params): - """显示使用提示""" - window_size = min(default_window, total_count) if default_window else total_count - print(f"\n{'='*80}") - print(f"📊 {stock_code} K线图 已显示 (最近{window_size}根K线,共{total_count}根)") - print(f"{'='*80}") - print("🎯 图表导航说明:") - print("📱 鼠标操作:") - print(" • 滚轮缩放图表") - print(" • 右键拖拽平移图表") - print(" • 左键点击查看具体数值") - print("🛠️ 工具栏:") - print(" • 点击工具栏按钮可进行缩放、平移、配置等操作") - print(" • Home键可快速回到全览视图") - if params: - print(f"📊 技术指标参数: MA{params.ma_periods}, MACD({params.macd_fast},{params.macd_slow},{params.macd_signal})") - print("💡 提示: 关闭图表窗口继续程序...") - print(f"{'='*80}") - - -class StockKlineViewer: - """ - 股票K线图查看器 - 重构版本 - 使用新的双层架构(stockdata_manager + database_manager)获取数据和计算技术指标 - """ - - def __init__(self): - """初始化K线查看器""" - try: - # 使用新的双层架构 - self.data_manager = get_stock_data_manager() - self.technical_indicators = TechnicalIndicators() - logger.info(f"{LOG_PREFIXES['SUCCESS']} 数据管理器初始化完成") - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 数据管理器初始化失败: {e}") - self.data_manager = None - self.technical_indicators = None - - self.chart_renderer = KlineChartRenderer() - logger.info("🚀 StockKlineViewer 初始化完成") - - @staticmethod - def get_time_range(days_back=None, start_date=None, end_date=None): - """ - 获取时间范围的便捷方法 - - Args: - days_back (int): 往前多少天,如30表示最近30天 - start_date (str): 手动指定开始日期,格式'YYYY-MM-DD' - end_date (str): 手动指定结束日期,格式'YYYY-MM-DD' - - Returns: - tuple: (start_date, end_date) - """ - if start_date and end_date: - return start_date, end_date - elif days_back: - end_date = datetime.now().strftime('%Y-%m-%d') - start_date = (datetime.now() - timedelta(days=days_back)).strftime('%Y-%m-%d') - return start_date, end_date - else: - return None, None # 返回全部数据 - - def get_price_info(self, stock_code: str, period: str = "1d") -> Dict: - """ - 获取股票价格信息摘要 - - Args: - stock_code: 股票代码 - period: 时间周期 - - Returns: - Dict: 包含最新价格、涨跌幅、数据范围等信息 - """ - try: - if self.data_manager is None: - return {} - - # 获取最新几条数据计算涨跌幅 - latest_df = self.data_manager.get_latest_data(stock_code, period, count=2) - - if latest_df.empty: - return {} - - latest_price = float(latest_df['close'].iloc[-1]) - - # 计算涨跌幅 - change_pct = 0.0 - if len(latest_df) >= 2: - prev_close = float(latest_df['close'].iloc[-2]) - if prev_close > 0: - change_pct = ((latest_price - prev_close) / prev_close) * 100 - - # 获取数据范围 - data_range_info = self.data_manager.get_data_range(stock_code, period) - date_range = "无数据" - if data_range_info: - start_date = data_range_info.get('start_date', '') - end_date = data_range_info.get('end_date', '') - if start_date and end_date: - date_range = f"{start_date} ~ {end_date}" - - return { - 'latest_price': latest_price, - 'change_pct': change_pct, - 'date_range': date_range - } - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 获取价格信息失败: {e}") - return {} - - def calculate_indicators(self, df: pd.DataFrame, params = None): - """ - 计算技术指标 - - Args: - df: K线数据DataFrame - params: 技术指标参数 - - Returns: - Dict: 包含MA和MACD指标的字典 - """ - try: - if self.technical_indicators is None or df.empty: - return {} - - if params is None: - params = IndicatorParams() - - indicators = {} - - # 计算移动平均线 - ma_data = self.technical_indicators.ma_from_df(df, params.ma_periods) - if ma_data: - indicators['ma'] = ma_data - - # 计算MACD - macd_data = self.technical_indicators.macd_from_df( - df, - fast=params.macd_fast, - slow=params.macd_slow, - signal=params.macd_signal - ) - - if macd_data: - indicators['macd'] = macd_data - - return indicators - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 计算技术指标失败: {e}") - return {} - - def show_kline_chart(self, stock_code, period='1d', start_date=None, end_date=None, - show_volume=True, show_macd=True, show_ma=True, params=None): - """ - 显示K线图表 - 重构版本,使用新的双层架构 - - Args: - stock_code (str): 股票代码 - period (str): 数据周期 - start_date (str): 开始日期 - end_date (str): 结束日期 - show_volume (bool): 是否显示成交量 - show_macd (bool): 是否显示MACD指标 - show_ma (bool): 是否显示移动平均线 - params (IndicatorParams): 技术指标参数配置 - - Returns: - bool: 显示是否成功 - """ - try: - if self.data_manager is None: - logger.error(f"{LOG_PREFIXES['ERROR']} 数据管理器不可用,无法显示K线图") - return False - - # 转换日期格式 - start_dt = None - end_dt = None - if start_date: - start_dt = datetime.strptime(start_date, '%Y-%m-%d') - if end_date: - end_dt = datetime.strptime(end_date, '%Y-%m-%d') - - # 通过新的双层架构获取K线数据 - df = self.data_manager.read_stock_data( - stock_code=stock_code, - period=period, - start_date=start_dt, - end_date=end_dt - ) - - if df.empty: - logger.error(f"{LOG_PREFIXES['ERROR']} 没有找到数据") - return False - - # 计算技术指标 - indicators_data = {} - if show_ma or show_macd: - indicators_data = self.calculate_indicators(df, params) - if indicators_data: - logger.info(f"{LOG_PREFIXES['SUCCESS']} 技术指标计算完成") - else: - logger.warning(f"{LOG_PREFIXES['WARNING']} 技术指标计算失败") - - # 渲染图表 - return self.chart_renderer.render_chart( - df, stock_code, period, indicators_data, - show_volume, show_macd, show_ma, params, default_window=150 - ) - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 显示K线图失败: {e}") - import traceback - traceback.print_exc() - return False - - -def main(): - """主函数 - 演示K线图查看器的使用,重构版本""" - print("📈 股票K线图查看器 - 重构版本 (使用新双层架构)") - print("=" * 60) - - # 创建K线查看器 - viewer = StockKlineViewer() - - # 检查数据管理器是否可用 - if viewer.data_manager is None: - print("❌ 数据管理器初始化失败") - return - - print("✅ 数据管理器已就绪") - print(f"{LOG_PREFIXES['DATABASE']} 使用新的双层架构 (stockdata_manager + database_manager)") - - # 测试股票代码列表 - test_stocks = ['601658.SH', '601398.SH'] - test_period = '60m' - - # 方式1: 设置具体的起止时间 - start_date, end_date = '2025-01-01', '2025-07-28' - - # 方式2: 使用便捷方法获取最近N天的数据 - # start_date, end_date = viewer.get_time_range(days_back=30) # 最近30天 - # start_date, end_date = viewer.get_time_range(days_back=90) # 最近90天 - - # 方式3: 获取全部数据 - # start_date, end_date = viewer.get_time_range() # 全部数据 - - # 创建指标参数配置 - params = IndicatorParams( - ma_periods=[5, 10, 20, 30, 60], # 移动平均线周期:5日、10日、20日、30日、60日 - macd_fast=6, # MACD快线 - macd_slow=13, # MACD慢线 - macd_signal=5 # MACD信号线 - ) - - print(f"📅 数据时间范围: {start_date} ~ {end_date if end_date else '最新数据'}") - print(f"📊 技术指标配置: MA{params.ma_periods}, MACD({params.macd_fast},{params.macd_slow},{params.macd_signal})") - - for stock_code in test_stocks: - print(f"\n🔍 查看股票: {stock_code} ({test_period})") - - # 先获取价格信息摘要 - try: - price_info = viewer.get_price_info(stock_code, test_period) - if price_info: - print(f"💰 最新价格: {price_info['latest_price']:.4f}") - print(f"📈 涨跌幅: {price_info['change_pct']:.2f}%") - print(f"📊 数据范围: {price_info['date_range']}") - except Exception as e: - logger.warning(f"{LOG_PREFIXES['WARNING']} 获取价格信息失败: {e}") - - # 显示K线图 - success = viewer.show_kline_chart( - stock_code=stock_code, - period=test_period, - start_date=start_date, # 开始时间 - end_date=end_date, # 结束时间 - show_volume=True, - show_macd=True, - show_ma=True, - params=params - ) - - if success: - print(f"✅ {stock_code} K线图显示完成") - else: - print(f"❌ {stock_code} K线图显示失败") - - # 询问是否继续 - user_input = input("\n继续查看下一个股票? (y/n, 默认y): ").strip().lower() - if user_input == 'n': - break - - print("\n👋 程序结束") - - -if __name__ == "__main__": - main() diff --git a/src/data_process_model/stock_models.py b/src/data_process_model/stock_models.py deleted file mode 100644 index 8552b85..0000000 --- a/src/data_process_model/stock_models.py +++ /dev/null @@ -1,115 +0,0 @@ -""" -股票K线数据模型 - 纯粹的 ORM 模型定义 -只负责数据模型的定义与约束,不包含数据库操作逻辑 -""" - -from typing import Dict -from peewee import DateTimeField, DecimalField, BigIntegerField -try: - from database_config import BaseModel, get_database -except ImportError: - from .database_config import BaseModel, get_database -from database_manager import BaseModel, get_database - -# 导入公共配置 -from common import ( - normalize_stock_code, get_table_name, LOG_PREFIXES -) - -import logging - - -logger = logging.getLogger(__name__) - -class StockKlineBase(BaseModel): - """ - 股票K线数据基础模型 - 遵循公共配置的字段命名约定和数据类型定义 - """ - # 时间戳字段 - 使用公共配置的列名 - timestamp = DateTimeField(primary_key=True, help_text="K线时间戳") - - # OHLCV数据 - 使用Decimal确保精度,遵循公共配置的字段名称 - open = DecimalField(max_digits=10, decimal_places=3, help_text="开盘价") - high = DecimalField(max_digits=10, decimal_places=3, help_text="最高价") - low = DecimalField(max_digits=10, decimal_places=3, help_text="最低价") - close = DecimalField(max_digits=10, decimal_places=3, help_text="收盘价") - volume = BigIntegerField(help_text="成交量") - amount = DecimalField(max_digits=20, decimal_places=2, help_text="成交额", null=True) - -# 支持的K线周期常量 -SUPPORTED_PERIODS = ['1m', '15m', '30m', '60m', '1d'] # 添加1d用于回测数据 - -def create_stock_kline_model(stock_code: str, period: str): - """ - 动态创建股票K线数据表模型 - 专门用于创建1分钟、15分钟、30分钟、60分钟周期的K线数据模型 - - Args: - stock_code (str): 股票代码,如 "601398.SH", "000001.SZ" - period (str): 数据周期,支持 "1m", "15m", "30m", "60m" - - Returns: - type: 动态创建的股票K线模型类 - - Raises: - ValueError: 当股票代码格式不正确或周期不支持时 - """ - # 验证周期参数 - if period not in SUPPORTED_PERIODS: - raise ValueError(f"不支持的周期: {period},支持的周期为: {SUPPORTED_PERIODS}") - - # 使用公共配置标准化股票代码 - normalized_code = normalize_stock_code(stock_code) - - # 生成表名:kline_{股票代码}_{周期} - # 例如:601398.SH + 15m -> kline_601398_sh_15m - code_part = normalized_code.lower().replace('.', '_') # 601398.SH -> 601398_sh - table_name = f"kline_{code_part}_{period}" - - # 生成类名 - clean_code = normalized_code.lower().replace(".", "_") - class_name = f"StockKline_{clean_code}_{period}" - - # 动态创建模型类 - model_class = type(class_name, (StockKlineBase,), { - '__module__': __name__, - 'Meta': type('Meta', (), { - 'table_name': table_name, - 'database': get_database() - }), - 'stock_code': normalized_code, # 保存标准化后的股票代码 - 'period': period, # 保存时间周期 - }) - - logger.info(f"{LOG_PREFIXES['DATABASE']} 创建股票K线模型: {class_name} -> {table_name}") - return model_class - -def create_all_timeframe_models(stock_code: str) -> Dict[str, type]: - """ - 为指定股票创建所有时间周期的K线模型 - - Args: - stock_code (str): 股票代码,如 "601398.SH" - - Returns: - Dict[str, type]: 时间周期到模型类的映射字典 - """ - models = {} - for period in SUPPORTED_PERIODS: - try: - models[period] = create_stock_kline_model(stock_code, period) - logger.info(f"{LOG_PREFIXES['DATABASE']} 成功创建 {stock_code} {period} 模型") - except Exception as e: - logger.error(f"{LOG_PREFIXES['DATABASE']} 创建 {stock_code} {period} 模型失败: {e}") - - return models - -# 其他可能的模型类可以在这里定义 -# class StockInfo(BaseModel): -# """股票基本信息模型""" -# pass -# -# class TradingCalendar(BaseModel): -# """交易日历模型""" -# pass diff --git a/src/data_process_model/stockdata_manager.py b/src/data_process_model/stockdata_manager.py deleted file mode 100644 index d4eef5c..0000000 --- a/src/data_process_model/stockdata_manager.py +++ /dev/null @@ -1,474 +0,0 @@ -""" -股票数据管理器 - DataFrame ↔ 数据库转换层 -负责将数据库中的数据转换为DataFrame格式,以及将DataFrame数据写入数据库 -调用 database_manager.py 提供的底层功能 -""" - -import pandas as pd -import logging -from typing import Dict, List, Optional, Any -from decimal import Decimal -from datetime import datetime - -# 导入底层依赖 -from database_manager import get_database_manager -from stock_models import create_stock_kline_model - -# 导入公共配置 -from common import ( - normalize_stock_code, get_table_name, - validate_kline_data, LOG_PREFIXES -) - -logger = logging.getLogger(__name__) - -class StockDataManager: - """ - 股票数据管理器 - - 职责: - 1. 从数据库读取K线数据并转换为DataFrame - 2. 将DataFrame格式的K线数据写入数据库 - 3. 提供数据查询、过滤、聚合等功能 - 4. 管理股票表的创建和维护 - """ - - def __init__(self): - """初始化股票数据管理器""" - self.db_manager = get_database_manager() - self.model_cache = {} # 缓存已创建的模型类 - - # 确保数据库连接 - if not self.db_manager.is_connected(): - self.db_manager.connect() - - logger.info(f"{LOG_PREFIXES['SUCCESS']} 股票数据管理器初始化完成") - - # ================================ 模型管理 ================================ - - def get_stock_model(self, stock_code: str, period: str = "1d"): - """ - 获取或创建股票K线模型类 - - Args: - stock_code: 股票代码 - period: 时间周期 - - Returns: - 股票K线模型类 - """ - # 标准化股票代码 - normalized_code = normalize_stock_code(stock_code) - model_key = f"{normalized_code}_{period}" - - # 从缓存获取 - if model_key in self.model_cache: - return self.model_cache[model_key] - - # 创建新模型 - model_class = create_stock_kline_model(normalized_code, period) - self.model_cache[model_key] = model_class - - return model_class - - def create_table(self, stock_code: str, period: str = "1d") -> bool: - """ - 创建股票K线数据表 - - Args: - stock_code: 股票代码 - period: 时间周期 - - Returns: - bool: 创建成功返回True - """ - try: - model_class = self.get_stock_model(stock_code, period) - success = self.db_manager.create_table(model_class, safe=True) - - if success: - table_name = get_table_name(normalize_stock_code(stock_code), period) - logger.info(f"{LOG_PREFIXES['SUCCESS']} 创建表成功: {table_name}") - - return success - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 创建表失败: {stock_code} ({period}) - {e}") - return False - - def create_tables_for_stocks(self, stock_codes: List[str], period: str = "1d") -> Dict[str, bool]: - """ - 批量创建股票表 - - Args: - stock_codes: 股票代码列表 - period: 时间周期 - - Returns: - Dict[str, bool]: 创建结果 {stock_code: success} - """ - results = {} - logger.info(f"{LOG_PREFIXES['DATABASE']} 开始批量创建 {len(stock_codes)} 个股票表...") - - for stock_code in stock_codes: - results[stock_code] = self.create_table(stock_code, period) - - success_count = sum(results.values()) - logger.info(f"{LOG_PREFIXES['SUCCESS']} 批量创建完成: {success_count}/{len(stock_codes)} 个表创建成功") - - return results - - # ================================ 数据读取 ================================ - - def read_stock_data(self, - stock_code: str, - period: str = "1d", - start_date: Optional[datetime] = None, - end_date: Optional[datetime] = None, - limit: Optional[int] = None) -> pd.DataFrame: - """ - 从数据库读取股票K线数据并转换为DataFrame - - Args: - stock_code: 股票代码 - period: 时间周期 - start_date: 开始日期 - end_date: 结束日期 - limit: 限制返回记录数 - - Returns: - pd.DataFrame: K线数据DataFrame,以timestamp为索引 - """ - try: - # 获取模型类 - model_class = self.get_stock_model(stock_code, period) - - # 构建查询 - query = model_class.select() - - # 添加时间范围过滤 - if start_date: - query = query.where(model_class.timestamp >= start_date) - if end_date: - query = query.where(model_class.timestamp <= end_date) - - # 按时间排序 - query = query.order_by(model_class.timestamp) - - # 添加限制 - if limit: - query = query.limit(limit) - - # 执行查询 - records = list(query) - - if not records: - logger.warning(f"{LOG_PREFIXES['WARNING']} 未找到数据: {stock_code} ({period})") - return pd.DataFrame() - - # 转换为DataFrame - data = [] - for record in records: - data.append({ - 'timestamp': record.timestamp, - 'open': float(record.open), - 'high': float(record.high), - 'low': float(record.low), - 'close': float(record.close), - 'volume': record.volume, - 'amount': float(record.amount) if record.amount else 0.0 - }) - - df = pd.DataFrame(data) - df.set_index('timestamp', inplace=True) - - logger.info(f"{LOG_PREFIXES['SUCCESS']} 成功读取 {len(df)} 条K线数据: {stock_code} ({period})") - - return df - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 读取股票数据失败: {stock_code} ({period}) - {e}") - return pd.DataFrame() - - def get_existing_timestamps(self, stock_code: str, period: str = "1d", - start_date: Optional[datetime] = None, - end_date: Optional[datetime] = None) -> set: - """ - 获取数据库中已存在的时间戳集合 - - Args: - stock_code: 股票代码 - period: 时间周期 - start_date: 开始日期 - end_date: 结束日期 - - Returns: - set: 时间戳集合 - """ - try: - model_class = self.get_stock_model(stock_code, period) - - query = model_class.select(model_class.timestamp) - - if start_date: - query = query.where(model_class.timestamp >= start_date) - if end_date: - query = query.where(model_class.timestamp <= end_date) - - timestamps = {record.timestamp for record in query} - - logger.debug(f"{LOG_PREFIXES['DATABASE']} 查询到 {len(timestamps)} 个已存在时间戳") - - return timestamps - - except Exception as e: - logger.warning(f"{LOG_PREFIXES['WARNING']} 查询已存在时间戳失败: {e}") - return set() - - # ================================ 数据写入 ================================ - - def save_dataframe(self, df: pd.DataFrame, stock_code: str, period: str = "1d", - mode: str = "append", batch_size: int = 1000) -> int: - """ - 将DataFrame保存到数据库 - - Args: - df: K线数据DataFrame - stock_code: 股票代码 - period: 时间周期 - mode: 保存模式 ("append" 增量追加, "replace" 替换模式) - batch_size: 批量大小 - - Returns: - int: 成功插入的记录数 - """ - # 数据验证 - if not validate_kline_data(df): - logger.error(f"{LOG_PREFIXES['ERROR']} DataFrame数据验证失败") - return 0 - - # 确保表存在 - if not self.create_table(stock_code, period): - logger.error(f"{LOG_PREFIXES['ERROR']} 创建表失败,无法保存数据") - return 0 - - # 获取模型类 - model_class = self.get_stock_model(stock_code, period) - - if mode == "replace": - return self._save_replace_mode(df, model_class, batch_size) - else: - return self._save_append_mode(df, model_class, batch_size) - - def _save_append_mode(self, df: pd.DataFrame, model_class, batch_size: int) -> int: - """增量追加模式保存""" - try: - # 查询已存在的时间戳 - min_time = df.index.min() - max_time = df.index.max() - - # 获取表名进行查询(通过模型实例获取) - instance = model_class() - existing_timestamps = self.get_existing_timestamps( - instance.stock_code, instance.period, min_time, max_time - ) - - # 过滤出新数据 - new_data = [] - for timestamp, row in df.iterrows(): - # 确保timestamp是datetime类型 - if isinstance(timestamp, pd.Timestamp): - timestamp = timestamp.to_pydatetime() - if timestamp not in existing_timestamps: - new_data.append(self._row_to_dict(timestamp, row)) - - if not new_data: - logger.info(f"{LOG_PREFIXES['INFO']} 没有新数据需要插入") - return 0 - - # 批量插入 - success_count = self.db_manager.batch_insert(model_class, new_data, batch_size) - - total_records = len(df) - skipped_records = total_records - len(new_data) - - logger.info(f"{LOG_PREFIXES['SUCCESS']} 增量保存完成: 新增 {success_count}/{len(new_data)} 条,跳过重复 {skipped_records} 条") - - return success_count - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 增量保存失败: {e}") - raise - - def _save_replace_mode(self, df: pd.DataFrame, model_class, batch_size: int) -> int: - """替换模式保存""" - try: - # 清空表 - self.db_manager.clear_table(model_class) - - # 准备所有数据 - all_data = [] - for timestamp, row in df.iterrows(): - # 确保timestamp是datetime类型 - if isinstance(timestamp, pd.Timestamp): - timestamp = timestamp.to_pydatetime() - all_data.append(self._row_to_dict(timestamp, row)) - - # 批量插入 - success_count = self.db_manager.batch_insert(model_class, all_data, batch_size) - - logger.info(f"{LOG_PREFIXES['SUCCESS']} 替换模式保存完成: 插入 {success_count}/{len(all_data)} 条记录") - - return success_count - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 替换模式保存失败: {e}") - raise - - def _row_to_dict(self, timestamp, row: pd.Series) -> Dict[str, Any]: - """将DataFrame行转换为字典""" - # 确保timestamp是datetime类型 - if isinstance(timestamp, pd.Timestamp): - timestamp = timestamp.to_pydatetime() - - return { - 'timestamp': timestamp, - 'open': Decimal(str(row['open'])), - 'high': Decimal(str(row['high'])), - 'low': Decimal(str(row['low'])), - 'close': Decimal(str(row['close'])), - 'volume': int(row['volume']), - 'amount': Decimal(str(row['amount'])) if 'amount' in row and pd.notna(row['amount']) else Decimal('0') - } - - # ================================ 数据查询和分析 ================================ - - def get_latest_data(self, stock_code: str, period: str = "1d", count: int = 1) -> pd.DataFrame: - """获取最新的K线数据""" - try: - model_class = self.get_stock_model(stock_code, period) - - records = list( - model_class.select() - .order_by(model_class.timestamp.desc()) - .limit(count) - ) - - if not records: - return pd.DataFrame() - - # 转换为DataFrame并按时间正序排列 - data = [] - for record in reversed(records): # 反转以获得正序 - data.append({ - 'timestamp': record.timestamp, - 'open': float(record.open), - 'high': float(record.high), - 'low': float(record.low), - 'close': float(record.close), - 'volume': record.volume, - 'amount': float(record.amount) if record.amount else 0.0 - }) - - df = pd.DataFrame(data) - df.set_index('timestamp', inplace=True) - - return df - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 获取最新数据失败: {e}") - return pd.DataFrame() - - def get_data_range(self, stock_code: str, period: str = "1d") -> Dict[str, Any]: - """获取数据的时间范围和统计信息""" - try: - model_class = self.get_stock_model(stock_code, period) - - # 使用peewee的聚合函数获取时间范围 - from peewee import fn - min_time_query = model_class.select(fn.MIN(model_class.timestamp)).scalar() - max_time_query = model_class.select(fn.MAX(model_class.timestamp)).scalar() - count = model_class.select().count() - - # 获取表名 - table_name = get_table_name(normalize_stock_code(stock_code), period) - - return { - 'stock_code': stock_code, - 'period': period, - 'start_date': min_time_query, - 'end_date': max_time_query, - 'record_count': count, - 'table_name': table_name - } - - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 获取数据范围失败: {e}") - return {} - - # ================================ 表维护 ================================ - - def clear_table(self, stock_code: str, period: str = "1d") -> int: - """清空股票表数据""" - try: - model_class = self.get_stock_model(stock_code, period) - return self.db_manager.clear_table(model_class) - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 清空表失败: {e}") - return 0 - - def drop_table(self, stock_code: str, period: str = "1d") -> bool: - """删除股票表""" - try: - model_class = self.get_stock_model(stock_code, period) - success = self.db_manager.drop_table(model_class, safe=True) - - # 从缓存中移除 - model_key = f"{normalize_stock_code(stock_code)}_{period}" - if model_key in self.model_cache: - del self.model_cache[model_key] - - return success - except Exception as e: - logger.error(f"{LOG_PREFIXES['ERROR']} 删除表失败: {e}") - return False - - def get_available_stocks(self) -> List[str]: - """获取可用的股票代码列表""" - # TODO: 实现从数据库获取所有表名并解析股票代码 - logger.warning(f"{LOG_PREFIXES['WARNING']} get_available_stocks() 方法待实现") - return [] - - def get_available_periods(self, stock_code: str) -> List[str]: - """获取指定股票的可用时间周期""" - # TODO: 实现从数据库获取指定股票的所有时间周期 - logger.warning(f"{LOG_PREFIXES['WARNING']} get_available_periods() 方法待实现") - return [] - - def close(self): - """关闭数据管理器""" - self.db_manager.disconnect() - logger.info(f"{LOG_PREFIXES['DATABASE']} 股票数据管理器已关闭") - -# ================================ 便捷函数 ================================ - -def get_stock_data_manager(): - """获取股票数据管理器实例""" - return StockDataManager() - -if __name__ == "__main__": - # 测试股票数据管理器 - print(f"{LOG_PREFIXES['DATABASE']} 测试股票数据管理器...") - - manager = StockDataManager() - - # 测试创建表 - success = manager.create_table("000001.SZ", "1d") - print(f"{LOG_PREFIXES['SUCCESS'] if success else LOG_PREFIXES['ERROR']} 创建表测试: {'成功' if success else '失败'}") - - # 测试数据范围查询 - data_range = manager.get_data_range("000001.SZ", "1d") - if data_range: - print(f"{LOG_PREFIXES['SUCCESS']} 数据范围查询成功: {data_range}") - - manager.close() diff --git a/src/data_process_model/stocktrade_manager.py b/src/data_process_model/stocktrade_manager.py deleted file mode 100644 index e4d0794..0000000 --- a/src/data_process_model/stocktrade_manager.py +++ /dev/null @@ -1,471 +0,0 @@ -""" -股票交易管理器 - 独立的交易记录模块 -专门负责交易委托和成交记录的管理 -与 stockdata_manager.py 并行存在,职责分离 -""" - -import uuid -import logging -from typing import Dict, List, Any, Optional -from datetime import datetime - -# 复用现有架构组件 -from database_manager import get_database_manager -from trade_models import TradeOrder, TradeExecution, create_trade_tables -from common import ( - LOG_PREFIXES, - TradeDirection, OrderType, OrderStatus -) - -logger = logging.getLogger(__name__) - -class StockTradeManager: - """ - 股票交易管理器 - - 职责: - 1. 记录交易委托信息 - 2. 记录交易成交信息 - 3. 提供交易记录查询功能 - 4. 管理交易相关数据表 - """ - - def __init__(self): - """初始化交易管理器""" - self.db_manager = get_database_manager() - self._setup_trade_tables() - logger.info(f"{LOG_PREFIXES['SUCCESS']} 股票交易管理器初始化完成") - - def _setup_trade_tables(self): - """设置交易数据表""" - try: - results = create_trade_tables() - success_count = sum(results.values()) - total_count = len(results) - print(f"{LOG_PREFIXES['DATABASE']} 交易表创建: {success_count}/{total_count} 成功") - except Exception as e: - print(f"{LOG_PREFIXES['ERROR']} 交易表创建失败: {e}") - - # ================================ 核心功能 ================================ - - def record_order(self, order_info: Dict[str, Any]) -> str: - """ - 记录交易委托 - - Args: - order_info: 委托信息字典 - - strategy_id: 策略ID - - stockcode: 股票代码 - - direction: 交易方向 (BUY/SELL) - - order_type: 委托类型 (MARKET/LIMIT) - - quantity: 委托数量 - - price: 委托价格 (限价单必填) - - notes: 备注 (可选) - - Returns: - str: 委托ID - - Example: - >>> order_info = { - >>> 'strategy_id': 'my_strategy', - >>> 'stockcode': '601658.SH', - >>> 'direction': 'BUY', - >>> 'order_type': 'MARKET', - >>> 'quantity': 100 - >>> } - >>> order_id = trade_manager.record_order(order_info) - """ - try: - # 生成唯一订单ID - order_id = f"ORDER_{datetime.now().strftime('%Y%m%d%H%M%S')}_{uuid.uuid4().hex[:8]}" - - # 验证必填字段 - required_fields = ['strategy_id', 'stockcode', 'direction', 'order_type', 'quantity'] - for field in required_fields: - if field not in order_info: - raise ValueError(f"缺少必填字段: {field}") - - # 验证枚举值 - if order_info['direction'] not in [TradeDirection.BUY.value, TradeDirection.SELL.value]: - raise ValueError(f"无效的交易方向: {order_info['direction']}") - - if order_info['order_type'] not in [OrderType.MARKET.value, OrderType.LIMIT.value]: - raise ValueError(f"无效的委托类型: {order_info['order_type']}") - - # 限价单必须提供价格 - if order_info['order_type'] == OrderType.LIMIT.value and 'price' not in order_info: - raise ValueError("限价单必须提供委托价格") - - # 创建委托记录 - order_data = { - 'order_id': order_id, - 'strategy_id': order_info['strategy_id'], - 'stockcode': order_info['stockcode'], - 'direction': order_info['direction'], - 'order_type': order_info['order_type'], - 'quantity': order_info['quantity'], - 'price': order_info.get('price'), - 'status': OrderStatus.PENDING.value, - 'notes': order_info.get('notes', ''), - 'order_time': datetime.now() - } - - # 保存到数据库 - TradeOrder.create(**order_data) - - print(f"{LOG_PREFIXES['SUCCESS']} 记录委托 {order_id}: {order_info['stockcode']} {order_info['direction']} {order_info['quantity']}") - return order_id - - except Exception as e: - print(f"{LOG_PREFIXES['ERROR']} 记录委托失败: {e}") - raise - - def record_execution(self, exec_info: Dict[str, Any]) -> str: - """ - 记录交易成交 - - Args: - exec_info: 成交信息字典 - - order_id: 对应的委托ID - - stockcode: 股票代码 - - price: 成交价格 - - quantity: 成交数量 - - execution_time: 成交时间 (可选,默认当前时间) - - commission: 手续费 (可选,默认0) - - notes: 备注 (可选) - - Returns: - str: 成交ID - - Example: - >>> exec_info = { - >>> 'order_id': order_id, - >>> 'stockcode': '601658.SH', - >>> 'price': 10.50, - >>> 'quantity': 100 - >>> } - >>> exec_id = trade_manager.record_execution(exec_info) - """ - try: - # 生成唯一成交ID - exec_id = f"EXEC_{datetime.now().strftime('%Y%m%d%H%M%S')}_{uuid.uuid4().hex[:8]}" - - # 验证必填字段 - required_fields = ['order_id', 'stockcode', 'price', 'quantity'] - for field in required_fields: - if field not in exec_info: - raise ValueError(f"缺少必填字段: {field}") - - # 查找对应的委托记录 - try: - order = TradeOrder.get(TradeOrder.order_id == exec_info['order_id']) - except Exception: - raise ValueError(f"未找到对应的委托记录: {exec_info['order_id']}") - - # 计算成交金额 - amount = float(exec_info['price']) * int(exec_info['quantity']) - - # 创建成交记录 - exec_data = { - 'execution_id': exec_id, - 'order_id': exec_info['order_id'], - 'stockcode': exec_info['stockcode'], - 'price': exec_info['price'], - 'quantity': exec_info['quantity'], - 'amount': amount, - 'commission': exec_info.get('commission', 0), - 'direction': order.direction, - 'notes': exec_info.get('notes', ''), - 'execution_time': exec_info.get('execution_time', datetime.now()) - } - - # 保存到数据库 - TradeExecution.create(**exec_data) - - print(f"{LOG_PREFIXES['SUCCESS']} 记录成交 {exec_id}: {exec_info['stockcode']} {order.direction} {exec_info['quantity']}@{exec_info['price']}") - return exec_id - - except Exception as e: - print(f"{LOG_PREFIXES['ERROR']} 记录成交失败: {e}") - raise - - def update_order_status(self, order_id: str, status: str) -> bool: - """ - 更新委托状态 - - Args: - order_id: 委托ID - status: 新状态 (PENDING/FILLED/CANCELLED/PARTIAL) - - Returns: - bool: 更新是否成功 - """ - try: - # 验证状态值 - valid_statuses = [s.value for s in OrderStatus] - if status not in valid_statuses: - raise ValueError(f"无效的委托状态: {status}") - - # 更新状态 - query = TradeOrder.update( - status=status, - updated_at=datetime.now() - ).where(TradeOrder.order_id == order_id) - - updated_count = query.execute() - - if updated_count > 0: - print(f"{LOG_PREFIXES['SUCCESS']} 更新委托状态: {order_id} -> {status}") - return True - else: - print(f"{LOG_PREFIXES['WARNING']} 未找到委托记录: {order_id}") - return False - - except Exception as e: - print(f"{LOG_PREFIXES['ERROR']} 更新委托状态失败: {e}") - return False - - def get_orders(self, filters: Optional[Dict[str, Any]] = None) -> List[Dict[str, Any]]: - """ - 查询委托记录 - - Args: - filters: 过滤条件字典 - - stockcode: 股票代码 - - strategy_id: 策略ID - - status: 委托状态 - - start_date: 开始日期 - - end_date: 结束日期 - - limit: 返回条数限制 - - Returns: - List[Dict]: 委托记录列表 - """ - try: - query = TradeOrder.select() - - if filters: - if 'stockcode' in filters: - query = query.where(TradeOrder.stockcode == filters['stockcode']) - - if 'strategy_id' in filters: - query = query.where(TradeOrder.strategy_id == filters['strategy_id']) - - if 'status' in filters: - query = query.where(TradeOrder.status == filters['status']) - - if 'start_date' in filters: - query = query.where(TradeOrder.order_time >= filters['start_date']) - - if 'end_date' in filters: - query = query.where(TradeOrder.order_time <= filters['end_date']) - - if 'limit' in filters: - query = query.limit(filters['limit']) - - # 按时间倒序排列 - query = query.order_by(TradeOrder.order_time.desc()) - - # 转换为字典列表 - orders = [] - for order in query: - orders.append({ - 'order_id': order.order_id, - 'strategy_id': order.strategy_id, - 'stockcode': order.stockcode, - 'order_time': order.order_time, - 'direction': order.direction, - 'order_type': order.order_type, - 'quantity': order.quantity, - 'price': float(order.price) if order.price else None, - 'status': order.status, - 'notes': order.notes - }) - - return orders - - except Exception as e: - print(f"{LOG_PREFIXES['ERROR']} 查询委托记录失败: {e}") - return [] - - def get_executions(self, filters: Optional[Dict[str, Any]] = None) -> List[Dict[str, Any]]: - """ - 查询成交记录 - - Args: - filters: 过滤条件字典 - - stockcode: 股票代码 - - order_id: 委托ID - - direction: 交易方向 - - start_date: 开始日期 - - end_date: 结束日期 - - limit: 返回条数限制 - - Returns: - List[Dict]: 成交记录列表 - """ - try: - query = TradeExecution.select() - - if filters: - if 'stockcode' in filters: - query = query.where(TradeExecution.stockcode == filters['stockcode']) - - if 'order_id' in filters: - query = query.where(TradeExecution.order_id == filters['order_id']) - - if 'direction' in filters: - query = query.where(TradeExecution.direction == filters['direction']) - - if 'start_date' in filters: - query = query.where(TradeExecution.execution_time >= filters['start_date']) - - if 'end_date' in filters: - query = query.where(TradeExecution.execution_time <= filters['end_date']) - - if 'limit' in filters: - query = query.limit(filters['limit']) - - # 按时间倒序排列 - query = query.order_by(TradeExecution.execution_time.desc()) - - # 转换为字典列表 - executions = [] - for execution in query: - executions.append({ - 'execution_id': execution.execution_id, - 'order_id': execution.order_id, - 'stockcode': execution.stockcode, - 'execution_time': execution.execution_time, - 'price': float(execution.price), - 'quantity': execution.quantity, - 'amount': float(execution.amount), - 'commission': float(execution.commission), - 'direction': execution.direction, - 'notes': execution.notes - }) - - return executions - - except Exception as e: - print(f"{LOG_PREFIXES['ERROR']} 查询成交记录失败: {e}") - return [] - - def get_trade_summary(self, stockcode: Optional[str] = None, strategy_id: Optional[str] = None) -> Dict[str, Any]: - """ - 获取交易汇总信息 - - Args: - stockcode: 股票代码 (可选) - strategy_id: 策略ID (可选) - - Returns: - Dict: 交易汇总信息 - """ - try: - summary = { - 'total_orders': 0, - 'total_executions': 0, - 'total_amount': 0.0, - 'total_commission': 0.0, - 'buy_count': 0, - 'sell_count': 0, - 'pending_orders': 0 - } - - # 统计委托 - order_query = TradeOrder.select() - if stockcode: - order_query = order_query.where(TradeOrder.stockcode == stockcode) - if strategy_id: - order_query = order_query.where(TradeOrder.strategy_id == strategy_id) - - summary['total_orders'] = order_query.count() - summary['pending_orders'] = order_query.where(TradeOrder.status == OrderStatus.PENDING.value).count() - - # 统计成交 - exec_query = TradeExecution.select() - if stockcode: - exec_query = exec_query.where(TradeExecution.stockcode == stockcode) - - summary['total_executions'] = exec_query.count() - summary['buy_count'] = exec_query.where(TradeExecution.direction == TradeDirection.BUY.value).count() - summary['sell_count'] = exec_query.where(TradeExecution.direction == TradeDirection.SELL.value).count() - - # 统计金额 - for execution in exec_query: - summary['total_amount'] += float(execution.amount) - summary['total_commission'] += float(execution.commission) - - return summary - - except Exception as e: - print(f"{LOG_PREFIXES['ERROR']} 获取交易汇总失败: {e}") - return {} - - def close(self): - """关闭交易管理器""" - # 注意:database_manager 可能没有 close 方法,先检查 - try: - if hasattr(self.db_manager, 'close') and callable(getattr(self.db_manager, 'close')): - getattr(self.db_manager, 'close')() - except Exception as e: - print(f"{LOG_PREFIXES['WARNING']} 关闭数据库管理器时出错: {e}") - - print(f"{LOG_PREFIXES['DATABASE']} 交易管理器已关闭") - -# 工厂函数,与 stockdata_manager.py 保持一致的模式 -def get_stock_trade_manager() -> StockTradeManager: - """获取股票交易管理器实例""" - return StockTradeManager() - -if __name__ == "__main__": - # 测试交易管理器 - print("测试股票交易管理器...") - - trade_manager = get_stock_trade_manager() - - # 测试记录委托 - order_info = { - 'strategy_id': 'test_strategy', - 'stockcode': '601658.SH', - 'direction': 'BUY', - 'order_type': 'MARKET', - 'quantity': 100, - 'notes': '测试委托' - } - - try: - order_id = trade_manager.record_order(order_info) - print(f"委托ID: {order_id}") - - # 测试记录成交 - exec_info = { - 'order_id': order_id, - 'stockcode': '601658.SH', - 'price': 10.50, - 'quantity': 100, - 'commission': 5.0 - } - - exec_id = trade_manager.record_execution(exec_info) - print(f"成交ID: {exec_id}") - - # 更新委托状态 - trade_manager.update_order_status(order_id, 'FILLED') - - # 查询记录 - orders = trade_manager.get_orders({'limit': 5}) - print(f"最近委托: {len(orders)} 条") - - executions = trade_manager.get_executions({'limit': 5}) - print(f"最近成交: {len(executions)} 条") - - # 交易汇总 - summary = trade_manager.get_trade_summary() - print(f"交易汇总: {summary}") - - except Exception as e: - print(f"测试失败: {e}") - finally: - trade_manager.close() diff --git a/src/data_process_model/technical_indicators.py b/src/data_process_model/technical_indicators.py deleted file mode 100644 index 75fd513..0000000 --- a/src/data_process_model/technical_indicators.py +++ /dev/null @@ -1,285 +0,0 @@ -""" -技术指标计算模块 - 基于TA-Lib,支持内存缓存 -""" - -import pandas as pd -import numpy as np -import talib -from typing import Dict, Any, Optional, List -from dataclasses import dataclass, field -from stockdata_manager import StockDataManager -import logging - -# 导入公共配置 -from common import LOG_PREFIXES, validate_kline_data - -logger = logging.getLogger(__name__) - - -@dataclass -class IndicatorParams: - """ - 技术指标参数配置类 - - 用于配置各种技术指标的计算参数,提供默认值。 - 所有参数都可以根据需要进行调整。 - """ - # MACD参数 - macd_fast: int = 12 # MACD快线周期,通常为12 - macd_slow: int = 26 # MACD慢线周期,通常为26 - macd_signal: int = 9 # MACD信号线周期,通常为9 - - # 移动平均线参数 - ma_periods: List[int] = field(default_factory=lambda: [5, 10, 20]) # MA周期列表 - - # RSI参数 - rsi_period: int = 14 # RSI计算周期,通常为14 - - # 布林带参数 - boll_period: int = 20 # 布林带周期,通常为20 - boll_std: float = 2.0 # 布林带标准差倍数,通常为2.0 - - # KDJ参数 - kdj_k: int = 9 # KDJ的K值周期 - kdj_d: int = 3 # KDJ的D值周期 - kdj_j: int = 3 # KDJ的J值周期 - - -class TechnicalIndicators: - """ - 技术指标计算器 - - 支持功能: - - 内存缓存机制,避免重复数据库查询 - - 基于TA-Lib的专业技术指标计算 - - 支持从数据库查询和直接DataFrame计算两种方式 - """ - - def __init__(self): - """初始化技术指标计算器""" - self.data_manager = StockDataManager() - self._cache = {} # 数据缓存:{cache_key: DataFrame} - - # ============================================================================= - # 公有方法:对外提供的接口 - # ============================================================================= - - def calculate_all(self, stock_code: str, period: str = '1d', - start_time: Optional[str] = None, end_time: Optional[str] = None, - params: Optional[IndicatorParams] = None) -> Dict[str, Any]: - """ - 计算所有技术指标 - - Args: - stock_code: 股票代码,如 '601658.SH' - period: 数据周期,如 '1d', '5m', '15m' 等 - start_time: 开始时间,格式 'YYYY-MM-DD',默认为None(获取所有数据) - end_time: 结束时间,格式 'YYYY-MM-DD',默认为None(获取所有数据) - params: 指标参数配置,默认使用标准参数 - - Returns: - Dict: 包含所有指标结果的字典 - { - 'timestamp': 时间索引, - 'ohlcv': {'open': 开盘价, 'high': 最高价, 'low': 最低价, 'close': 收盘价, 'volume': 成交量}, - 'macd': {'macd': MACD线, 'signal': 信号线, 'histogram': 柱状图}, - 'ma': {'ma5': 5日均线, 'ma10': 10日均线, ...}, - 'rsi': RSI值数组, - 'bollinger': {'upper': 上轨, 'middle': 中轨, 'lower': 下轨}, - 'kdj': {'k': K值, 'd': D值, 'j': J值} - } - """ - if params is None: - params = IndicatorParams() - - df = self._get_dataframe(stock_code, period, start_time, end_time) - - # 使用公共配置验证数据 - if not validate_kline_data(df): - logger.warning(f"{LOG_PREFIXES['WARNING']} K线数据验证失败或为空: {stock_code}") - return {} - - # 转换为numpy数组(TA-Lib要求) - close = np.array(df['close'].values, dtype=np.float64) - high = np.array(df['high'].values, dtype=np.float64) - low = np.array(df['low'].values, dtype=np.float64) - volume = np.array(df['volume'].values, dtype=np.float64) - - return { - 'timestamp': df.index, - 'ohlcv': {'open': df['open'].values, 'high': high, 'low': low, 'close': close, 'volume': volume}, - 'macd': self._macd(close, params), - 'ma': self._ma(close, params.ma_periods or [5, 10, 20]), - 'rsi': talib.RSI(close, params.rsi_period), - 'bollinger': self._bollinger(close, params), - 'kdj': self._kdj(high, low, close, params) - } - - def macd_from_df(self, df: pd.DataFrame, fast: int = 12, slow: int = 26, signal: int = 9) -> Dict[str, pd.Series]: - """ - 直接从DataFrame计算MACD指标 - - Args: - df: 包含OHLCV数据的DataFrame,必须有'close'列 - fast: MACD快线周期,默认12 - slow: MACD慢线周期,默认26 - signal: MACD信号线周期,默认9 - - Returns: - Dict[str, pd.Series]: - { - 'macd': MACD线, - 'signal': 信号线, - 'histogram': 柱状图(MACD-信号线) - } - """ - close = np.array(df['close'].values, dtype=np.float64) - macd, signal_line, histogram = talib.MACD(close, fast, slow, signal) - return { - 'macd': pd.Series(macd, index=df.index), - 'signal': pd.Series(signal_line, index=df.index), - 'histogram': pd.Series(histogram, index=df.index) - } - - def ma_from_df(self, df: pd.DataFrame, periods: Optional[List[int]] = None) -> Dict[str, pd.Series]: - """ - 直接从DataFrame计算移动平均线 - - Args: - df: 包含OHLCV数据的DataFrame,必须有'close'列 - periods: 移动平均线周期列表,如[5, 10, 20],默认[5, 10, 20] - - Returns: - Dict[str, pd.Series]: {'ma5': 5日均线, 'ma10': 10日均线, ...} - """ - if periods is None: - periods = [5, 10, 20] - close = np.array(df['close'].values, dtype=np.float64) - return {f'ma{p}': pd.Series(talib.SMA(close, p), index=df.index) for p in periods} - - def clear_cache(self): - """ - 清空内存缓存 - - 用于释放内存或强制重新从数据库获取数据 - """ - self._cache.clear() - - # ============================================================================= - # 私有方法:内部实现 - # ============================================================================= - - def _get_cache_key(self, stock_code: str, period: str, start_time: Optional[str] = None, end_time: Optional[str] = None) -> str: - """ - 生成缓存键 - - Args: - stock_code: 股票代码 - period: 数据周期 - start_time: 开始时间 - end_time: 结束时间 - - Returns: - str: 缓存键字符串 - """ - return f"{stock_code}_{period}_{start_time}_{end_time}" - - def _get_dataframe(self, stock_code: str, period: str, start_time: Optional[str] = None, end_time: Optional[str] = None) -> pd.DataFrame: - """ - 获取DataFrame数据,优先从缓存获取 - - Args: - stock_code: 股票代码 - period: 数据周期 - start_time: 开始时间 - end_time: 结束时间 - - Returns: - pd.DataFrame: 股票OHLCV数据 - """ - cache_key = self._get_cache_key(stock_code, period, start_time, end_time) - - # 优先从缓存获取 - if cache_key in self._cache: - return self._cache[cache_key] - - # 转换时间格式 - from datetime import datetime - start_dt = None - end_dt = None - if start_time: - start_dt = datetime.strptime(start_time, '%Y-%m-%d') - if end_time: - end_dt = datetime.strptime(end_time, '%Y-%m-%d') - - # 从数据库获取并缓存 - df = self.data_manager.read_stock_data(stock_code, period, start_dt, end_dt) - - if not df.empty: - self._cache[cache_key] = df - - return df - - def _macd(self, close: np.ndarray, params: IndicatorParams) -> Dict[str, np.ndarray]: - """ - 计算MACD指标 - - Args: - close: 收盘价数组 - params: 指标参数 - - Returns: - Dict: {'macd': MACD线, 'signal': 信号线, 'histogram': 柱状图} - """ - macd, signal, histogram = talib.MACD(close, params.macd_fast, params.macd_slow, params.macd_signal) - return {'macd': macd, 'signal': signal, 'histogram': histogram} - - def _ma(self, close: np.ndarray, periods: List[int]) -> Dict[str, np.ndarray]: - """ - 计算移动平均线 - - Args: - close: 收盘价数组 - periods: 周期列表 - - Returns: - Dict: {'ma5': 5日均线, 'ma10': 10日均线, ...} - """ - return {f'ma{p}': talib.SMA(close, p) for p in periods} - - def _bollinger(self, close: np.ndarray, params: IndicatorParams) -> Dict[str, np.ndarray]: - """ - 计算布林带指标 - - Args: - close: 收盘价数组 - params: 指标参数 - - Returns: - Dict: {'upper': 上轨, 'middle': 中轨, 'lower': 下轨} - """ - upper, middle, lower = talib.BBANDS(close, params.boll_period, params.boll_std, params.boll_std) - return {'upper': upper, 'middle': middle, 'lower': lower} - - def _kdj(self, high: np.ndarray, low: np.ndarray, close: np.ndarray, params: IndicatorParams) -> Dict[str, np.ndarray]: - """ - 计算KDJ指标 - - Args: - high: 最高价数组 - low: 最低价数组 - close: 收盘价数组 - params: 指标参数 - - Returns: - Dict: {'k': K值, 'd': D值, 'j': J值} - """ - k, d = talib.STOCH(high, low, close, fastk_period=params.kdj_k, slowk_period=params.kdj_d, slowd_period=params.kdj_j) - j = 3 * k - 2 * d # J = 3K - 2D - return {'k': k, 'd': d, 'j': j} - - -if __name__ == "__main__": - calculator = TechnicalIndicators() - print("📊 技术指标计算器已就绪") - diff --git a/src/data_process_model/test_stocktrade.py b/src/data_process_model/test_stocktrade.py deleted file mode 100644 index e553263..0000000 --- a/src/data_process_model/test_stocktrade.py +++ /dev/null @@ -1,205 +0,0 @@ -#!/usr/bin/env python3 -""" -测试股票交易管理器功能 -""" - -import sys -import os - -# 添加当前目录到Python路径 -sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) - -def test_imports(): - """测试模块导入""" - print("=" * 50) - print("测试模块导入...") - - try: - from common import TradeDirection, OrderType, OrderStatus - print("✓ common 模块导入成功") - except Exception as e: - print(f"✗ common 模块导入失败: {e}") - return False - - try: - from database_manager import get_database_manager - print("✓ database_manager 模块导入成功") - except Exception as e: - print(f"✗ database_manager 模块导入失败: {e}") - return False - - try: - from trade_models import TradeOrder, TradeExecution, create_trade_tables - print("✓ trade_models 模块导入成功") - except Exception as e: - print(f"✗ trade_models 模块导入失败: {e}") - return False - - try: - from stocktrade_manager import StockTradeManager, get_stock_trade_manager - print("✓ stocktrade_manager 模块导入成功") - except Exception as e: - print(f"✗ stocktrade_manager 模块导入失败: {e}") - return False - - return True - -def test_manager_creation(): - """测试管理器创建""" - print("=" * 50) - print("测试管理器创建...") - - try: - from stocktrade_manager import get_stock_trade_manager - manager = get_stock_trade_manager() - print("✓ 交易管理器创建成功") - return manager - except Exception as e: - print(f"✗ 交易管理器创建失败: {e}") - return None - -def test_order_recording(manager): - """测试委托记录功能""" - print("=" * 50) - print("测试委托记录功能...") - - try: - # 准备委托信息 - order_info = { - 'strategy_id': 'test_strategy_001', - 'stockcode': '000001.SZ', - 'direction': 'BUY', - 'order_type': 'MARKET', - 'quantity': 100, - 'notes': '测试市价买入委托' - } - - # 记录委托 - order_id = manager.record_order(order_info) - print(f"✓ 委托记录成功,订单ID: {order_id}") - return order_id - - except Exception as e: - print(f"✗ 委托记录失败: {e}") - return None - -def test_execution_recording(manager, order_id): - """测试成交记录功能""" - print("=" * 50) - print("测试成交记录功能...") - - if not order_id: - print("✗ 无有效订单ID,跳过成交记录测试") - return None - - try: - # 准备成交信息 - exec_info = { - 'order_id': order_id, - 'stockcode': '000001.SZ', - 'price': 12.50, - 'quantity': 100, - 'commission': 5.0, - 'notes': '测试成交记录' - } - - # 记录成交 - exec_id = manager.record_execution(exec_info) - print(f"✓ 成交记录成功,成交ID: {exec_id}") - return exec_id - - except Exception as e: - print(f"✗ 成交记录失败: {e}") - return None - -def test_status_update(manager, order_id): - """测试状态更新功能""" - print("=" * 50) - print("测试状态更新功能...") - - if not order_id: - print("✗ 无有效订单ID,跳过状态更新测试") - return False - - try: - # 更新订单状态为已成交 - result = manager.update_order_status(order_id, 'FILLED') - if result: - print("✓ 订单状态更新成功") - else: - print("✗ 订单状态更新失败") - return result - - except Exception as e: - print(f"✗ 订单状态更新异常: {e}") - return False - -def test_query_functions(manager): - """测试查询功能""" - print("=" * 50) - print("测试查询功能...") - - try: - # 查询最近的委托记录 - orders = manager.get_orders({'limit': 5}) - print(f"✓ 查询委托记录成功,找到 {len(orders)} 条记录") - - # 查询最近的成交记录 - executions = manager.get_executions({'limit': 5}) - print(f"✓ 查询成交记录成功,找到 {len(executions)} 条记录") - - # 获取交易汇总 - summary = manager.get_trade_summary() - print(f"✓ 交易汇总获取成功,总委托: {summary.get('total_orders', 0)}, 总成交: {summary.get('total_executions', 0)}") - - return True - - except Exception as e: - print(f"✗ 查询功能测试失败: {e}") - return False - -def main(): - """主测试函数""" - print("开始测试股票交易管理器功能") - print("当前工作目录:", os.getcwd()) - - # 测试模块导入 - if not test_imports(): - print("\n❌ 模块导入测试失败,停止测试") - return - - # 测试管理器创建 - manager = test_manager_creation() - if not manager: - print("\n❌ 管理器创建测试失败,停止测试") - return - - try: - # 测试委托记录 - order_id = test_order_recording(manager) - - # 测试成交记录 - exec_id = test_execution_recording(manager, order_id) - - # 测试状态更新 - test_status_update(manager, order_id) - - # 测试查询功能 - test_query_functions(manager) - - print("=" * 50) - print("✅ 所有测试完成") - - except Exception as e: - print(f"\n❌ 测试过程中发生异常: {e}") - - finally: - # 关闭管理器 - try: - manager.close() - print("🔒 交易管理器已关闭") - except Exception as e: - print(f"⚠️ 关闭管理器时出错: {e}") - -if __name__ == "__main__": - main() diff --git a/src/data_process_model/trade_example.py b/src/data_process_model/trade_example.py deleted file mode 100644 index 0be9655..0000000 --- a/src/data_process_model/trade_example.py +++ /dev/null @@ -1,263 +0,0 @@ -""" -交易记录系统使用示例 -演示如何在策略中使用 stocktrade_manager.py 记录交易 -""" - -from datetime import datetime -from typing import Optional -from stocktrade_manager import get_stock_trade_manager -from stockdata_manager import get_stock_data_manager - -class SimpleTradeStrategy: - """ - 简单交易策略示例 - 演示如何集成交易记录功能 - """ - - def __init__(self, strategy_id: str): - self.strategy_id = strategy_id - - # 数据管理器和交易管理器并行使用 - self.data_manager = get_stock_data_manager() # 负责K线数据 - self.trade_manager = get_stock_trade_manager() # 负责交易记录 - - print(f"✅ 策略 {strategy_id} 初始化完成") - - def execute_buy_signal(self, stockcode: str, quantity: int, price: Optional[float] = None): - """ - 执行买入信号 - - Args: - stockcode: 股票代码 - quantity: 买入数量 - price: 限价(None表示市价单) - """ - try: - print(f"\n📈 执行买入信号: {stockcode} x {quantity}") - - # 1. 记录委托 - order_info = { - 'strategy_id': self.strategy_id, - 'stockcode': stockcode, - 'direction': 'BUY', - 'order_type': 'LIMIT' if price else 'MARKET', - 'quantity': quantity, - 'notes': f'策略买入信号 - {datetime.now().strftime("%H:%M:%S")}' - } - - if price: - order_info['price'] = price - - order_id = self.trade_manager.record_order(order_info) - print(f"🎯 委托已提交: {order_id}") - - # 2. 模拟交易执行(实际应用中这里会调用券商API) - execution_price = price if price else self._get_current_price(stockcode) - execution_result = self._simulate_execution(stockcode, quantity, execution_price) - - # 3. 记录成交 - if execution_result['success']: - exec_info = { - 'order_id': order_id, - 'stockcode': stockcode, - 'price': execution_result['price'], - 'quantity': execution_result['quantity'], - 'commission': execution_result['commission'], - 'notes': '模拟成交' - } - - exec_id = self.trade_manager.record_execution(exec_info) - print(f"✅ 成交记录: {exec_id}") - - # 4. 更新委托状态 - self.trade_manager.update_order_status(order_id, 'FILLED') - - return { - 'order_id': order_id, - 'execution_id': exec_id, - 'success': True - } - else: - print(f"❌ 交易执行失败: {execution_result['error']}") - self.trade_manager.update_order_status(order_id, 'CANCELLED') - return {'success': False, 'error': execution_result['error']} - - except Exception as e: - print(f"❌ 执行买入信号失败: {e}") - return {'success': False, 'error': str(e)} - - def execute_sell_signal(self, stockcode: str, quantity: int, price: Optional[float] = None): - """ - 执行卖出信号 - - Args: - stockcode: 股票代码 - quantity: 卖出数量 - price: 限价(None表示市价单) - """ - try: - print(f"\n📉 执行卖出信号: {stockcode} x {quantity}") - - # 1. 记录委托 - order_info = { - 'strategy_id': self.strategy_id, - 'stockcode': stockcode, - 'direction': 'SELL', - 'order_type': 'LIMIT' if price else 'MARKET', - 'quantity': quantity, - 'notes': f'策略卖出信号 - {datetime.now().strftime("%H:%M:%S")}' - } - - if price: - order_info['price'] = price - - order_id = self.trade_manager.record_order(order_info) - print(f"🎯 委托已提交: {order_id}") - - # 2. 模拟交易执行 - execution_price = price if price else self._get_current_price(stockcode) - execution_result = self._simulate_execution(stockcode, quantity, execution_price) - - # 3. 记录成交 - if execution_result['success']: - exec_info = { - 'order_id': order_id, - 'stockcode': stockcode, - 'price': execution_result['price'], - 'quantity': execution_result['quantity'], - 'commission': execution_result['commission'], - 'notes': '模拟成交' - } - - exec_id = self.trade_manager.record_execution(exec_info) - print(f"✅ 成交记录: {exec_id}") - - # 4. 更新委托状态 - self.trade_manager.update_order_status(order_id, 'FILLED') - - return { - 'order_id': order_id, - 'execution_id': exec_id, - 'success': True - } - else: - print(f"❌ 交易执行失败: {execution_result['error']}") - self.trade_manager.update_order_status(order_id, 'CANCELLED') - return {'success': False, 'error': execution_result['error']} - - except Exception as e: - print(f"❌ 执行卖出信号失败: {e}") - return {'success': False, 'error': str(e)} - - def _get_current_price(self, stockcode: str) -> float: - """ - 获取当前股价(模拟) - 实际应用中会从数据源获取实时价格 - """ - # 这里使用模拟价格,实际应用中会调用数据接口 - price_map = { - '601658.SH': 10.50, - '601398.SH': 5.20, - '601288.SH': 42.80, - '510310.SH': 1.05 - } - return price_map.get(stockcode, 10.0) - - def _simulate_execution(self, stockcode: str, quantity: int, price: float) -> dict: - """ - 模拟交易执行 - 实际应用中会调用券商API - """ - # 模拟成功执行 - commission = max(5.0, quantity * price * 0.0003) # 最低5元手续费 - - return { - 'success': True, - 'price': price, - 'quantity': quantity, - 'commission': round(commission, 2) - } - - def get_strategy_performance(self) -> dict: - """获取策略绩效统计""" - return self.trade_manager.get_trade_summary(strategy_id=self.strategy_id) - - def get_recent_trades(self, limit: int = 10) -> dict: - """获取最近的交易记录""" - orders = self.trade_manager.get_orders({ - 'strategy_id': self.strategy_id, - 'limit': limit - }) - - executions = self.trade_manager.get_executions({ - 'limit': limit - }) - - return { - 'orders': orders, - 'executions': executions - } - - def close(self): - """关闭策略""" - self.data_manager.close() - self.trade_manager.close() - print(f"🔒 策略 {self.strategy_id} 已关闭") - -def demo_trading_strategy(): - """ - 演示交易策略的完整流程 - """ - print("🚀 开始演示交易记录系统...") - - # 创建策略实例 - strategy = SimpleTradeStrategy("demo_strategy_001") - - try: - # 模拟交易信号 - print("\n" + "="*50) - print("📊 模拟交易场景") - print("="*50) - - # 买入信号 - result1 = strategy.execute_buy_signal('601658.SH', 100, 10.50) - result2 = strategy.execute_buy_signal('601398.SH', 200) # 市价单 - - # 卖出信号 - result3 = strategy.execute_sell_signal('601658.SH', 50, 10.80) - - # 查看交易记录 - print("\n" + "="*50) - print("📈 交易记录查询") - print("="*50) - - recent_trades = strategy.get_recent_trades(5) - print(f"📋 最近委托 ({len(recent_trades['orders'])} 条):") - for order in recent_trades['orders']: - print(f" {order['order_time']} | {order['stockcode']} | {order['direction']} | {order['quantity']} | {order['status']}") - - print(f"\n✅ 最近成交 ({len(recent_trades['executions'])} 条):") - for execution in recent_trades['executions']: - print(f" {execution['execution_time']} | {execution['stockcode']} | {execution['direction']} | {execution['quantity']}@{execution['price']}") - - # 策略绩效 - print("\n" + "="*50) - print("📊 策略绩效统计") - print("="*50) - - performance = strategy.get_strategy_performance() - print(f"总委托数: {performance.get('total_orders', 0)}") - print(f"总成交数: {performance.get('total_executions', 0)}") - print(f"买入次数: {performance.get('buy_count', 0)}") - print(f"卖出次数: {performance.get('sell_count', 0)}") - print(f"总成交金额: {performance.get('total_amount', 0):.2f}") - print(f"总手续费: {performance.get('total_commission', 0):.2f}") - print(f"待成交委托: {performance.get('pending_orders', 0)}") - - except Exception as e: - print(f"❌ 演示过程中出错: {e}") - finally: - strategy.close() - -if __name__ == "__main__": - demo_trading_strategy() diff --git a/src/data_process_model/trade_models.py b/src/data_process_model/trade_models.py deleted file mode 100644 index 21f5bc2..0000000 --- a/src/data_process_model/trade_models.py +++ /dev/null @@ -1,118 +0,0 @@ -""" -交易数据模型 - 基于现有 stock_models.py 的架构 -定义交易委托和成交的数据表结构 -""" - -from peewee import ( - Model, MySQLDatabase, CharField, DateTimeField, - IntegerField, DecimalField, TextField -) -from datetime import datetime -from database_config import DATABASE_CONFIG - -# 复用现有的数据库连接方式 -database = MySQLDatabase(**DATABASE_CONFIG) - -class BaseTradeModel(Model): - """交易数据基础模型""" - class Meta: - database = database - -class TradeOrder(BaseTradeModel): - """ - 交易委托模型 - 记录交易委托的详细信息 - """ - order_id = CharField(primary_key=True, max_length=50, help_text="委托唯一ID") - strategy_id = CharField(max_length=50, help_text="策略ID") - stockcode = CharField(max_length=20, help_text="股票代码") - order_time = DateTimeField(default=datetime.now, help_text="委托时间") - direction = CharField(max_length=10, help_text="交易方向 BUY/SELL") - order_type = CharField(max_length=10, help_text="委托类型 MARKET/LIMIT") - quantity = IntegerField(help_text="委托数量") - price = DecimalField(max_digits=10, decimal_places=3, null=True, help_text="委托价格") - status = CharField(max_length=20, default='PENDING', help_text="委托状态") - notes = TextField(null=True, help_text="备注信息") - created_at = DateTimeField(default=datetime.now, help_text="记录创建时间") - updated_at = DateTimeField(default=datetime.now, help_text="记录更新时间") - - class Meta: - table_name = 'trade_orders' - indexes = ( - # 复合索引优化查询性能 - (('stockcode', 'order_time'), False), - (('strategy_id', 'order_time'), False), - (('status', 'order_time'), False), - ) - -class TradeExecution(BaseTradeModel): - """ - 交易成交模型 - 记录交易成交的详细信息 - """ - execution_id = CharField(primary_key=True, max_length=50, help_text="成交唯一ID") - order_id = CharField(max_length=50, help_text="对应的委托ID") - stockcode = CharField(max_length=20, help_text="股票代码") - execution_time = DateTimeField(default=datetime.now, help_text="成交时间") - price = DecimalField(max_digits=10, decimal_places=3, help_text="成交价格") - quantity = IntegerField(help_text="成交数量") - amount = DecimalField(max_digits=15, decimal_places=2, help_text="成交金额") - commission = DecimalField(max_digits=10, decimal_places=2, default=0, help_text="手续费") - direction = CharField(max_length=10, help_text="交易方向 BUY/SELL") - notes = TextField(null=True, help_text="备注信息") - created_at = DateTimeField(default=datetime.now, help_text="记录创建时间") - - class Meta: - table_name = 'trade_executions' - indexes = ( - # 复合索引优化查询性能 - (('stockcode', 'execution_time'), False), - (('order_id', 'execution_time'), False), - (('direction', 'execution_time'), False), - ) - -def create_trade_tables(): - """ - 创建交易相关数据表 - - Returns: - dict: 创建结果 {table_name: success} - """ - results = {} - - try: - # 连接数据库 - database.connect() - - # 创建委托表 - try: - database.create_tables([TradeOrder], safe=True) - results['trade_orders'] = True - print("✅ 创建交易委托表 trade_orders 成功") - except Exception as e: - results['trade_orders'] = False - print(f"❌ 创建交易委托表失败: {e}") - - # 创建成交表 - try: - database.create_tables([TradeExecution], safe=True) - results['trade_executions'] = True - print("✅ 创建交易成交表 trade_executions 成功") - except Exception as e: - results['trade_executions'] = False - print(f"❌ 创建交易成交表失败: {e}") - - except Exception as e: - print(f"❌ 数据库连接失败: {e}") - results['connection'] = False - finally: - if not database.is_closed(): - database.close() - - return results - -if __name__ == "__main__": - # 测试创建表 - print("开始创建交易数据表...") - results = create_trade_tables() - print(f"创建结果: {results}") diff --git a/src/log/__init__.py b/src/log/__init__.py deleted file mode 100644 index e43c406..0000000 --- a/src/log/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .logger import get_logger - -__all__ = ['get_logger'] diff --git a/src/log/logger.py b/src/log/logger.py deleted file mode 100644 index 4fee570..0000000 --- a/src/log/logger.py +++ /dev/null @@ -1,148 +0,0 @@ -import logging -import datetime -import os -from typing import Optional - -# 全局日志开关,默认为打开 -LOGGING_ENABLED = True - -# 创建logs目录 -LOGS_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'logs') -if not os.path.exists(LOGS_DIR): - os.makedirs(LOGS_DIR) - -# 获取当前时间作为日志文件名的一部分 -current_date = datetime.datetime.now().strftime("%Y%m%d") -current_time = datetime.datetime.now().strftime("%H%M%S") -log_file = os.path.join(LOGS_DIR, f'backtrader_{current_date}-{current_time}.log') - -# 配置日志格式 -LOG_FORMAT = '%(asctime)s - %(levelname)s - %(message)s' -formatter = logging.Formatter(LOG_FORMAT) - -# 设置根日志记录器 -root_logger = logging.getLogger() -root_logger.setLevel(logging.INFO) - -# 清除已有的处理器 -for handler in root_logger.handlers[:]: - root_logger.removeHandler(handler) - -# 添加控制台处理器 -console_handler = logging.StreamHandler() -console_handler.setFormatter(formatter) -root_logger.addHandler(console_handler) - -# 添加文件处理器,使用UTF-8编码解决中文乱码问题 -file_handler = logging.FileHandler(log_file, encoding='utf-8') -file_handler.setFormatter(formatter) -root_logger.addHandler(file_handler) - -class Logger: - """日志记录工具类,包含全局开关控制""" - - @staticmethod - def set_global_logging(enabled: bool = True): - """ - 设置全局日志开关 - - Args: - enabled: True为打开日志,False为关闭日志 - """ - global LOGGING_ENABLED - LOGGING_ENABLED = enabled - if enabled: - logging.info("全局日志已打开") - logging.info(f"日志文件保存在: {os.path.abspath(log_file)}") - - @staticmethod - def is_enabled() -> bool: - """ - 获取当前日志开关状态 - - Returns: - 当前日志是否开启 - """ - return LOGGING_ENABLED - - @staticmethod - def log(message: str, dt: Optional[datetime.date] = None, level: str = "INFO"): - """ - 记录日志 - - Args: - message: 日志消息 - dt: 可选的日期时间 - level: 日志级别 - """ - if not LOGGING_ENABLED: - return - - if dt: - message = f"{dt.isoformat()}, {message}" - - if level.upper() == "DEBUG": - logging.debug(message) - elif level.upper() == "INFO": - logging.info(message) - elif level.upper() == "WARNING": - logging.warning(message) - elif level.upper() == "ERROR": - logging.error(message) - elif level.upper() == "CRITICAL": - logging.critical(message) - else: - logging.info(message) - - @staticmethod - def debug(message: str, dt: Optional[datetime.date] = None): - """记录调试级别日志""" - Logger.log(message, dt, "DEBUG") - - @staticmethod - def info(message: str, dt: Optional[datetime.date] = None): - """记录信息级别日志""" - Logger.log(message, dt, "INFO") - - @staticmethod - def warning(message: str, dt: Optional[datetime.date] = None): - """记录警告级别日志""" - Logger.log(message, dt, "WARNING") - - @staticmethod - def error(message: str, dt: Optional[datetime.date] = None): - """记录错误级别日志""" - Logger.log(message, dt, "ERROR") - - @staticmethod - def critical(message: str, dt: Optional[datetime.date] = None): - """记录严重错误级别日志""" - Logger.log(message, dt, "CRITICAL") - - -# 便捷函数,直接使用静态方法 -def log(message: str, dt: Optional[datetime.date] = None, level: str = "INFO"): - """使用Logger记录日志的便捷函数""" - Logger.log(message, dt, level) - -def set_logging(enabled: bool = True): - """设置全局日志开关的便捷函数""" - Logger.set_global_logging(enabled) - -def is_logging_enabled() -> bool: - """获取全局日志开关状态的便捷函数""" - return Logger.is_enabled() - -# 添加 get_logger 函数,以满足 __init__.py 中的导入需求 -def get_logger(name: str = None): - """ - 获取一个配置好的日志记录器 - - Args: - name: 记录器名称,默认为None时使用根记录器 - - Returns: - 配置好的日志记录器 - """ - logger = logging.getLogger(name) - return logger diff --git a/src/main.py b/src/main.py index 5c6ed50..9d03c89 100644 --- a/src/main.py +++ b/src/main.py @@ -1,153 +1,213 @@ """ -QTrade Socket服务器启动脚本 - 简化版 -专注于同步消息处理和网格策略 +QTrade 服务启动入口 + +支持启动单个服务或所有服务 +用法: + python -m src.main # 启动所有服务 + python -m src.main gateway # 只启动 Gateway + python -m src.main core_service # 只启动 Core Service + python -m src.main data_service # 只启动 Data Service + python -m src.main strategy_engine # 只启动 Strategy Engine """ -import time +import argparse +import asyncio +import signal import sys -import os +from typing import Optional -# 添加项目根目录到Python路径 -sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) +import uvicorn -from strategy import GridStrategy -from network_model.simple_socket_server import SimpleQTradeSocketServerManager +from src.core.config import settings +from src.core.logger import get_logger +from src.core.database import db +from src.core.redis_client import redis_client -# 全局策略实例 -strategy = GridStrategy( - upper_price=8.0, - lower_price=1.0, - grid_step=0.04, - quantity_per_grid=1200, - trend="up_and_down", -) +logger = get_logger("main") -def handle_message(message): - """同步消息处理器 - 包含网格策略""" +# 服务配置映射 +SERVICE_CONFIG = { + "gateway": { + "module": "src.gateway.app:app", + "host": settings.services.gateway.host, + "port": settings.services.gateway.port, + }, + "core_service": { + "module": "src.core_service.app:app", + "host": settings.services.core_service.host, + "port": settings.services.core_service.port, + }, + "data_service": { + "module": "src.data_service.app:app", + "host": settings.services.data_service.host, + "port": settings.services.data_service.port, + }, + "strategy_engine": { + "module": "src.strategy_engine.app:app", + "host": settings.services.strategy_engine.host, + "port": settings.services.strategy_engine.port, + }, +} + + +async def init_infrastructure() -> None: + """初始化基础设施(Redis、数据库)""" + logger.info("正在初始化基础设施...") + try: - # 处理字符串消息 - if isinstance(message, str): - if message == "ping": - return {"type": "response", "data": "pong", "request_id": None} - elif message == "status": - return { - "type": "server_status", - "status": "online", - "strategy": f"GridStrategy({strategy.upper_price}-{strategy.lower_price})", - "timestamp": time.time(), - "request_id": None, - } - else: - return { - "type": "response", - "data": f"Unknown command: {message}", - "request_id": None, - } - - # 处理字典消息 - elif isinstance(message, dict): - request_id = message.get("request_id") - msg_type = message.get("type", "unknown") - - # K线数据更新 - 使用网格策略 - if msg_type == "update_kline": - data = message.get("data", {}) - close_price = data.get("close", 0) - - if close_price <= 0: - return { - "type": "error", - "error": "Invalid close price", - "request_id": request_id, - } - - # 使用网格策略计算信号 - signal = strategy.determine_signal(close_price) - - return { - "type": "trade_signal", - "signal": signal, - "request_id": request_id, - } - - # 获取服务器状态 - elif msg_type == "get_server_status": - return { - "type": "server_status", - "status": "online", - "version": "2.0.0-simplified", - "protocol": "socket", - "strategy": { - "type": "GridStrategy", - "upper_price": strategy.upper_price, - "lower_price": strategy.lower_price, - "grid_step": strategy.grid_step, - "quantity_per_grid": strategy.quantity_per_grid, - }, - "timestamp": time.time(), - "request_id": request_id, - } - - # 测试同步消息 - elif msg_type == "test_sync": - return { - "type": "sync_response", - "message": "Sync message processed successfully", - "received_data": message.get("data"), - "timestamp": time.time(), - "request_id": request_id, - } - - # 未知消息类型 - else: - return { - "type": "error", - "error": f"Unknown message type: {msg_type}", - "request_id": request_id, - } - - # 其他类型消息 - else: - return { - "type": "error", - "error": "Unsupported message type", - "request_id": None, - } - + # 连接 Redis + await redis_client.connect() + logger.info("✓ Redis 连接成功") except Exception as e: - return { - "type": "error", - "error": f"Message processing failed: {str(e)}", - "request_id": message.get("request_id") - if isinstance(message, dict) - else None, - } + logger.warning(f"✗ Redis 连接失败: {e}") + + try: + # 连接数据库 + await db.connect() + logger.info("✓ 数据库连接成功") + except Exception as e: + logger.warning(f"✗ 数据库连接失败: {e}") + + logger.info("基础设施初始化完成") -def main(): - """主函数 - 简化版""" - print("🎯 QTrade Socket Server - 极简版 (单客户端同步 + 网格策略)") - print("=" * 60) - print( - f"📊 网格策略配置: {strategy.upper_price}-{strategy.lower_price}, 步长: {strategy.grid_step}" +async def shutdown_infrastructure() -> None: + """关闭基础设施连接""" + logger.info("正在关闭基础设施...") + + try: + await redis_client.disconnect() + except Exception: + pass + + try: + await db.disconnect() + except Exception: + pass + + logger.info("基础设施已关闭") + + +def run_service(service_name: str) -> None: + """ + 运行单个服务 + + Args: + service_name: 服务名称 + """ + if service_name not in SERVICE_CONFIG: + logger.error(f"未知服务: {service_name}") + logger.info(f"可用服务: {', '.join(SERVICE_CONFIG.keys())}") + sys.exit(1) + + config = SERVICE_CONFIG[service_name] + + logger.info(f"启动服务: {service_name}") + logger.info(f" 地址: http://{config['host']}:{config['port']}") + + uvicorn.run( + config["module"], + host=config["host"], + port=config["port"], + reload=settings.app.debug, + log_level="info" if settings.app.debug else "warning", ) - print("🎯 监听地址: 127.0.0.1:8081 (单客户端)") - print("=" * 60) - # 创建服务器 - server = SimpleQTradeSocketServerManager(host="127.0.0.1", port=8081) - server.set_message_handler(handle_message) - # 启动服务器 +async def run_all_services() -> None: + """ + 运行所有服务(开发模式) + + 注意: 生产环境建议使用 Supervisor 分别管理各服务 + """ + logger.info("=" * 50) + logger.info("QTrade 量化交易系统") + logger.info(f"版本: {settings.app.version}") + logger.info(f"环境: {settings.app.env}") + logger.info("=" * 50) + + # 初始化基础设施 + await init_infrastructure() + + # 创建服务配置列表 + servers = [] + for name, config in SERVICE_CONFIG.items(): + server_config = uvicorn.Config( + config["module"], + host=config["host"], + port=config["port"], + log_level="info", + ) + server = uvicorn.Server(server_config) + servers.append((name, server)) + logger.info(f" {name}: http://{config['host']}:{config['port']}") + + logger.info("-" * 50) + logger.info("按 Ctrl+C 停止所有服务") + + # 启动所有服务 try: - server.start() - except KeyboardInterrupt: - print("\n⚠️ 收到中断信号") - server.stop() - except Exception as e: - print(f"\n❌ 服务器错误: {e}") - server.stop() + await asyncio.gather(*[server.serve() for _, server in servers]) + except asyncio.CancelledError: + pass + finally: + await shutdown_infrastructure() + + +def main() -> None: + """主入口""" + parser = argparse.ArgumentParser( + description="QTrade 服务启动器", + formatter_class=argparse.RawDescriptionHelpFormatter, + epilog=""" +服务列表: + gateway API 网关 (端口 8001) + core_service 核心业务服务 (端口 8010) + data_service 数据服务 (端口 8020) + strategy_engine 策略引擎 (端口 8030) + +示例: + python -m src.main 启动所有服务 + python -m src.main gateway 只启动 Gateway + python -m src.main core_service 只启动 Core Service + """, + ) + + parser.add_argument( + "service", + nargs="?", + choices=list(SERVICE_CONFIG.keys()), + help="要启动的服务名称,不指定则启动所有服务", + ) + + parser.add_argument( + "--host", + type=str, + help="覆盖服务监听地址", + ) + + parser.add_argument( + "--port", + type=int, + help="覆盖服务监听端口", + ) + + args = parser.parse_args() + + if args.service: + # 启动单个服务 + if args.host: + SERVICE_CONFIG[args.service]["host"] = args.host + if args.port: + SERVICE_CONFIG[args.service]["port"] = args.port + run_service(args.service) + else: + # 启动所有服务 + try: + asyncio.run(run_all_services()) + except KeyboardInterrupt: + logger.info("收到退出信号,正在关闭...") if __name__ == "__main__": diff --git a/src/network_model/__init__.py b/src/network_model/__init__.py deleted file mode 100644 index d4ffb63..0000000 --- a/src/network_model/__init__.py +++ /dev/null @@ -1,20 +0,0 @@ -""" -网络模块 - 现代化v2.0架构 -包含HTTP服务器和简化版Socket服务器 -""" - -from .http_server import QTradeHTTPServer -from .http_client import QTradeHTTPClient -from .simple_socket_server import ( - SimpleQTradeSocketServer, - SimpleQTradeSocketServerManager, -) -from .simple_socket_client import SimpleQTradeSocketClient - -__all__ = [ - "QTradeHTTPServer", - "QTradeHTTPClient", - "SimpleQTradeSocketServer", - "SimpleQTradeSocketServerManager", - "SimpleQTradeSocketClient", -] diff --git a/src/network_model/http_client.py b/src/network_model/http_client.py deleted file mode 100644 index a71f4c8..0000000 --- a/src/network_model/http_client.py +++ /dev/null @@ -1,119 +0,0 @@ -""" -QTrade Client v2.0 - 现代化简洁版 -不保证向后兼容性,专注于易用性和性能 -""" - -import json -import urllib.request -import urllib.error -import time -from typing import Dict, Any, Union - - -class QTradeHTTPClient: - """现代化的QTrade HTTP客户端""" - - def __init__(self, host: str = "127.0.0.1", port: int = 8080, timeout: int = 10): - self.base_url = f"http://{host}:{port}" - self.timeout = timeout - self.session_info = None - - def ping(self) -> Union[str, Dict[str, Any]]: - """测试连接""" - return self.send("ping") - - def status(self) -> Dict[str, Any]: - """获取服务器状态""" - try: - response = urllib.request.urlopen( - f"{self.base_url}/api/status", timeout=self.timeout - ) - return json.loads(response.read().decode("utf-8")) - except urllib.error.HTTPError as e: - error_data = e.read().decode("utf-8") - try: - return json.loads(error_data) - except json.JSONDecodeError: - return {"error": f"HTTP {e.code}: {error_data}"} - except Exception as e: - return {"error": f"Request failed: {str(e)}"} - - def health(self) -> Dict[str, Any]: - """健康检查""" - try: - response = urllib.request.urlopen( - f"{self.base_url}/api/health", timeout=self.timeout - ) - return json.loads(response.read().decode("utf-8")) - except urllib.error.HTTPError as e: - error_data = e.read().decode("utf-8") - try: - return json.loads(error_data) - except json.JSONDecodeError: - return {"error": f"HTTP {e.code}: {error_data}"} - except Exception as e: - return {"error": f"Request failed: {str(e)}"} - - def send_kline( - self, symbol: str, close: float, high: float, low: float, volume: int - ) -> Union[str, Dict[str, Any]]: - """发送K线数据""" - message = { - "type": "update_kline", - "data": { - "symbol": symbol, - "close": close, - "high": high, - "low": low, - "volume": volume, - "timestamp": time.time(), - }, - } - return self.send(message) - - def send(self, message: Union[str, Dict[str, Any]]) -> Union[str, Dict[str, Any]]: - """发送消息到服务器""" - try: - # 准备数据 - if isinstance(message, dict): - data = json.dumps(message).encode("utf-8") - else: - data = str(message).encode("utf-8") - - # 创建请求 - req = urllib.request.Request( - url=f"{self.base_url}/api/message", - data=data, - headers={ - "Content-Type": "application/json" - if isinstance(message, dict) - else "text/plain" - }, - ) - - # 发送请求 - with urllib.request.urlopen(req, timeout=self.timeout) as response: - result = response.read().decode("utf-8") - - # 尝试解析JSON - try: - return json.loads(result) - except json.JSONDecodeError: - return result - - except urllib.error.HTTPError as e: - error_data = e.read().decode("utf-8") - try: - return json.loads(error_data) - except json.JSONDecodeError: - return {"error": f"HTTP {e.code}: {error_data}"} - except Exception as e: - return {"error": f"Request failed: {str(e)}"} - - def __enter__(self): - """上下文管理器支持""" - return self - - def __exit__(self, exc_type, exc_val, exc_tb): - """上下文管理器退出""" - pass diff --git a/src/network_model/http_server.py b/src/network_model/http_server.py deleted file mode 100644 index 7c71750..0000000 --- a/src/network_model/http_server.py +++ /dev/null @@ -1,154 +0,0 @@ -""" -QTrade HTTP服务器 - 现代化简洁版 -不保证向后兼容性,专注于性能和简洁性 -""" -import json -import time -from http.server import HTTPServer, BaseHTTPRequestHandler -from typing import Any, Callable - - -class QTradeHTTPServer(HTTPServer): - """扩展的HTTP服务器,包含QTrade特定属性""" - - def __init__(self, server_address, RequestHandlerClass, message_handler: Callable[[Any], Any]): - super().__init__(server_address, RequestHandlerClass) - self.message_handler = message_handler - self.start_time = time.time() - -class QTradeHTTPHandler(BaseHTTPRequestHandler): - """简化的HTTP请求处理器""" - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - # 类型注解:明确指定 server 是 QTradeHTTPServer 类型 - self.server: QTradeHTTPServer - - def do_POST(self): - """处理POST请求""" - if self.path == '/api/message': - self._handle_message() - else: - self._send_error(404, "Endpoint not found") - - def do_GET(self): - """处理GET请求""" - if self.path == '/api/status': - self._handle_status() - elif self.path == '/api/health': - self._send_json({"status": "healthy", "timestamp": time.time()}) - else: - self._send_error(404, "Endpoint not found") - - def _handle_message(self): - """处理消息请求""" - try: - # 读取和解析请求数据 - content_length = int(self.headers.get('Content-Length', 0)) - raw_data = self.rfile.read(content_length).decode('utf-8') - - # 自动检测JSON或文本 - message = self._parse_message(raw_data) - - # 处理消息 - response = self.server.message_handler(message) - self._send_json(response) - - except Exception as e: - self._send_error(500, f"Message processing error: {str(e)}") - - def _handle_status(self): - """处理状态请求""" - status = { - "status": "online", - "version": "2.0.0", - "timestamp": time.time(), - "uptime": time.time() - self.server.start_time, - "protocol": "http" - } - self._send_json(status) - - def _parse_message(self, raw_data): - """智能解析消息""" - if not raw_data: - return "" - - # 尝试JSON解析 - try: - return json.loads(raw_data) - except json.JSONDecodeError: - # 返回原始文本 - return raw_data.strip() - - def _send_json(self, data): - """发送JSON响应""" - response_data = json.dumps(data, ensure_ascii=False).encode('utf-8') - - self.send_response(200) - self.send_header('Content-Type', 'application/json; charset=utf-8') - self.send_header('Content-Length', str(len(response_data))) - self.send_header('Access-Control-Allow-Origin', '*') - self.end_headers() - - self.wfile.write(response_data) - - def _send_error(self, code, message): - """发送错误响应""" - error_data = { - "error": message, - "code": code, - "timestamp": time.time() - } - - response_data = json.dumps(error_data).encode('utf-8') - - self.send_response(code) - self.send_header('Content-Type', 'application/json; charset=utf-8') - self.send_header('Content-Length', str(len(response_data))) - self.end_headers() - - self.wfile.write(response_data) - - def log_message(self, format, *args): - """禁用默认日志""" - pass - -class QTradeHTTPServerManager: - """简化的QTrade HTTP服务器管理器""" - - def __init__(self, host='127.0.0.1', port=8080): - self.host = host - self.port = port - self.start_time = time.time() - self.message_handler = None - self._server = None - - def set_message_handler(self, handler): - """设置消息处理器""" - self.message_handler = handler - - def start(self): - """启动HTTP服务器""" - if not self.message_handler: - raise ValueError("Message handler must be set before starting server") - - # 创建服务器 - self._server = QTradeHTTPServer( - (self.host, self.port), - QTradeHTTPHandler, - self.message_handler - ) - - print(f"🚀 QTrade HTTP服务器启动 - {self.host}:{self.port}") - - try: - self._server.serve_forever() - except KeyboardInterrupt: - self.stop() - - def stop(self): - """停止HTTP服务器""" - if self._server: - print("\n🛑 正在关闭HTTP服务器...") - self._server.shutdown() - print("✅ HTTP服务器已关闭") \ No newline at end of file diff --git a/src/network_model/simple_socket_client.py b/src/network_model/simple_socket_client.py deleted file mode 100644 index 8c0c870..0000000 --- a/src/network_model/simple_socket_client.py +++ /dev/null @@ -1,141 +0,0 @@ -""" -QTrade Socket客户端 - 简化版 -只支持同步通信,专注于与网格策略交互 -""" - -import json -import socket -import time -from typing import Any -import logging - -# 配置日志 - 只显示WARNING和ERROR -logging.basicConfig(level=logging.WARNING) -logger = logging.getLogger(__name__) - - -class SimpleQTradeSocketClient: - """简化版QTrade Socket客户端 - 同步通信""" - - def __init__(self, host="127.0.0.1", port=8081): - self.host = host - self.port = port - self.socket = None - self.is_connected = False - - def connect(self) -> bool: - """连接到服务器""" - try: - # 初始化连接(保留) - print(f"🔗 正在连接到 {self.host}:{self.port}") - - self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.socket.settimeout(10) # 10秒超时 - self.socket.connect((self.host, self.port)) - - self.is_connected = True - print("✅ 连接成功") - - # 接收欢迎消息 - welcome_data = self.socket.recv(4096) - if welcome_data: - self._parse_message(welcome_data.decode("utf-8")) - # 移除欢迎消息的info日志 - - return True - - except ConnectionRefusedError as e: - print("❌ 连接被拒绝: Socket服务器可能没有启动") - print( - " 请先启动服务器: python example_and_demos/socket/run_socket_server.py" - ) - print(f" 详细错误: {e}") - self.is_connected = False - return False - except Exception as e: - logger.error(f"❌ 连接失败: {e}") - self.is_connected = False - return False - - def disconnect(self): - """断开连接""" - # 移除正常断开连接的info日志 - self.is_connected = False - - if self.socket: - try: - self.socket.close() - except Exception: - pass - - # 移除连接断开的info日志 - - def send_message_sync(self, message: Any, timeout: float = 10.0) -> Any: - """同步发送消息并等待响应""" - if not self.is_connected or not self.socket: - logger.error("❌ 未连接到服务器") - return None - - try: - # 发送消息 - if isinstance(message, dict): - data = json.dumps(message, ensure_ascii=False) - else: - data = str(message) - - self.socket.send(data.encode("utf-8")) - # 移除发送消息的info日志 - - # 等待响应 - self.socket.settimeout(timeout) - response_data = self.socket.recv(4096) - - if response_data: - response = self._parse_message(response_data.decode("utf-8")) - # 移除收到响应的info日志 - return response - else: - logger.error("❌ 收到空响应") - return None - - except socket.timeout: - logger.error(f"❌ 消息超时: {timeout}秒") - return None - except Exception as e: - logger.error(f"❌ 发送消息失败: {e}") - return None - - def _parse_message(self, raw_data: str): - """解析消息""" - if not raw_data: - return "" - - try: - # 尝试JSON解析 - return json.loads(raw_data) - except json.JSONDecodeError: - # 返回原始文本 - return raw_data.strip() - - def ping(self) -> dict: - """发送ping消息""" - return self.send_message_sync("ping") - - def get_server_status(self) -> dict: - """获取服务器状态""" - return self.send_message_sync( - {"type": "get_server_status", "timestamp": time.time()} - ) - - def send_kline_update(self, close_price: float) -> dict: - """发送K线更新""" - return self.send_message_sync( - { - "type": "update_kline", - "data": {"close": close_price, "timestamp": time.time()}, - } - ) - - def test_sync_message(self, data: str) -> dict: - """测试同步消息""" - return self.send_message_sync({"type": "test_sync", "data": data}) diff --git a/src/network_model/simple_socket_server.py b/src/network_model/simple_socket_server.py deleted file mode 100644 index 784a7d2..0000000 --- a/src/network_model/simple_socket_server.py +++ /dev/null @@ -1,180 +0,0 @@ -""" -QTrade Socket服务器 - 简化版 -只支持单客户端同步通信,专注于网格策略处理 -""" - -import json -import socket -import time -from typing import Any, Callable -import logging - -# 配置日志 - 只显示WARNING和ERROR -logging.basicConfig(level=logging.WARNING) -logger = logging.getLogger(__name__) - - -class SimpleQTradeSocketServer: - """简化版QTrade Socket服务器 - 单客户端同步通信""" - - def __init__(self, host="127.0.0.1", port=8081): - self.host = host - self.port = port - self.message_handler = None - self.is_running = False - self.server_socket = None - self.client_socket = None - - def set_message_handler(self, handler: Callable[[Any], Any]): - """设置消息处理器""" - self.message_handler = handler - - def start(self): - """启动Socket服务器""" - if not self.message_handler: - raise ValueError("Message handler must be set before starting server") - - self.is_running = True - - # 创建服务器socket - self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - self.server_socket.bind((self.host, self.port)) - self.server_socket.listen(1) # 只允许一个客户端连接 - - # 保留服务器启动日志(初始化) - print(f"🚀 简化版Socket服务器启动 - {self.host}:{self.port}") - - try: - while self.is_running: - # 等待客户端连接(移除info日志) - client_socket, client_address = self.server_socket.accept() - - # 保留客户端连接日志(重要状态) - print(f"✅ 客户端已连接: {client_address}") - self.client_socket = client_socket - - # 发送欢迎消息 - welcome_msg = { - "type": "welcome", - "message": "Connected to Simple QTrade Socket Server", - "client_address": str(client_address), - "timestamp": time.time(), - } - self._send_message(welcome_msg) - - # 处理客户端消息 - self._handle_client_messages() - - except Exception as e: - logger.error(f"❌ 服务器错误: {e}") - finally: - self.stop() - - def _handle_client_messages(self): - """处理客户端消息 - 同步方式""" - try: - while self.is_running and self.client_socket: - try: - # 接收消息 - data = self.client_socket.recv(4096) - if not data: - # 移除客户端断开连接的info日志 - break - - # 解析消息 - message = self._parse_message(data.decode("utf-8")) - # 移除收到消息的info日志 - - # 处理消息 - if self.message_handler: - response = self.message_handler(message) - - # 发送响应 - self._send_message(response) - # 移除发送响应的info日志 - else: - # 默认响应 - self._send_message({"error": "No message handler configured"}) - - except socket.timeout: - continue - except Exception as e: - logger.error(f"❌ 处理消息失败: {e}") - break - - except Exception as e: - logger.error(f"❌ 客户端处理异常: {e}") - finally: - if self.client_socket: - self.client_socket.close() - self.client_socket = None - - def _parse_message(self, raw_data: str): - """解析消息""" - if not raw_data: - return "" - - try: - # 尝试JSON解析 - return json.loads(raw_data) - except json.JSONDecodeError: - # 返回原始文本 - return raw_data.strip() - - def _send_message(self, message: Any): - """发送消息给客户端""" - if not self.client_socket: - return False - - try: - if isinstance(message, dict): - data = json.dumps(message, ensure_ascii=False) - else: - data = str(message) - - self.client_socket.send(data.encode("utf-8")) - return True - except Exception as e: - logger.error(f"❌ 发送消息失败: {e}") - return False - - def stop(self): - """停止服务器""" - logger.info("🛑 正在停止服务器...") - self.is_running = False - - if self.client_socket: - try: - self.client_socket.close() - except Exception: - pass - self.client_socket = None - - if self.server_socket: - try: - self.server_socket.close() - except Exception: - pass - self.server_socket = None - - logger.info("✅ 服务器已停止") - - -class SimpleQTradeSocketServerManager: - """简化版Socket服务器管理器""" - - def __init__(self, host="127.0.0.1", port=8081): - self.server = SimpleQTradeSocketServer(host, port) - - def set_message_handler(self, handler: Callable[[Any], Any]): - """设置消息处理器""" - self.server.set_message_handler(handler) - - def start(self): - """启动服务器""" - self.server.start() - - def stop(self): - """停止服务器""" - self.server.stop() diff --git a/src/strategy/__init__.py b/src/strategy/__init__.py deleted file mode 100644 index c7b9619..0000000 --- a/src/strategy/__init__.py +++ /dev/null @@ -1,8 +0,0 @@ -""" -策略模块 -包含各种交易策略的实现 -""" - -from .grid_strategy import GridStrategy - -__all__ = ["GridStrategy"] diff --git a/src/strategy/grid_strategy.py b/src/strategy/grid_strategy.py deleted file mode 100644 index e0b488e..0000000 --- a/src/strategy/grid_strategy.py +++ /dev/null @@ -1,131 +0,0 @@ -import numpy as np - - -class GridStrategy: - def __init__( - self, - upper_price, - lower_price, - grid_step, - quantity_per_grid=2000, - trend="up_and_down", - ): - """ - 网格交易策略 - :param upper_price: 网格上限价格 - :param lower_price: 网格下限价格 - :param grid_step: 每格相差的价格 - :param quantity_per_grid: 每笔交易股数 - :param trend: 趋势判断 'up'上升趋势, 'down'下降趋势, 'up_and_down'震荡 - """ - # 参数有效性检查 - if upper_price <= lower_price: - raise ValueError("上限价格必须大于下限价格") - if grid_step <= 0: - raise ValueError("每格相差的价格必须大于0") - if quantity_per_grid <= 0: - raise ValueError("每笔交易股数必须大于0") - if trend not in ["up", "down", "up_and_down"]: - raise ValueError("趋势参数必须是 'up', 'down' 或 'up_and_down'") - - self.upper_price = upper_price - self.lower_price = lower_price - self.grid_step = grid_step - self.quantity_per_grid = quantity_per_grid - - # 根据价格步长计算网格数量和价格点 - self.grid_num = int((upper_price - lower_price) / grid_step) + 1 - self.grid_prices = np.arange(lower_price, upper_price + grid_step, grid_step) - - self.current_index = None # 当前活跃的网格索引 - self.trend = trend - - def determine_signal(self, current_price, trend=None): - """ - 生成交易信号 - :param current_price: 当前价格 - :param trend: 趋势判断,可选参数,默认为None - :return: 交易信号字典 - """ - # 更新趋势(如果提供了新趋势) - if trend and trend in ["up", "down", "up_and_down"]: - self.trend = trend - - # 初始化信号 - signal = {"action": "hold", "qty": 0, "price": current_price} - - # 超出网格范围,不交易 - if current_price < self.lower_price or current_price > self.upper_price: - return signal - - # 首次进入,确定当前活跃价格线 - if self.current_index is None: - # 找到当前价格上方最近的网格线作为活跃线 - self.current_index = 0 - for i, price_line in enumerate(self.grid_prices): - if current_price < price_line: - self.current_index = i - break - signal["action"] = "buy" - signal["qty"] = int(self.quantity_per_grid) - signal["price"] = current_price - return signal - - # 根据趋势判断交易信号 - if self.trend == "up": - # 上升趋势:向上穿越2条线卖出,向下穿越1条线买入 - if self.current_index + 2 < self.grid_num and self.current_index - 1 >= 0: - upper_active_price = self.grid_prices[self.current_index + 2] - lower_active_price = self.grid_prices[self.current_index - 1] - - if current_price >= upper_active_price: - signal["action"] = "sell" - signal["qty"] = int(self.quantity_per_grid) - signal["price"] = current_price - self.current_index += 2 - elif current_price <= lower_active_price: - signal["action"] = "buy" - signal["qty"] = int(self.quantity_per_grid) - signal["price"] = current_price - self.current_index -= 1 - - elif self.trend == "down": - # 下降趋势:向下穿越2条线买入,向上穿越1条线卖出 - if self.current_index - 2 >= 0 and self.current_index + 1 < self.grid_num: - lower_active_price = self.grid_prices[self.current_index - 2] - upper_active_price = self.grid_prices[self.current_index + 1] - - if current_price <= lower_active_price: - signal["action"] = "buy" - signal["qty"] = int(self.quantity_per_grid) - signal["price"] = current_price - self.current_index -= 2 - elif current_price >= upper_active_price: - signal["action"] = "sell" - signal["qty"] = int(self.quantity_per_grid) - signal["price"] = current_price - self.current_index += 1 - - else: - # 震荡趋势:向上穿越1条线卖出,向下穿越1条线买入 - if self.current_index + 1 < self.grid_num and self.current_index - 1 >= 0: - upper_active_price = self.grid_prices[self.current_index + 1] - lower_active_price = self.grid_prices[self.current_index - 1] - - if current_price >= upper_active_price: - signal["action"] = "sell" - signal["qty"] = int(self.quantity_per_grid) - signal["price"] = current_price - self.current_index += 1 - elif current_price <= lower_active_price: - signal["action"] = "buy" - signal["qty"] = int(self.quantity_per_grid) - signal["price"] = current_price - self.current_index -= 1 - # print(f"signal & price: {signal} - {current_price}") - # print(f"[ {self.grid_prices[self.current_index-1]} - {self.grid_prices[self.current_index]} - {self.grid_prices[self.current_index+1]} ]") - return signal - - def reset(self): - """重置策略状态""" - self.current_index = None diff --git a/test/test_simple_socket.py b/test/test_simple_socket.py deleted file mode 100644 index 7ad32f7..0000000 --- a/test/test_simple_socket.py +++ /dev/null @@ -1,55 +0,0 @@ -#!/usr/bin/env python3 -""" -简化版Socket通信测试 -测试极简版Socket服务器和客户端 -""" - -import sys -import os -import time - -# 添加项目根目录到Python路径 -sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -from src.network_model.simple_socket_client import SimpleQTradeSocketClient - - -def test_simple_socket_communication(): - """测试简化版Socket通信""" - print("🧪 简化版Socket通信测试") - print("=" * 50) - - # 创建客户端 - client = SimpleQTradeSocketClient("127.0.0.1", 8081) - - try: - # 连接测试 - if client.connect(): - print("✅ 连接成功") - - # 测试各种消息类型 - test_cases = [ - ("ping", "Ping测试"), - ({"type": "get_server_status"}, "获取服务器状态"), - ({"type": "update_kline", "data": {"close": 5.0}}, "K线数据更新"), - ({"type": "test_sync", "data": "测试数据"}, "同步消息测试"), - ] - - for message, description in test_cases: - print(f"\n🔸 {description}") - response = client.send_message_sync(message) - print(f"响应: {response}") - time.sleep(0.5) - - print("\n✅ 所有测试完成") - else: - print("❌ 连接失败") - - except Exception as e: - print(f"❌ 测试过程中发生错误: {e}") - finally: - client.disconnect() - - -if __name__ == "__main__": - test_simple_socket_communication() diff --git a/test/test_socket_only.py b/test/test_socket_only.py deleted file mode 100644 index a7120c8..0000000 --- a/test/test_socket_only.py +++ /dev/null @@ -1,112 +0,0 @@ -#!/usr/bin/env python3 -""" -简单的Socket服务器和客户端测试 -""" - -import sys -import os -import time -import threading - -# 添加项目根目录到Python路径 -sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) - -from src.network_model.simple_socket_server import SimpleQTradeSocketServerManager -from src.network_model.simple_socket_client import SimpleQTradeSocketClient - - -def handle_message(message): - """消息处理器""" - try: - if isinstance(message, str): - if message == "ping": - return "pong" - elif message == "status": - return {"status": "online", "version": "2.0.0"} - else: - return f"Echo: {message}" - - # 处理价格数据 - if isinstance(message, dict) and "type" in message: - if message["type"] == "kline": - # 模拟网格策略处理 - price = message.get("price", 0) - return { - "type": "trade_signal", - "signal": {"action": "buy", "qty": 1200, "price": price}, - "processed_price": price, - } - - return {"status": "processed", "message": message} - except Exception as e: - return {"error": str(e)} - - -def start_server(): - """启动服务器""" - server = SimpleQTradeSocketServerManager(host="127.0.0.1", port=8081) - server.set_message_handler(handle_message) - - try: - print("🚀 启动Socket服务器...") - server.start() - except Exception as e: - print(f"❌ 服务器启动失败: {e}") - - -def test_client(): - """测试客户端""" - time.sleep(1) # 等待服务器启动 - - client = SimpleQTradeSocketClient("127.0.0.1", 8081) - - if not client.connect(): - print("❌ 客户端连接失败") - return - - print("✅ 客户端连接成功") - - try: - # 测试1: Ping - print("\n=== Ping测试 ===") - ping_response = client.ping() - print(f"Ping响应: {ping_response}") - - # 测试2: 状态 - print("\n=== 状态测试 ===") - status = client.get_server_status() - print(f"状态响应: {status}") - - # 测试3: K线数据 - print("\n=== K线数据测试 ===") - kline_response = client.send_kline_update(5.0) - print(f"K线响应: {kline_response}") - - # 测试4: 同步消息 - print("\n=== 同步消息测试 ===") - sync_response = client.test_sync_message("测试消息") - print(f"同步响应: {sync_response}") - - print("\n✅ 所有测试完成") - - except Exception as e: - print(f"❌ 测试出错: {e}") - finally: - client.disconnect() - - -def main(): - """主函数""" - print("🎯 QTrade Socket测试") - print("=" * 50) - - # 在后台线程启动服务器 - server_thread = threading.Thread(target=start_server, daemon=True) - server_thread.start() - - # 运行客户端测试 - test_client() - - -if __name__ == "__main__": - main() diff --git a/tests/README.md b/tests/README.md new file mode 100644 index 0000000..7afecf9 --- /dev/null +++ b/tests/README.md @@ -0,0 +1,288 @@ +# tests 目录 + +## 🧪 用途 + +存放**单元测试与集成测试的代码和用例**。 + +## 📋 测试类型 + +### 1. 单元测试(Unit Tests) +测试单个函数或类的功能。 + +**特点**: +- 快速执行 +- 独立运行 +- 测试单一功能 + +**示例**: +```python +def test_data_processor_clean(): + """测试数据清洗功能""" + processor = KlineDataProcessor() + df = create_test_data() + + result = processor.clean_data(df) + + assert result is not None + assert len(result) > 0 + assert result.isnull().sum().sum() == 0 # 无空值 +``` + +### 2. 集成测试(Integration Tests) +测试多个模块的协作和完整流程。 + +**特点**: +- 执行较慢 +- 需要环境准备 +- 测试完整流程 + +**示例**: +```python +def test_socket_communication(): + """测试 Socket 完整通信流程""" + # 启动服务器 + server = SimpleQTradeSocketServer() + server.start() + + # 连接客户端 + client = SimpleQTradeSocketClient() + client.connect() + + # 发送消息 + client.send({"type": "ping"}) + + # 接收响应 + response = client.receive() + assert response['type'] == 'pong' + + # 清理 + client.disconnect() + server.stop() +``` + +## 🗂️ 目录结构(推荐) + +``` +tests/ +├── unit/ # 单元测试 +│ ├── test_data_processor.py +│ ├── test_grid_strategy.py +│ └── test_database.py +│ +├── integration/ # 集成测试 +│ ├── test_socket_server.py +│ ├── test_http_api.py +│ └── test_strategy_flow.py +│ +├── fixtures/ # 测试数据 +│ ├── sample_kline.csv +│ └── test_config.yaml +│ +└── conftest.py # pytest 配置 +``` + +## 🚀 运行测试 + +### 运行所有测试 +```bash +pytest tests/ -v +``` + +### 运行指定测试文件 +```bash +pytest tests/test_simple_socket.py -v +``` + +### 运行指定测试函数 +```bash +pytest tests/test_simple_socket.py::test_connection -v +``` + +### 带覆盖率报告 +```bash +pytest tests/ --cov=src --cov-report=html +``` + +查看覆盖率报告: 打开 `htmlcov/index.html` + +### 只运行失败的测试 +```bash +pytest --lf +``` + +### 并行运行(需安装 pytest-xdist) +```bash +pytest tests/ -n auto +``` + +## ✍️ 编写测试 + +### 1. 测试文件命名 + +- ✅ `test_*.py` - 测试文件 +- ✅ `*_test.py` - 也可以 +- ❌ `test.py` - 太通用,避免 + +### 2. 测试函数命名 + +- ✅ `test_function_name()` - 测试某个功能 +- ✅ `test_function_name_with_condition()` - 测试特定条件 +- ❌ `my_test()` - 不以 test_ 开头 + +### 3. 测试结构(AAA 模式) + +```python +def test_example(): + # Arrange - 准备测试数据 + data = {"key": "value"} + processor = DataProcessor() + + # Act - 执行被测试的功能 + result = processor.process(data) + + # Assert - 验证结果 + assert result == expected_value +``` + +### 4. 使用 fixtures + +```python +import pytest + +@pytest.fixture +def sample_data(): + """准备测试数据""" + return {"symbol": "601398.SH", "price": 5.23} + +def test_with_fixture(sample_data): + """使用 fixture 的测试""" + assert sample_data['symbol'] == "601398.SH" +``` + +## 📝 测试用例设计 + +### 正常场景 +测试正常输入和预期输出。 + +```python +def test_calculate_returns_normal(): + df = pd.DataFrame({'close': [10, 11, 12]}) + result = calculate_returns(df) + assert len(result) == 3 +``` + +### 边界条件 +测试边界值和特殊情况。 + +```python +def test_calculate_returns_empty(): + df = pd.DataFrame() + with pytest.raises(ValueError): + calculate_returns(df) +``` + +### 异常情况 +测试错误处理。 + +```python +def test_connect_with_wrong_port(): + client = SocketClient(port=99999) + with pytest.raises(ConnectionError): + client.connect() +``` + +## 🎯 测试覆盖率目标 + +| 模块 | 目标覆盖率 | +| ------------ | ---------- | +| 核心业务逻辑 | 90%+ | +| 数据处理 | 85%+ | +| 网络通信 | 80%+ | +| 策略逻辑 | 90%+ | +| 工具函数 | 70%+ | + +## ⚡ 测试最佳实践 + +### ✅ 应该做的 + +1. **测试要独立** - 不依赖其他测试 +2. **测试要快速** - 单元测试毫秒级 +3. **测试要明确** - 一个测试一个断言 +4. **使用 fixtures** - 复用测试数据 +5. **测试要可重复** - 每次结果一致 + +### ❌ 不应该做的 + +1. ❌ 测试依赖外部服务(数据库、API)- 使用 mock +2. ❌ 测试包含随机性 - 固定随机种子 +3. ❌ 测试修改全局状态 - 使用 fixtures 隔离 +4. ❌ 测试写死路径 - 使用相对路径 +5. ❌ 测试没有断言 - 每个测试必须有 assert + +## 🛠️ 测试工具 + +### pytest +```bash +pip install pytest +``` + +主要测试框架,功能强大。 + +### pytest-cov +```bash +pip install pytest-cov +``` + +代码覆盖率报告。 + +### pytest-mock +```bash +pip install pytest-mock +``` + +Mock 和 Patch 工具。 + +### pytest-xdist +```bash +pip install pytest-xdist +``` + +并行运行测试。 + +## 📖 示例 + +完整示例请查看现有测试文件: +- `tests/test_simple_socket.py` - Socket 测试 +- `tests/test_socket_only.py` - 基础测试 + +## 🐛 调试测试 + +### 在失败时进入调试器 +```bash +pytest --pdb +``` + +### 查看打印输出 +```bash +pytest -s +``` + +### 只运行标记的测试 +```python +@pytest.mark.slow +def test_slow_operation(): + pass + +# 运行 +pytest -m slow +``` + +## 📚 参考资料 + +- [pytest 官方文档](https://docs.pytest.org/) +- [测试驱动开发(TDD)](https://en.wikipedia.org/wiki/Test-driven_development) +- Python 测试最佳实践 + +--- + +**保持测试,保持质量!** ✨