## 1. Project Overview & Quickstart (yutiansut/QUANTAXIS) ## File: README.md # QUANTAXIS 2.1.0-alpha2 > 🚀 **全新升级**: Python 3.9+、QARS2 Rust核心集成、100x性能提升 > > **最新版本**: v2.1.0-alpha2 | **Python**: 3.9-3.12 | **更新日期**: 2025-10-25 --- ## 🌟 新特性 (v2.1.0) ### ⚡ QARS2 Rust核心集成 - 性能飞跃 - **100x账户操作加速**: 创建账户从50ms降至0.5ms - **10x回测速度提升**: 10年日线回测从30秒降至3秒 - **90%内存优化**: 大规模持仓内存占用降低90% - **无缝集成**: 完全兼容QIFI协议,自动回退Python实现 ### 🔧 Python 3.9-3.12 现代化 - **依赖升级**: 60+核心依赖现代化 (pymongo 4.10+, pandas 2.0+, pyarrow 15.0+) - **性能优化**: 利用Python 3.11+的性能提升 - **类型安全**: 更好的类型提示支持 ### 📦 QARSBridge - Rust桥接层 ```python from QUANTAXIS.QARSBridge import QARSAccount, has_qars_support # 自动检测并使用Rust高性能版本 if has_qars_support(): print("✨ 使用QARS2 Rust版本 (100x性能)") account = QARSAccount("my_account", init_cash=1000000) # API完全兼容,无需修改代码 account.buy("000001", 10.5, "2025-01-15", 1000) ``` --- ## 🔗 相关项目生态 ### 核心项目 - 🦀 [**QARS2**](https://github.com/yutiansut/qars2) - QUANTAXIS Rust核心 (高性能账户、回测引擎) - ⚡ [**QADataSwap**](https://github.com/QUANTAXIS/qadataswap) - 跨语言零拷贝通信 (Python/Rust/C++) - 🏛️ [**QAEXCHANGE-RS**](https://github.com/yutiansut/qaexchange-rs) - Rust交易所 + HTAP混合数据库 ### 扩展实现 - 📊 [**QAUltra-cpp**](https://github.com/QUANTAXIS/qaultra-cpp) - QUANTAXIS C++实现 - 🔥 [**QAUltra-rs**](https://github.com/QUANTAXIS/qautlra-rs) - QUANTAXIS Rust实现 (部分开源) [](https://github.com/quantaxis/quantaxis/watchers) [](https://github.com/quantaxis/quantaxis/stargazers) [](https://github.com/quantaxis/quantaxis/fork) [点击右上角Star和Watch来跟踪项目进展! 点击Fork来创建属于你的QUANTAXIS!] --- ## 📞 联系方式 - **项目主页**: https://github.com/yutiansut/QUANTAXIS - **作者**: yutiansut - **Email**: yutiansut@qq.com - **微信公众号**: QAPRO - **微信**: quantitativeanalysis --- 更多文档在[QABook Release](https://github.com/QUANTAXIS/QUANTAXIS/releases/download/latest/quantaxis.pdf) Quantitative Financial FrameWork ## 📚 核心模块 ### 1. 🦀 QARSBridge - Rust桥接层 (v2.1新增) **QARS2 Rust核心的Python包装器,提供100x性能提升** - **QARSAccount**: 高性能QIFI账户系统 - 股票交易: `buy()`, `sell()` - 期货交易: `buy_open()`, `sell_open()`, `buy_close()`, `sell_close()` - 账户查询: `get_qifi()`, `get_positions()`, `get_account_info()` - 完全兼容QIFI协议,跨语言一致性 (Python/Rust/C++) - **QARSBacktest**: Rust回测引擎 - 10x回测速度提升 - 支持自定义策略 (`QARSStrategy`基类) - 内存占用降低90% - **自动回退机制**: QARS2未安装时自动使用纯Python实现 ```python # 完整示例 from QUANTAXIS.QARSBridge import QARSAccount account = QARSAccount("test", init_cash=1000000) account.buy("000001", 10.5, "2025-01-15", 1000) # 股票买入 account.buy_open("IF2512", 4500.0, "2025-01-15", 2) # 期货开仓 positions = account.get_positions() # 查询持仓 ``` 📖 **详细文档**: [QARSBridge README](./QUANTAXIS/QARSBridge/README.md) --- ### 2. 🔄 QADataBridge - 零拷贝数据交换 (v2.1新增) **基于QADataSwap的跨语言零拷贝数据传输,5-10x性能提升** - **零拷贝转换**: - Pandas ↔ Polars (2.5x加速) - Pandas ↔ Arrow (零拷贝) - Polars ↔ Arrow (零拷贝) - 批量转换支持 - **共享内存通信**: - 跨进程数据传输 (7x加速) - 实时行情分发 - 策略间数据共享 - **自动回退机制**: QADataSwap未安装时自动使用标准转换 ```python # 零拷贝转换示例 from QUANTAXIS.QADataBridge import convert_pandas_to_polars import pandas as pd df_pandas = pd.DataFrame({'price': [10.5, 20.3], 'volume': [1000, 2000]}) df_polars = convert_pandas_to_polars(df_pandas) # 零拷贝,2.5x加速 # 共享内存示例 from QUANTAXIS.QADataBridge import SharedMemoryWriter, SharedMemoryReader # 进程A:写入数据 writer = SharedMemoryWriter("market_data", size_mb=50) writer.write(df_polars) # 进程B:读取数据 reader = SharedMemoryReader("market_data") df = reader.read(timeout_ms=5000) # 零拷贝,7x加速 ``` 📖 **详细文档**: [QADataBridge README](./QUANTAXIS/QADataBridge/README.md) --- ### 3. 💾 QASU / QAFetch - 多市场数据 - 支持MongoDB / ClickHouse存储 - 自动运维和数据更新 - Tick / L2 Order / Transaction数据格式 - 因子化数据结构 ### 4. 🕐 QAUtil - 工具函数 - 交易时间、交易日历 - 时间向前向后推算 - 市场识别、DataFrame转换 ### 5. 💼 QIFI / QAMarket - 统一账户体系 **多市场、多语言统一账户协议** - **qifiaccount**: 标准QIFI账户,与Rust/C++版本保持100%一致 - **qifimanager**: 多账户管理系统 - **qaposition**: 单标的精准仓位管理 (套利/CTA/股票) - **marketpreset**: 市场预制基类 (tick大小/保证金/手续费) **QIFI协议特点**: - 跨语言兼容 (Python/Rust/C++) - 完整账户状态 (账户/持仓/订单/成交) - 增量更新支持 (Diff机制) - MongoDB友好 ### 6. 📊 QAFactor - 因子研究 - 单因子研究入库 - 因子管理、测试 - 因子合并 - 优化器 [开发中] ### 7. 📈 QAData - 内存数据库 多标的多市场数据结构,支持: - 实时计算 - 回测引擎 - 高性能数据访问 ### 8. 📉 QAIndicator - 自定义指标 - 支持自定义指标编写 - 批量全市场apply - 因子表达式构建 ### 9. ⚙️ QAEngine - 异步计算 - 自定义线程/进程基类 - 异步计算支持 - 局域网分布式计算agent ### 10. 📮 QAPubSub - 消息队列 基于RabbitMQ的消息系统: - 1-1 / 1-n / n-n 消息分发 - 计算任务分发收集 - 实时订单流 ### 11. 🎯 QAStrategy - 回测套件 - CTA策略回测 - 套利策略回测 - 完整QIFI模式支持 ### 12. 🌐 QAWebServer - 微服务 - Tornado Web服务器 - 中台微服务构建 - RESTful API ### 13. 📅 QASchedule - 任务调度 - 后台任务调度 - 自动运维 - 远程任务调度 --- ## 🆕 版本更新说明 ### v2.1.0 (2025-10-25) - 重大性能升级 #### 🚀 核心升级 **1. QARS2 Rust核心集成** - ✅ QARSBridge桥接层 - 100x性能提升 - ✅ 完全兼容QIFI协议 - ✅ 自动fallback到Python实现 - ✅ 账户操作: 50ms → 0.5ms - ✅ 回测速度: 30s → 3s (10年日线) - ✅ 内存优化: -90% **2. Python现代化** - ✅ Python版本: 3.5-3.10 → **3.9-3.12** - ✅ 依赖升级: 60+核心依赖现代化 - pymongo: 3.11.2 → 4.10.0+ - pandas: 1.1.5 → 2.0.0+ - pyarrow: 6.0.1 → 15.0.0+ - tornado: 6.3.2 → 6.4.0+ - ✅ 移除过时依赖: delegator.py, six, pyconvert **3. 新增模块** - ✅ `QARSBridge/`: QARS2桥接层 - `qars_account.py`: 高性能账户包装器 - `qars_backtest.py`: Rust回测引擎 - `QIFI_PROTOCOL.md`: 完整协议规范 - ✅ `examples/qarsbridge_example.py`: 完整使用示例 **4. 安装方式优化** ```bash # 基础安装 pip install -e . # 包含Rust组件 (推荐) pip install -e .[rust] # 包含性能优化包 pip install -e .[performance] # 完整安装 pip install -e .[full] ``` #### 📝 升级文档 - ✅ [UPGRADE_PLAN.md](./UPGRADE_PLAN.md) - 完整升级计划 - ✅ [PHASE1_COMPLETE.md](./PHASE1_COMPLETE.md) - Phase 1完成报告 - ✅ [PHASE2_COMPLETE.md](./PHASE2_COMPLETE.md) - Phase 2完成报告 - ✅ [QIFI_PROTOCOL.md](./QUANTAXIS/QARSBridge/QIFI_PROTOCOL.md) - QIFI协议规范 --- ### v2.0.0 - 架构重构 本版本为不兼容升级,涉及重大架构改变: #### 数据层改进 - ✅ ClickHouse客户端集成 - ✅ Tabular数据支持 - ✅ 因子化数据结构 - ✅ Tick / L2 Order / Transaction格式 #### 微服务架构 - ✅ QAWebServer - Tornado Web服务 - ✅ QASchedule - 动态任务调度 - ✅ DAG Pipeline模型 - ✅ QAPubSub - RabbitMQ消息队列 #### 账户系统升级 - ⚠️ 移除QAARP (不再维护老版本) - ✅ 完整QIFI模块 - 保证金模型 - 股票/期货支持 - 期权 [开发中] #### 实盘/模拟盘 - ✅ QIFI结构对接 - ✅ CTP接口 (期货/期权) - ✅ QMT对接 (股票) - ✅ 母子账户OMS - ✅ OrderGateway风控 #### 多语言集成 - ✅ QUANTAXIS Rust版本通信 - ✅ Apache Arrow跨语言数据交换 - pyarrow (Python) - arrow-rs (Rust) - libarrow (C++) - ✅ Rust/C++账户支持 - ✅ Rust Job Worker --- ## 🚀 快速开始 ### 系统要求 - **Python**: 3.9 - 3.12 (推荐3.11+) - **操作系统**: Linux / macOS / Windows - **内存**: 最低4GB,推荐8GB+ - **数据库**: MongoDB 4.0+ / ClickHouse 20.0+ (可选) ### 安装 #### 1. 基础安装 ```bash # 克隆仓库 git clone https://github.com/QUANTAXIS/QUANTAXIS.git cd QUANTAXIS # 安装依赖 pip install -e . ``` #### 2. 包含Rust组件 (推荐 - 100x性能) ```bash # 安装QUANTAXIS + QARS2 pip install -e .[rust] # 或手动安装QARS2 cd /home/quantaxis/qars2 pip install -e . ``` #### 3. 完整安装 ```bash # 安装所有组件 pip install -e .[full] # 包含: # - QARS2 Rust核心 # - QADataSwap跨语言通信 # - Polars高性能DataFrame # - 所有可选依赖 ``` #### 4. 验证安装 ```python import QUANTAXIS as QA from QUANTAXIS.QARSBridge import has_qars_support print(f"QUANTAXIS版本: {QA.__version__}") print(f"QARS2支持: {has_qars_support()}") # 预期输出: # QUANTAXIS版本: 2.1.0.alpha2 # QARS2支持: True ``` ### 快速示例 ```python from QUANTAXIS.QARSBridge import QARSAccount # 创建高性能账户 (自动使用Rust核心) account = QARSAccount( account_cookie="my_strategy", init_cash=1000000.0 ) # 股票交易 account.buy("000001", 10.5, "2025-01-15", 1000) account.sell("000001", 10.8, "2025-01-16", 500) # 期货交易 account.buy_open("IF2512", 4500.0, "2025-01-15", 2) account.sell_close("IF2512", 4520.0, "2025-01-16", 1) # 查询持仓 positions = account.get_positions() print(positions) # 获取QIFI格式账户数据 qifi = account.get_qifi() print(f"账户权益: {qifi['accounts']['balance']}") print(f"可用资金: {qifi['accounts']['available']}") ``` ### 数据库配置 ```python # MongoDB配置 import QUANTAXIS as QA # 设置MongoDB连接 QA.DATABASE = QA.QAUtil.QALogs.QA_Setting.MONGO_URI # 默认: mongodb://localhost:27017/quantaxis # ClickHouse配置 QA.CLICKHOUSE_HOST = 'localhost' QA.CLICKHOUSE_PORT = 9000 ``` --- ## 📖 文档 ### 📚 文档中心 完整文档请访问 **[文档中心 (Documentation Hub)](./doc/README.md)** ### 快速导航 **🚀 入门指南** - [快速开始](./doc/getting-started/quickstart.md) - 10分钟上手教程 - [安装指南](./doc/getting-started/installation.md) - 详细安装步骤 **📘 API参考** - [API概览](./doc/api-reference/overview.md) - 完整API文档 - [QAFetch](./doc/api-reference/qafetch.md) - 数据获取 - [QAData](./doc/api-reference/qadata.md) - 数据结构 - [QAMarket/QIFI](./doc/api-reference/qamarket.md) - 账户体系 **🔧 高级功能** - [资源管理器](./doc/advanced/resource-manager.md) - 统一资源管理 - [Rust集成](./doc/advanced/rust-integration.md) - 高性能组件 - [数据桥接](./doc/advanced/data-bridge.md) - 零拷贝数据交换 **🐳 部署指南** - [Docker部署](./doc/deployment/docker.md) - 容器化部署 - [Kubernetes部署](./doc/deployment/kubernetes.md) - K8s集群部署 - [部署概览](./doc/deployment/overview.md) - 完整部署指南 **📦 迁移指南** - [2.0 → 2.1 迁移](./doc/migration/v2.0-to-v2.1.md) - 升级步骤和注意事项 - [兼容性状态](./doc/migration/COMPATIBILITY_STATUS.md) - 100%向后兼容 **👨‍💻 开发者** - [贡献指南](./doc/development/contributing.md) - 如何参与开发 - [最佳实践](./doc/development/best-practices.md) - 生产环境建议 - [开发指南 (CLAUDE.md)](./CLAUDE.md) - AI辅助开发 **📘 其他资源** - [完整手册 (QABook PDF)](https://github.com/QUANTAXIS/QUANTAXIS/releases/download/latest/quantaxis.pdf) - [示例代码](./examples/) - 完整示例集合 --- ## 🤝 社区与支持 ### GitHub QUANTAXIS 是一个开放的项目, 在开源的3年中有大量的小伙伴加入了我, 并提交了相关的代码, 感谢以下的同学们 [](https://github.com/QUANTAXIS/QUANTAXIS/graphs/contributors) **问题反馈**: - 💬 [GitHub Issues](https://github.com/QUANTAXIS/QUANTAXIS/issues) - 提交Bug和功能请求 - 🌟 [GitHub Discussions](https://github.com/QUANTAXIS/QUANTAXIS/discussions) - 技术讨论 ### 社群 #### QQ群 - 💬 **QUANTAXIS交流群**: 563280067 [群链接](https://jq.qq.com/?_wv=1027&k=4CEKGzn) - 👨‍💻 **QUANTAXIS开发群**: 773602202 (贡献代码请加此群,需备注GitHub ID) - 🔥 **期货实盘部署群**: 945822690 (仅限本地多账户部署用户) #### Discord - 🌍 [QUANTAXIS Discord社区](https://discord.gg/mkk5RgN) #### 论坛 - 📝 [QUANTAXIS CLUB论坛](http://www.yutiansut.com:3000) - 论坛提问享有最高回复优先级 #### 公众号 - 📱 关注公众号获取最新动态和免费下单推送接口 - 回复 `trade` 获取下单接口 --- ## 📊 性能对比 ### QARS2 Rust vs Python | 操作 | Python版本 | QARS2 Rust | 加速比 | |------|-----------|-----------|-------| | 创建1000个账户 | ~50秒 | ~0.5秒 | **100x** ⚡ | | 发送10000个订单 | ~50秒 | ~0.5秒 | **100x** ⚡ | | 账户结算 | ~200ms | ~2ms | **100x** ⚡ | | 10年日线回测 | ~30秒 | ~3秒 | **10x** 🚀 | | 内存占用(单账户) | ~2MB | ~200KB | **-90%** 💾 | | 内存占用(1000持仓) | ~50MB | ~5MB | **-90%** 💾 | ### Python版本性能 | Python版本 | 性能提升 | 推荐度 | |-----------|---------|-------| | Python 3.9 | 基准 | ⭐⭐⭐ | | Python 3.10 | +10% | ⭐⭐⭐⭐ | | Python 3.11 | +25% | ⭐⭐⭐⭐⭐ 最佳 | | Python 3.12 | +20% | ⭐⭐⭐⭐⭐ 最新 | --- ## 💰 项目支持 ### 捐赠 写代码不易...请作者喝杯咖啡呗? ☕ **注**: 支付时请备注您的名字/昵称,我们会维护一个赞助列表感谢您的支持! ### 企业赞助 如需企业级支持、定制开发或技术咨询,请联系: - 📧 Email: yutiansut@qq.com - 💼 企业服务: 提供定制化量化交易解决方案 --- ## 📜 许可证 本项目采用 **MIT License** 开源许可证。 ``` Copyright (c) 2016-2025 yutiansut/QUANTAXIS 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... ``` 完整许可证请查看 [LICENSE](./LICENSE) 文件。 --- ## 👏 致谢 ### 核心贡献者 特别感谢所有为QUANTAXIS做出贡献的开发者! ### 技术栈 QUANTAXIS得以实现离不开以下优秀的开源项目: - **Python生态**: pandas, numpy, scipy, matplotlib - **数据库**: MongoDB, ClickHouse, Redis - **Web框架**: Tornado, Flask - **消息队列**: RabbitMQ (pika) - **Rust生态**: PyO3, Polars, Arrow - **金融数据**: tushare, pytdx ### 特别鸣谢 - **QARS2项目组**: 提供高性能Rust核心 - **社区贡献者**: 所有提交PR和Issue的朋友们 - **早期用户**: 在项目初期就给予支持和反馈的用户 --- ## 🗺️ 路线图 ### v2.1.x (当前) - ✅ QARS2 Rust核心集成 - ✅ Python 3.9-3.12支持 - ✅ QARSBridge桥接层 - 🔄 QADataSwap跨语言通信 (进行中) - 📋 完善文档和示例 ### v2.2.0 (计划中) - 📊 完整的QADataSwap集成 - 🔥 Polars全面替代pandas (可选) - ⚡ 更多Rust加速模块 - 🧪 增强的回测引擎 ### v3.0.0 (未来) - 🤖 AI驱动的策略优化 - 🌐 分布式回测系统 - 📱 移动端支持 - ☁️ 云原生部署 --- ## File: config/readme.md # 配置/脚本区 - ubuntu16.sh ubuntu 16 一键安装脚本 - startjupyter.sh 开启jupyter notebook - run_backend.sh 开启mongod后台,WEBKIT前后台 - update_data.py 更新数据脚本 --- ## File: doc/getting-started/installation.md # QUANTAXIS 安装指南 > 🚀 **QUANTAXIS 2.1.0** - 完整安装教程和依赖配置 > > **版本**: v2.1.0-alpha2 | **Python**: 3.9-3.12 | **更新**: 2025-10-25 --- ## 📋 目录 - [系统要求](#系统要求) - [安装方式](#安装方式) - [依赖说明](#依赖说明) - [Rust组件安装](#rust组件安装) - [数据库配置](#数据库配置) - [验证安装](#验证安装) - [常见问题](#常见问题) - [升级指南](#升级指南) --- ## 🖥️ 系统要求 ### 操作系统 | 系统 | 版本 | 支持状态 | |------|------|---------| | **Linux** | Ubuntu 18.04+, CentOS 7+ | ✅ 完全支持 | | **macOS** | 10.14+ (Mojave) | ✅ 完全支持 | | **Windows** | 10/11 | ⚠️ 部分支持 | **推荐**: Linux (Ubuntu 20.04/22.04) 用于生产环境 ### Python版本 | Python版本 | 支持状态 | 说明 | |-----------|---------|------| | **3.9** | ✅ 推荐 | 稳定版本 | | **3.10** | ✅ 推荐 | 稳定版本 | | **3.11** | ✅ 推荐 | 最新稳定版 | | **3.12** | ✅ 支持 | 最新版本 | | 3.8及以下 | ❌ 不支持 | - | ### 硬件要求 | 用途 | CPU | 内存 | 硬盘 | |------|-----|------|------| | **开发/学习** | 2核+ | 4GB+ | 20GB+ | | **回测/研究** | 4核+ | 8GB+ | 100GB+ | | **生产交易** | 8核+ | 16GB+ | 500GB+ SSD | --- ## 📦 安装方式 ### 方式1: 基础安装(最简单) 适合初学者和基础使用场景。 ```bash # 使用pip安装 pip install quantaxis # 或从源码安装 git clone https://github.com/QUANTAXIS/QUANTAXIS.git cd QUANTAXIS pip install -e . ``` **包含功能**: - ✅ 核心数据结构 - ✅ 数据获取和存储 - ✅ 回测框架 - ✅ 因子分析 - ❌ Rust高性能组件 - ❌ 零拷贝数据传输 --- ### 方式2: 完整安装 with Rust(推荐) 推荐给追求性能的用户,包含所有高性能组件。 ```bash # 安装完整版(包含Rust组件) pip install quantaxis[rust] # 或从源码安装 git clone https://github.com/QUANTAXIS/QUANTAXIS.git cd QUANTAXIS pip install -e .[rust] ``` **包含功能**: - ✅ 所有基础功能 - ✅ QARS2 Rust高性能账户(100x加速) - ✅ QADataSwap零拷贝传输(5-10x加速) - ✅ Polars高性能DataFrame **性能提升**: - 账户操作: 100x加速 - 回测速度: 10x加速 - 数据传输: 5-10x加速 --- ### 方式3: 开发者安装 适合需要修改源码或贡献代码的开发者。 ```bash # 克隆主仓库 git clone https://github.com/QUANTAXIS/QUANTAXIS.git cd QUANTAXIS # 安装开发依赖 pip install -e .[dev] # 安装完整依赖(包括Rust组件) pip install -e .[rust,dev] ``` **额外包含**: - ✅ pytest测试框架 - ✅ pylint代码检查 - ✅ black代码格式化 - ✅ mypy类型检查 --- ### 方式4: Docker安装 适合快速部署和隔离环境。 ```bash # 拉取Docker镜像 docker pull quantaxis/quantaxis:latest # 运行容器 docker run -it --name quantaxis \ -p 8888:8888 \ -v ~/quantaxis_data:/data \ quantaxis/quantaxis:latest # 或使用docker-compose git clone https://github.com/QUANTAXIS/QUANTAXIS.git cd QUANTAXIS/docker docker-compose up -d ``` **包含服务**: - ✅ QUANTAXIS完整环境 - ✅ MongoDB数据库 - ✅ Jupyter Notebook - ✅ WebServer服务 --- ## 📚 依赖说明 ### 核心依赖(必需) | 包名 | 版本要求 | 用途 | |------|---------|------| | **pandas** | ≥1.1.5 | 数据处理 | | **numpy** | ≥1.12.0 | 数值计算 | | **pymongo** | 3.11.2 | MongoDB连接 | | **requests** | ≥2.14.2 | HTTP请求 | | **lxml** | ≥3.8.0 | XML解析 | | **tornado** | ≥6.3.2 | Web服务器 | 安装命令: ```bash pip install pandas numpy pymongo requests lxml tornado ``` --- ### 数据源依赖 | 包名 | 版本要求 | 用途 | |------|---------|------| | **tushare** | ≥1.2.10 | 股票数据获取 | | **pytdx** | ≥1.67 | 通达信数据 | | **akshare** | latest | 多源数据获取 | 安装命令: ```bash pip install tushare pytdx akshare ``` --- ### 可选依赖(推荐) #### 高性能组件 | 包名 | 版本要求 | 用途 | 性能提升 | |------|---------|------|---------| | **qars3** | latest | Rust账户引擎 | 100x | | **qadataswap** | ≥0.1.0 | 零拷贝传输 | 5-10x | | **polars** | ≥0.20.0 | 高性能DataFrame | 5-10x | | **pyarrow** | ≥15.0.0 | Arrow数据格式 | 2-5x | 安装命令: ```bash # 方式1: 通过quantaxis[rust] pip install quantaxis[rust] # 方式2: 单独安装 pip install polars pyarrow cd /home/quantaxis/qars2 && pip install -e . cd /home/quantaxis/qadataswap && pip install -e . ``` #### 可视化和分析 | 包名 | 版本要求 | 用途 | |------|---------|------| | **matplotlib** | ≥3.0.0 | 图表绘制 | | **seaborn** | ≥0.11.1 | 统计可视化 | | **plotly** | ≥5.0.0 | 交互式图表 | | **empyrical** | ≥0.5.0 | 绩效分析 | 安装命令: ```bash pip install matplotlib seaborn plotly empyrical ``` #### 机器学习 | 包名 | 版本要求 | 用途 | |------|---------|------| | **scikit-learn** | ≥0.24.0 | 机器学习 | | **statsmodels** | ≥0.12.1 | 统计模型 | | **alphalens** | latest | 因子分析 | 安装命令: ```bash pip install scikit-learn statsmodels alphalens ``` --- ## 🦀 Rust组件安装 ### QARS2 (Rust账户引擎) **性能**: 100x账户操作加速 #### 方式1: 从PyPI安装(推荐) ```bash pip install qars3 ``` #### 方式2: 从源码编译 ```bash # 克隆QARS2仓库 cd /home/quantaxis git clone https://github.com/yutiansut/qars2.git cd qars2 # 安装Rust(如果未安装) curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source $HOME/.cargo/env # 编译安装 pip install -e . ``` **验证安装**: ```python from QUANTAXIS.QARSBridge import has_qars_support if has_qars_support(): print("✅ QARS2已安装") else: print("❌ QARS2未安装") ``` --- ### QADataSwap (零拷贝数据传输) **性能**: 5-10x数据传输加速 #### 方式1: 从PyPI安装(即将支持) ```bash pip install qadataswap ``` #### 方式2: 从源码编译 ```bash # 克隆QADataSwap仓库 cd /home/quantaxis git clone https://github.com/yutiansut/qadataswap.git cd qadataswap # 确保Rust已安装 rustc --version # 编译安装 pip install -e . ``` **验证安装**: ```python from QUANTAXIS.QADataBridge import has_dataswap_support if has_dataswap_support(): print("✅ QADataSwap已安装") else: print("❌ QADataSwap未安装") ``` --- ## 💾 数据库配置 ### MongoDB安装 QUANTAXIS使用MongoDB作为主要数据存储。 #### Linux (Ubuntu/Debian) ```bash # 导入MongoDB公钥 wget -qO - https://www.mongodb.org/static/pgp/server-6.0.asc | sudo apt-key add - # 添加MongoDB源 echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/6.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-6.0.list # 安装MongoDB sudo apt-get update sudo apt-get install -y mongodb-org # 启动MongoDB sudo systemctl start mongod sudo systemctl enable mongod # 验证安装 mongo --version ``` #### macOS ```bash # 使用Homebrew安装 brew tap mongodb/brew brew install mongodb-community@6.0 # 启动MongoDB brew services start mongodb-community@6.0 # 验证安装 mongosh --version ``` #### Windows 1. 下载MongoDB安装包: https://www.mongodb.com/try/download/community 2. 运行安装程序,选择"Complete"安装 3. 配置MongoDB为Windows服务 4. 验证: 打开命令提示符,输入`mongod --version` --- ### MongoDB配置 创建QUANTAXIS数据库配置: ```bash # 连接MongoDB mongosh # 创建数据库和用户 use quantaxis db.createUser({ user: "quantaxis", pwd: "your_password", roles: [{role: "readWrite", db: "quantaxis"}] }) # 退出 exit ``` 配置QUANTAXIS连接: ```python # 在Python中配置 from QUANTAXIS.QAUtil import DATABASE # 查看当前配置 print(DATABASE) # 或修改配置文件 # ~/.quantaxis/setting/config.ini ``` --- ### ClickHouse安装(可选) 用于大规模数据分析和查询加速。 ```bash # Ubuntu/Debian sudo apt-get install -y apt-transport-https ca-certificates dirmngr sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 8919F6BD2B48D754 echo "deb https://packages.clickhouse.com/deb stable main" | sudo tee /etc/apt/sources.list.d/clickhouse.list sudo apt-get update sudo apt-get install -y clickhouse-server clickhouse-client # 启动服务 sudo systemctl start clickhouse-server sudo systemctl enable clickhouse-server ``` --- ## ✅ 验证安装 ### 基础验证 ```python # test_installation.py import sys print(f"Python版本: {sys.version}") # 导入QUANTAXIS import QUANTAXIS as QA print(f"QUANTAXIS版本: {QA.__version__}") # 检查核心模块 from QUANTAXIS import ( QA_fetch_get_stock_day, QA_DataStruct_Stock_day, QIFI_Account, ) print("✅ 核心模块导入成功") # 检查数据库连接 from QUANTAXIS.QAUtil import DATABASE try: DATABASE.stock_day.find_one() print("✅ MongoDB连接成功") except Exception as e: print(f"⚠️ MongoDB连接失败: {e}") ``` 运行验证: ```bash python test_installation.py ``` --- ### Rust组件验证 ```python # test_rust_components.py from QUANTAXIS.QARSBridge import has_qars_support from QUANTAXIS.QADataBridge import has_dataswap_support print("\n" + "=" * 50) print("Rust组件检查") print("=" * 50) # QARS2检查 if has_qars_support(): from QUANTAXIS.QARSBridge import QARSAccount print("✅ QARS2 (Rust账户引擎) 已安装") print(" 性能提升: 100x账户操作加速") else: print("⚠️ QARS2未安装,使用Python实现") print(" 建议: pip install quantaxis[rust]") # QADataSwap检查 if has_dataswap_support(): from QUANTAXIS.QADataBridge import ( convert_pandas_to_polars, SharedMemoryWriter, ) print("✅ QADataSwap (零拷贝传输) 已安装") print(" 性能提升: 5-10x数据传输加速") else: print("⚠️ QADataSwap未安装,使用标准传输") print(" 建议: pip install quantaxis[rust]") print("=" * 50) ``` 运行验证: ```bash python test_rust_components.py ``` **预期输出**: ``` ================================================== Rust组件检查 ================================================== ✅ QARS2 (Rust账户引擎) 已安装 性能提升: 100x账户操作加速 ✅ QADataSwap (零拷贝传输) 已安装 性能提升: 5-10x数据传输加速 ================================================== ``` --- ### 完整功能验证 ```python # test_full_features.py import QUANTAXIS as QA import pandas as pd print("\n" + "=" * 50) print("QUANTAXIS完整功能验证") print("=" * 50) # 1. 数据获取测试 print("\n1. 测试数据获取...") try: df = QA.QA_fetch_get_stock_day('000001', '2024-01-01', '2024-01-10') print(f" ✅ 获取数据成功: {len(df)}条记录") except Exception as e: print(f" ⚠️ 数据获取失败: {e}") # 2. 数据结构测试 print("\n2. 测试数据结构...") try: data = QA.QA_DataStruct_Stock_day(df) print(f" ✅ 数据结构创建成功") print(f" 数据范围: {data.data.index[0]} 至 {data.data.index[-1]}") except Exception as e: print(f" ⚠️ 数据结构创建失败: {e}") # 3. QIFI账户测试 print("\n3. 测试QIFI账户...") try: account = QA.QIFI_Account( username="test", password="test", model="future", init_cash=100000 ) print(f" ✅ QIFI账户创建成功") print(f" 初始资金: {account.init_cash}") except Exception as e: print(f" ⚠️ QIFI账户创建失败: {e}") # 4. Rust组件测试(如果可用) from QUANTAXIS.QARSBridge import has_qars_support if has_qars_support(): print("\n4. 测试QARS2 Rust账户...") try: from QUANTAXIS.QARSBridge import QARSAccount rust_account = QARSAccount("test", init_cash=100000) print(f" ✅ Rust账户创建成功") print(f" 初始资金: {rust_account.init_cash}") except Exception as e: print(f" ⚠️ Rust账户创建失败: {e}") print("\n" + "=" * 50) print("✅ 验证完成") print("=" * 50) ``` 运行验证: ```bash python test_full_features.py ``` --- ## ❓ 常见问题 ### Q1: ImportError: No module named 'QUANTAXIS' **原因**: QUANTAXIS未正确安装 **解决方案**: ```bash # 重新安装 pip uninstall quantaxis pip install quantaxis # 或从源码安装 cd QUANTAXIS pip install -e . ``` --- ### Q2: MongoDB连接失败 **原因**: MongoDB未启动或配置错误 **解决方案**: ```bash # 检查MongoDB状态 sudo systemctl status mongod # 启动MongoDB sudo systemctl start mongod # 测试连接 mongosh ``` --- ### Q3: Rust组件安装失败 **原因**: 缺少Rust工具链或编译失败 **解决方案**: ```bash # 安装Rust curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh source $HOME/.cargo/env # 更新Rust rustup update # 重新安装 pip install --force-reinstall quantaxis[rust] ``` --- ### Q4: pandas版本冲突 **原因**: pandas版本过低或过高 **解决方案**: ```bash # 升级pandas pip install --upgrade pandas>=1.1.5 # 或指定版本 pip install pandas==2.0.0 ``` --- ### Q5: Python版本不兼容 **错误**: `wrong version, should be 3.9/3.10/3.11 version` **解决方案**: ```bash # 检查Python版本 python --version # 安装Python 3.9+ # Ubuntu/Debian sudo apt-get install python3.9 # macOS brew install python@3.9 # 创建虚拟环境 python3.9 -m venv quantaxis_env source quantaxis_env/bin/activate ``` --- ## 🔄 升级指南 ### 从v1.x升级到v2.1.0 #### 1. 备份数据 ```bash # 备份MongoDB数据 mongodump --db quantaxis --out ~/quantaxis_backup # 备份配置文件 cp -r ~/.quantaxis ~/quantaxis_config_backup ``` #### 2. 卸载旧版本 ```bash pip uninstall quantaxis ``` #### 3. 安装新版本 ```bash # 安装完整版 pip install quantaxis[rust] ``` #### 4. 迁移数据(如需要) ```python # migration_script.py import QUANTAXIS as QA # 检查数据兼容性 # 执行必要的数据转换 # ... print("✅ 数据迁移完成") ``` #### 5. 更新配置 ```python # 更新配置文件格式(如有变化) from QUANTAXIS.QAUtil import QA_util_cfg_initial QA_util_cfg_initial() ``` --- ### 主要变更 #### v2.1.0新特性 - ✅ Python 3.9+支持 - ✅ QARS2 Rust账户引擎集成(100x加速) - ✅ QADataSwap零拷贝传输(5-10x加速) - ✅ QARSBridge桥接层 - ✅ QADataBridge数据交换层 - ✅ Polars高性能DataFrame支持 #### 不兼容变更 - ❌ 不再支持Python 3.8及以下 - ⚠️ 部分API接口调整(向后兼容) --- ## 📝 安装检查清单 完成安装后,请确认以下项目: ### 基础安装 - [ ] Python 3.9+已安装 - [ ] QUANTAXIS已安装 - [ ] MongoDB已安装并运行 - [ ] 可以导入QUANTAXIS模块 - [ ] 数据库连接正常 ### Rust组件(可选但推荐) - [ ] Rust工具链已安装 - [ ] QARS2已安装 - [ ] QADataSwap已安装 - [ ] Polars已安装 - [ ] PyArrow已安装 ### 数据源配置 - [ ] Tushare已配置(如使用) - [ ] AkShare已安装(如使用) - [ ] pytdx已安装 ### 功能验证 - [ ] 数据获取功能正常 - [ ] 账户创建功能正常 - [ ] 回测功能正常 - [ ] Rust组件功能正常(如已安装) --- ## 🆘 获取帮助 如果遇到安装问题,可以通过以下方式获取帮助: ### 官方渠道 - **GitHub Issues**: https://github.com/QUANTAXIS/QUANTAXIS/issues - **QQ群**: 563280068 - **Discord**: https://discord.gg/quantaxis - **论坛**: https://forum.quantaxis.cn ### 提问建议 提问时请提供以下信息: 1. 操作系统和版本 2. Python版本 3. QUANTAXIS版本 4. 完整的错误信息 5. 已尝试的解决方案 --- ## 📚 下一步 安装完成后,建议: 1. **阅读快速入门**: [QUICKSTART.md](./QUICKSTART.md) 2. **查看示例代码**: [examples/](./examples/) 3. **运行基准测试**: 验证性能提升 4. **配置数据源**: 开始获取市场数据 --- **@yutiansut @quantaxis** **最后更新**: 2025-10-25 --- ## File: doc/getting-started/quickstart.md # QUANTAXIS 快速入门 > 🚀 **10分钟上手QUANTAXIS** - 从零开始的量化交易之旅 > > **版本**: v2.1.0-alpha2 | **难度**: 入门 | **时间**: 10-15分钟 --- ## 📋 目录 - [前置准备](#前置准备) - [第一个程序](#第一个程序) - [数据获取](#数据获取) - [数据分析](#数据分析) - [简单回测](#简单回测) - [使用Rust加速](#使用rust加速) - [下一步学习](#下一步学习) --- ## ✅ 前置准备 ### 确认安装 ```python # 检查QUANTAXIS是否已安装 import QUANTAXIS as QA print(f"QUANTAXIS版本: {QA.__version__}") # 预期输出: QUANTAXIS版本: 2.1.0.alpha2 ``` 如果未安装,请参考[安装指南](./INSTALLATION.md)。 ### 导入常用模块 ```python import QUANTAXIS as QA import pandas as pd import numpy as np from datetime import datetime, timedelta ``` --- ## 🎯 第一个程序 让我们从最简单的例子开始——获取股票数据并查看。 ### 示例1: Hello QUANTAXIS ```python """ 第一个QUANTAXIS程序 功能: 获取平安银行(000001)的历史数据 """ import QUANTAXIS as QA # 获取股票日线数据 # 参数: 股票代码, 开始日期, 结束日期 df = QA.QA_fetch_get_stock_day( code='000001', # 平安银行 start='2024-01-01', # 开始日期 end='2024-01-31' # 结束日期 ) # 显示数据 print("\n" + "=" * 50) print("平安银行 2024年1月行情数据") print("=" * 50) print(df.head()) # 统计信息 print("\n基本统计:") print(f"交易天数: {len(df)}") print(f"最高价: {df['high'].max():.2f}") print(f"最低价: {df['low'].min():.2f}") print(f"平均成交量: {df['volume'].mean():.0f}股") ``` **运行输出**: ``` ================================================== 平安银行 2024年1月行情数据 ================================================== open high low close volume date 2024-01-02 10.5 10.68 10.45 10.52 12543200 2024-01-03 10.5 10.75 10.48 10.68 15234100 ... 基本统计: 交易天数: 20 最高价: 11.25 最低价: 10.32 平均成交量: 14523456股 ``` --- ## 📊 数据获取 QUANTAXIS支持多种市场的数据获取。 ### 示例2: 股票数据 ```python """ 获取多只股票的历史数据 """ import QUANTAXIS as QA # 股票代码列表 stocks = ['000001', '000002', '600000'] # 批量获取数据 for code in stocks: df = QA.QA_fetch_get_stock_day( code=code, start='2024-01-01', end='2024-01-10' ) # 使用QA数据结构 data = QA.QA_DataStruct_Stock_day(df) print(f"\n股票 {code}:") print(f" 交易天数: {len(data.data)}") print(f" 涨跌幅: {data.data['close'].pct_change().mean() * 100:.2f}%") ``` --- ### 示例3: 期货数据 ```python """ 获取期货主力合约数据 """ import QUANTAXIS as QA # 获取期货日线数据 df_future = QA.QA_fetch_get_future_day( code='IF2512', # 沪深300期货2025年12月合约 start='2024-01-01', end='2024-01-31' ) # 使用期货数据结构 data_future = QA.QA_DataStruct_Future_day(df_future) print(f"\n期货合约 IF2512:") print(f" 交易天数: {len(data_future.data)}") print(f" 开盘价范围: {data_future.data['open'].min():.2f} - {data_future.data['open'].max():.2f}") print(f" 收盘价范围: {data_future.data['close'].min():.2f} - {data_future.data['close'].max():.2f}") ``` --- ### 示例4: 实时数据 ```python """ 获取实时行情数据 """ import QUANTAXIS as QA # 获取股票实时行情 realtime = QA.QA_fetch_get_stock_realtime( code=['000001', '000002', '600000'] ) print("\n实时行情:") print(realtime[['code', 'price', 'bid1', 'ask1', 'volume']]) ``` --- ## 📈 数据分析 使用QUANTAXIS的数据结构进行分析。 ### 示例5: 技术指标计算 ```python """ 计算技术指标 """ import QUANTAXIS as QA # 获取数据 df = QA.QA_fetch_get_stock_day('000001', '2023-01-01', '2024-01-31') data = QA.QA_DataStruct_Stock_day(df) # 计算均线 ma5 = data.data['close'].rolling(5).mean() ma10 = data.data['close'].rolling(10).mean() ma20 = data.data['close'].rolling(20).mean() print("\n均线系统 (最近5天):") print(pd.DataFrame({ '日期': data.data.index[-5:], '收盘价': data.data['close'][-5:].values, 'MA5': ma5[-5:].values, 'MA10': ma10[-5:].values, 'MA20': ma20[-5:].values, })) # 使用QA内置指标 from QUANTAXIS.QAIndicator import QA_indicator_MA, QA_indicator_MACD # 计算MACD macd_df = QA_indicator_MACD(data.data) print("\nMACD指标 (最近5天):") print(macd_df.tail()) ``` --- ### 示例6: 数据可视化 ```python """ 数据可视化 """ import QUANTAXIS as QA import matplotlib.pyplot as plt # 设置中文字体 plt.rcParams['font.sans-serif'] = ['SimHei'] plt.rcParams['axes.unicode_minus'] = False # 获取数据 df = QA.QA_fetch_get_stock_day('000001', '2023-01-01', '2024-01-31') data = QA.QA_DataStruct_Stock_day(df) # 创建图表 fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 8)) # 价格走势 ax1.plot(data.data.index, data.data['close'], label='收盘价') ax1.plot(data.data.index, data.data['close'].rolling(20).mean(), label='MA20') ax1.set_title('平安银行股价走势') ax1.set_ylabel('价格 (元)') ax1.legend() ax1.grid(True) # 成交量 ax2.bar(data.data.index, data.data['volume'], alpha=0.5) ax2.set_title('成交量') ax2.set_ylabel('成交量 (股)') ax2.grid(True) plt.tight_layout() plt.savefig('stock_analysis.png') print("\n✅ 图表已保存至 stock_analysis.png") ``` --- ## 🔄 简单回测 ### 示例7: 均线策略回测 ``` /* Detailed source-code truncated for AI context efficiency. */ ``` --- ### 示例8: 使用QA回测框架 ```python """ 使用QUANTAXIS回测框架 """ import QUANTAXIS as QA from QUANTAXIS.QAStrategy import QAStrategyCtaBase class MyStrategy(QAStrategyCtaBase): """简单的均线策略""" def __init__(self): super().__init__() self.ma_short = 5 self.ma_long = 20 def on_bar(self, bar): """每根K线回调""" # 计算均线 ma5 = bar['close'].rolling(self.ma_short).mean().iloc[-1] ma20 = bar['close'].rolling(self.ma_long).mean().iloc[-1] # 交易逻辑 if ma5 > ma20: self.buy(bar['code'].iloc[-1], bar['close'].iloc[-1], 100) elif ma5 < ma20: self.sell(bar['code'].iloc[-1], bar['close'].iloc[-1], 100) # 创建策略实例 strategy = MyStrategy() # 运行回测 result = QA.QA_Backtest( strategy=strategy, code='000001', start='2023-01-01', end='2024-01-31', init_cash=100000 ) print(f"\n收益率: {result.profit_rate * 100:.2f}%") ``` --- ## ⚡ 使用Rust加速 ### 示例9: QARS2高性能账户 ```python """ 使用Rust实现的高性能账户 性能提升: 100x """ from QUANTAXIS.QARSBridge import has_qars_support if has_qars_support(): from QUANTAXIS.QARSBridge import QARSAccount # 创建Rust账户(100x加速) account = QARSAccount( account_cookie="rust_account", init_cash=100000.0 ) # 买入操作 account.buy( code="000001", price=10.5, datetime="2024-01-15", amount=1000 ) print(f"✅ Rust账户创建成功") print(f" 可用资金: {account.cash:.2f}元") print(f" 持仓股票: {list(account.positions.keys())}") else: print("⚠️ QARS2未安装,请运行: pip install quantaxis[rust]") ``` --- ### 示例10: 零拷贝数据转换 ```python """ 使用零拷贝进行高性能数据转换 性能提升: 2-5x """ from QUANTAXIS.QADataBridge import has_dataswap_support if has_dataswap_support(): from QUANTAXIS.QADataBridge import convert_pandas_to_polars import pandas as pd # 创建Pandas数据 df_pandas = pd.DataFrame({ 'code': ['000001'] * 1000, 'price': [10.5] * 1000, 'volume': [1000] * 1000, }) # 零拷贝转换为Polars(2-5x加速) df_polars = convert_pandas_to_polars(df_pandas) print(f"✅ 零拷贝转换成功") print(f" 原始格式: {type(df_pandas)}") print(f" 转换后: {type(df_polars)}") print(f" 性能提升: 2-5x") else: print("⚠️ QADataSwap未安装,请运行: pip install quantaxis[rust]") ``` --- ## 🎓 学习路径 ### 初学者 (第1-2周) **目标**: 熟悉基本操作 1. **数据获取** - ✅ 获取股票/期货数据 - ✅ 理解数据结构 - ✅ 数据可视化 2. **简单分析** - ✅ 计算技术指标 - ✅ 统计分析 - ✅ 数据清洗 **推荐练习**: ```python # 练习1: 获取多只股票数据并对比 # 练习2: 计算并可视化MA、MACD等指标 # 练习3: 分析成交量与价格的关系 ``` --- ### 进阶 (第3-4周) **目标**: 掌握回测框架 1. **策略开发** - ✅ 简单的均线策略 - ✅ 多因子策略 - ✅ 事件驱动策略 2. **回测优化** - ✅ 参数优化 - ✅ 风险控制 - ✅ 绩效分析 **推荐练习**: ```python # 练习4: 实现双均线策略并回测 # 练习5: 添加止损止盈逻辑 # 练习6: 对比不同参数的表现 ``` --- ### 高级 (第5-8周) **目标**: 生产环境部署 1. **高性能优化** - ✅ 使用QARS2 Rust账户 - ✅ 使用零拷贝数据传输 - ✅ 多进程并行 2. **实盘交易** - ✅ 接入交易接口 - ✅ 风险管理 - ✅ 监控告警 **推荐练习**: ```python # 练习7: 将策略迁移到QARS2 # 练练习8: 使用共享内存进行跨进程通信 # 练习9: 搭建完整的交易系统 ``` --- ## 📚 下一步学习 ### 推荐文档 1. **核心概念** - [QIFI协议详解](./QUANTAXIS/QARSBridge/QIFI_PROTOCOL.md) - [数据结构说明](./docs/data_structures.md) - [回测框架文档](./docs/backtest.md) 2. **进阶功能** - [QARSBridge使用指南](./QUANTAXIS/QARSBridge/README.md) - [QADataBridge性能优化](./QUANTAXIS/QADataBridge/README.md) - [因子分析框架](./docs/factor_analysis.md) 3. **API参考** - [完整API文档](./API_REFERENCE.md) - [配置参数说明](./docs/configuration.md) ### 示例代码 ```bash # 查看所有示例 ls examples/ # 运行QARSBridge示例 python examples/qarsbridge_example.py # 运行QADataBridge示例 python examples/qadatabridge_example.py # 运行性能测试 python scripts/benchmark_databridge.py ``` ### 社区资源 - **GitHub**: https://github.com/QUANTAXIS/QUANTAXIS - **QQ群**: 563280068 - **Discord**: https://discord.gg/quantaxis - **论坛**: https://forum.quantaxis.cn - **文档**: https://doc.quantaxis.cn --- ## 💡 实用技巧 ### 技巧1: 配置数据库连接 ```python from QUANTAXIS.QAUtil import DATABASE # 查看当前配置 print(DATABASE) # 自定义配置 import pymongo client = pymongo.MongoClient('localhost', 27017) db = client.quantaxis ``` ### 技巧2: 批量数据获取 ```python # 获取股票列表 stock_list = QA.QA_fetch_get_stock_list() # 批量获取数据 for code in stock_list[:10]: # 前10只股票 df = QA.QA_fetch_get_stock_day(code, '2024-01-01', '2024-01-31') # 处理数据... ``` ### 技巧3: 错误处理 ```python try: df = QA.QA_fetch_get_stock_day('000001', '2024-01-01', '2024-01-31') except Exception as e: print(f"数据获取失败: {e}") # 降级处理... ``` ### 技巧4: 性能分析 ```python import time # 对比标准实现和Rust实现 start = time.time() # ... 标准代码 ... time_standard = time.time() - start start = time.time() # ... Rust代码 ... time_rust = time.time() - start print(f"加速比: {time_standard / time_rust:.2f}x") ``` --- ## ❓ 常见问题 ### Q1: 如何获取更多股票代码? ```python # 获取所有A股代码 stock_list = QA.QA_fetch_get_stock_list() print(f"共{len(stock_list)}只股票") print(stock_list.head()) ``` ### Q2: 如何处理缺失数据? ```python df = QA.QA_fetch_get_stock_day('000001', '2024-01-01', '2024-01-31') # 检查缺失值 print(df.isnull().sum()) # 填充缺失值 df_filled = df.fillna(method='ffill') # 前向填充 ``` ### Q3: 如何加速数据处理? ```python # 方式1: 使用Polars from QUANTAXIS.QADataBridge import convert_pandas_to_polars df_polars = convert_pandas_to_polars(df) # Polars操作通常快5-10x # 方式2: 使用向量化操作 df['returns'] = df['close'].pct_change() # ✅ 向量化 # 避免循环: for i in range(len(df)): ... ❌ ``` --- **恭喜你完成了QUANTAXIS快速入门!🎉** 现在你已经掌握了: - ✅ 数据获取和分析 - ✅ 技术指标计算 - ✅ 简单策略回测 - ✅ Rust组件使用 继续探索更多高级功能,祝交易顺利! --- **@yutiansut @quantaxis** **最后更新**: 2025-10-25 --- ## File: doc/development/best-practices.md # QUANTAXIS 最佳实践 > 💡 **生产环境最佳实践** - 性能优化、代码规范、架构设计 > > **版本**: v2.1.0-alpha2 | **适用场景**: 生产环境 | **更新**: 2025-10-25 --- ## 📋 目录 - [性能优化](#性能优化) - [代码规范](#代码规范) - [架构设计](#架构设计) - [错误处理](#错误处理) - [数据库优化](#数据库优化) - [安全建议](#安全建议) - [测试策略](#测试策略) - [部署建议](#部署建议) --- ## ⚡ 性能优化 ### 1. 使用Rust组件(100x加速) #### ✅ 推荐做法 ```python from QUANTAXIS.QARSBridge import has_qars_support, QARSAccount # 检查并使用Rust账户 if has_qars_support(): # 使用Rust账户(100x加速) account = QARSAccount("account_id", init_cash=100000.0) else: # 降级到Python实现 from QUANTAXIS.QIFI import QIFI_Account account = QIFI_Account("account_id", "pwd", "stock", 100000) ``` **性能提升**: - 账户创建: 50ms → 0.5ms(100x) - 订单处理: 10ms → 0.1ms(100x) - 持仓计算: 5ms → 0.05ms(100x) #### ❌ 避免的做法 ```python # 不要: 始终使用Python实现 account = QIFI_Account(...) # 性能损失100x ``` --- ### 2. 使用零拷贝数据转换(2-5x加速) #### ✅ 推荐做法 ```python from QUANTAXIS.QADataBridge import ( has_dataswap_support, convert_pandas_to_polars ) if has_dataswap_support(): # 零拷贝转换(2.5x加速) df_polars = convert_pandas_to_polars(df_pandas) # 使用Polars进行高性能计算 result = ( df_polars .filter(pl.col("volume") > 1000000) .group_by("code") .agg(pl.col("price").mean()) ) # 转回Pandas(如需要) result_pandas = convert_polars_to_pandas(result) else: # 降级到标准处理 result = df_pandas[df_pandas['volume'] > 1000000].groupby('code')['price'].mean() ``` **性能对比**: | 操作 | Pandas | Polars (零拷贝) | 加速比 | |------|--------|----------------|--------| | 数据转换 (100万行) | 450ms | 180ms | 2.5x | | 过滤操作 | 120ms | 25ms | 4.8x | | 分组聚合 | 350ms | 60ms | 5.8x | #### ❌ 避免的做法 ```python # 不要: 频繁的类型转换 for i in range(100): df_polars = pl.from_pandas(df) # 每次都复制数据 result = df_polars.filter(...) df_pandas = result.to_pandas() # 又复制回来 ``` --- ### 3. 使用共享内存(7x加速) #### ✅ 推荐做法 - 行情数据分发 **进程A(行情服务器)**: ```python from QUANTAXIS.QADataBridge import SharedMemoryWriter # 创建共享内存写入器 writer = SharedMemoryWriter("realtime_market", size_mb=20) while True: # 接收实时tick数据 tick_df = receive_tick_from_exchange() # 写入共享内存(7x加速) writer.write(tick_df) time.sleep(0.1) # 100ms更新一次 ``` **进程B(策略进程)**: ```python from QUANTAXIS.QADataBridge import SharedMemoryReader # 创建共享内存读取器 reader = SharedMemoryReader("realtime_market") while True: # 读取最新行情(零拷贝) tick_df = reader.read(timeout_ms=200) if tick_df is not None: # 策略逻辑 execute_strategy(tick_df) ``` **性能对比**: - 共享内存传输: ~20ms (100万行) - Pickle序列化: ~140ms (100万行) - **加速比: 7x** #### ❌ 避免的做法 ```python # 不要: 使用pickle在进程间传输 import pickle import multiprocessing queue = multiprocessing.Queue() # 进程A queue.put(pickle.dumps(df)) # 序列化开销大 # 进程B df = pickle.loads(queue.get()) # 反序列化开销大 ``` --- ### 4. 向量化操作 #### ✅ 推荐做法 ```python # 使用向量化计算收益率 df['returns'] = df['close'].pct_change() # 使用向量化计算信号 df['signal'] = np.where(df['ma5'] > df['ma20'], 1, -1) # 使用向量化计算累积收益 df['cumulative_returns'] = (1 + df['returns']).cumprod() ``` **性能提升**: 通常快10-100x #### ❌ 避免的做法 ```python # 不要: 使用循环 returns = [] for i in range(1, len(df)): ret = (df.iloc[i]['close'] / df.iloc[i-1]['close']) - 1 returns.append(ret) df['returns'] = [0] + returns # 慢100x ``` --- ### 5. 批量操作 #### ✅ 推荐做法 ```python # 批量获取数据 codes = QA.QA_fetch_get_stock_list()['code'].tolist()[:100] # 使用列表推导式批量处理 data_list = [ QA.QA_fetch_get_stock_day(code, '2024-01-01', '2024-01-31') for code in codes ] # 合并数据 all_data = pd.concat(data_list, keys=codes) ``` #### ❌ 避免的做法 ```python # 不要: 逐个处理 all_data = pd.DataFrame() for code in codes: df = QA.QA_fetch_get_stock_day(code, '2024-01-01', '2024-01-31') df['code'] = code all_data = all_data.append(df) # append很慢,每次都重新分配内存 ``` --- ## 📝 代码规范 ### 1. 命名规范 #### ✅ 推荐做法 ```python # 变量名:小写下划线 stock_code = '000001' close_price = 10.5 ma_period = 20 # 类名:大驼峰 class MovingAverageStrategy: pass # 函数名:小写下划线 def calculate_returns(prices): return prices.pct_change() # 常量:大写下划线 MAX_POSITION_SIZE = 1000000 DEFAULT_COMMISSION_RATE = 0.0003 ``` --- ### 2. 类型提示 #### ✅ 推荐做法 ```python from typing import Optional, Union, List import pandas as pd def get_stock_data( code: str, start: str, end: str, adjust: Optional[str] = None ) -> pd.DataFrame: """ 获取股票数据 参数: code: 股票代码 start: 开始日期 end: 结束日期 adjust: 复权类型,可选 返回: 股票数据DataFrame """ return QA.QA_fetch_get_stock_day(code, start, end) ``` --- ### 3. 文档字符串 #### ✅ 推荐做法 ```python def calculate_sharpe_ratio( returns: pd.Series, risk_free_rate: float = 0.03 ) -> float: """ 计算夏普比率 夏普比率衡量每单位风险的超额收益,计算公式: Sharpe = (年化收益率 - 无风险利率) / 年化波动率 参数: returns: 收益率序列 risk_free_rate: 无风险利率,默认3% 返回: 夏普比率 示例: >>> returns = pd.Series([0.01, -0.02, 0.03, 0.01]) >>> sharpe = calculate_sharpe_ratio(returns) >>> print(f"夏普比率: {sharpe:.2f}") """ annual_return = returns.mean() * 252 annual_vol = returns.std() * np.sqrt(252) return (annual_return - risk_free_rate) / annual_vol ``` --- ### 4. 配置管理 #### ✅ 推荐做法 ```python # config.py from dataclasses import dataclass from typing import Optional @dataclass class TradingConfig: """交易配置""" init_cash: float = 100000.0 commission_rate: float = 0.0003 slippage: float = 0.0001 max_position: int = 10 # MongoDB配置 mongo_host: str = 'localhost' mongo_port: int = 27017 mongo_db: str = 'quantaxis' @classmethod def from_file(cls, path: str) -> 'TradingConfig': """从配置文件加载""" import json with open(path) as f: config_dict = json.load(f) return cls(**config_dict) # main.py config = TradingConfig.from_file('config.json') account = QARSAccount("account", init_cash=config.init_cash) ``` #### ❌ 避免的做法 ```python # 不要: 硬编码配置 init_cash = 100000 # 魔法数字 commission = 0.0003 # 魔法数字 mongo_host = 'localhost' # 硬编码 ``` --- ## 🏗️ 架构设计 ### 1. 分层架构 #### ✅ 推荐架构 ``` 项目结构: ├── data/ # 数据层 │ ├── fetcher.py # 数据获取 │ ├── storage.py # 数据存储 │ └── processor.py # 数据处理 │ ├── strategy/ # 策略层 │ ├── base.py # 策略基类 │ ├── ma_strategy.py # 均线策略 │ └── factors.py # 因子策略 │ ├── execution/ # 执行层 │ ├── account.py # 账户管理 │ ├── broker.py # 券商接口 │ └── risk.py # 风险控制 │ ├── backtest/ # 回测层 │ ├── engine.py # 回测引擎 │ └── analyzer.py # 绩效分析 │ └── utils/ # 工具层 ├── logger.py # 日志 ├── config.py # 配置 └── helpers.py # 辅助函数 ``` --- ### 2. 策略模式 #### ✅ 推荐做法 ```python from abc import ABC, abstractmethod from typing import Dict, Any class BaseStrategy(ABC): """策略基类""" def __init__(self, config: Dict[str, Any]): self.config = config self.positions = {} @abstractmethod def generate_signal(self, data: pd.DataFrame) -> int: """ 生成交易信号 返回: 1: 买入信号 0: 持有 -1: 卖出信号 """ pass @abstractmethod def on_bar(self, bar: pd.Series): """K线回调""" pass class MAStrategy(BaseStrategy): """均线策略""" def generate_signal(self, data: pd.DataFrame) -> int: ma5 = data['close'].rolling(5).mean().iloc[-1] ma20 = data['close'].rolling(20).mean().iloc[-1] if ma5 > ma20: return 1 elif ma5 < ma20: return -1 return 0 def on_bar(self, bar: pd.Series): # 实现交易逻辑 pass ``` --- ### 3. 依赖注入 #### ✅ 推荐做法 ```python class BacktestEngine: """回测引擎""" def __init__( self, strategy: BaseStrategy, data_source: DataSource, account: AccountInterface ): self.strategy = strategy self.data_source = data_source self.account = account def run(self): data = self.data_source.load() for bar in data: signal = self.strategy.generate_signal(bar) if signal == 1: self.account.buy(...) elif signal == -1: self.account.sell(...) # 使用 strategy = MAStrategy(config) data_source = MongoDataSource() account = QARSAccount("test", 100000) engine = BacktestEngine(strategy, data_source, account) engine.run() ``` --- ## 🚨 错误处理 ### 1. 异常处理 #### ✅ 推荐做法 ```python import logging logger = logging.getLogger(__name__) def fetch_stock_data(code: str, start: str, end: str) -> Optional[pd.DataFrame]: """ 安全地获取股票数据 返回None表示失败,便于调用者处理 """ try: df = QA.QA_fetch_get_stock_day(code, start, end) # 数据验证 if df is None or len(df) == 0: logger.warning(f"股票{code}数据为空") return None # 数据清洗 df = df.dropna() return df except Exception as e: logger.error(f"获取股票{code}数据失败: {e}", exc_info=True) return None # 使用 df = fetch_stock_data('000001', '2024-01-01', '2024-01-31') if df is not None: # 处理数据 pass else: # 降级处理 pass ``` #### ❌ 避免的做法 ```python # 不要: 忽略异常 try: df = QA.QA_fetch_get_stock_day(code, start, end) except: pass # 静默失败,难以调试 # 不要: 过于宽泛的异常捕获 try: df = QA.QA_fetch_get_stock_day(code, start, end) except Exception: # 捕获所有异常,包括KeyboardInterrupt pass ``` --- ### 2. 断言验证 #### ✅ 推荐做法 ```python def calculate_position_size( account_value: float, risk_ratio: float, price: float ) -> int: """ 计算仓位大小 参数: account_value: 账户总值 risk_ratio: 风险比例 (0-1) price: 股票价格 返回: 持仓数量(100股整数倍) """ # 输入验证 assert account_value > 0, "账户总值必须大于0" assert 0 < risk_ratio <= 1, "风险比例必须在(0, 1]之间" assert price > 0, "价格必须大于0" # 计算仓位 position_value = account_value * risk_ratio shares = int(position_value / price / 100) * 100 return shares ``` --- ## 💾 数据库优化 ### 1. 索引优化 #### ✅ 推荐做法 ```python from pymongo import ASCENDING, DESCENDING # 创建复合索引 DATABASE.stock_day.create_index([ ('code', ASCENDING), ('date', DESCENDING) ]) # 创建唯一索引 DATABASE.stock_list.create_index( [('code', ASCENDING)], unique=True ) # 查询使用索引 df = DATABASE.stock_day.find({ 'code': '000001', 'date': {'$gte': '2024-01-01', '$lte': '2024-01-31'} }).sort('date', DESCENDING) ``` --- ### 2. 批量操作 #### ✅ 推荐做法 ```python # 批量插入 documents = [ { 'code': code, 'date': date, 'price': price, ... } for code, date, price in data_list ] DATABASE.stock_day.insert_many(documents, ordered=False) ``` #### ❌ 避免的做法 ```python # 不要: 逐条插入 for code, date, price in data_list: DATABASE.stock_day.insert_one({ 'code': code, 'date': date, 'price': price, }) # 每次都是一次网络请求 ``` --- ### 3. 查询优化 #### ✅ 推荐做法 ```python # 只查询需要的字段 df = DATABASE.stock_day.find( {'code': '000001'}, {'_id': 0, 'code': 1, 'date': 1, 'close': 1} # 投影 ) # 使用聚合管道 pipeline = [ {'$match': {'code': '000001'}}, {'$group': { '_id': '$code', 'avg_price': {'$avg': '$close'} }} ] result = DATABASE.stock_day.aggregate(pipeline) ``` --- ## 🔒 安全建议 ### 1. 敏感信息保护 #### ✅ 推荐做法 ```python import os from dotenv import load_dotenv # 使用环境变量 load_dotenv() MONGO_USER = os.getenv('MONGO_USER') MONGO_PASSWORD = os.getenv('MONGO_PASSWORD') API_KEY = os.getenv('TUSHARE_API_KEY') # .env文件 (不要提交到git) # MONGO_USER=admin # MONGO_PASSWORD=your_password # TUSHARE_API_KEY=your_api_key ``` #### ❌ 避免的做法 ```python # 不要: 硬编码密码 MONGO_PASSWORD = "my_password" # 泄露风险 API_KEY = "abc123xyz" # 不要提交到git ``` --- ### 2. 输入验证 #### ✅ 推荐做法 ```python def validate_stock_code(code: str) -> bool: """验证股票代码格式""" import re # A股代码: 6位数字 return bool(re.match(r'^\d{6}$', code)) def safe_fetch(code: str, start: str, end: str): # 验证输入 if not validate_stock_code(code): raise ValueError(f"无效的股票代码: {code}") # 验证日期格式 try: datetime.strptime(start, '%Y-%m-%d') datetime.strptime(end, '%Y-%m-%d') except ValueError: raise ValueError("日期格式必须为YYYY-MM-DD") return QA.QA_fetch_get_stock_day(code, start, end) ``` --- ## 🧪 测试策略 ### 1. 单元测试 #### ✅ 推荐做法 ```python import pytest import pandas as pd def test_calculate_returns(): """测试收益率计算""" prices = pd.Series([100, 105, 102, 108]) expected = pd.Series([0.0, 0.05, -0.0286, 0.0588]) returns = calculate_returns(prices) pd.testing.assert_series_equal( returns, expected, check_exact=False, rtol=0.01 ) def test_ma_strategy_signal(): """测试均线策略信号生成""" data = create_test_data() # 创建测试数据 strategy = MAStrategy(config) signal = strategy.generate_signal(data) assert signal in [-1, 0, 1], "信号必须是-1, 0或1" ``` --- ### 2. 回测验证 #### ✅ 推荐做法 ```python def test_backtest_consistency(): """测试回测结果一致性""" # 运行两次回测 result1 = run_backtest(strategy, data, seed=42) result2 = run_backtest(strategy, data, seed=42) # 结果应该完全相同 assert result1['final_value'] == result2['final_value'] assert result1['sharpe_ratio'] == result2['sharpe_ratio'] def test_backtest_sanity(): """测试回测合理性""" result = run_backtest(strategy, data) # 基本合理性检查 assert result['final_value'] > 0, "最终净值必须大于0" assert -1 <= result['max_drawdown'] <= 0, "最大回撤范围: [-1, 0]" assert result['total_trades'] >= 0, "交易次数不能为负" ``` --- ## 🚀 部署建议 ### 1. 日志配置 #### ✅ 推荐做法 ```python import logging from logging.handlers import RotatingFileHandler def setup_logging(log_level=logging.INFO): """配置日志""" logger = logging.getLogger('quantaxis') logger.setLevel(log_level) # 文件处理器(自动轮转) file_handler = RotatingFileHandler( 'quantaxis.log', maxBytes=10*1024*1024, # 10MB backupCount=5 ) file_handler.setLevel(logging.INFO) # 控制台处理器 console_handler = logging.StreamHandler() console_handler.setLevel(logging.WARNING) # 格式化 formatter = logging.Formatter( '%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) file_handler.setFormatter(formatter) console_handler.setFormatter(formatter) logger.addHandler(file_handler) logger.addHandler(console_handler) return logger ``` --- ### 2. 监控告警 #### ✅ 推荐做法 ```python class TradingMonitor: """交易监控""" def __init__(self, account, alert_threshold=0.05): self.account = account self.alert_threshold = alert_threshold self.last_check_time = datetime.now() def check_drawdown(self): """检查回撤""" current_drawdown = self.account.get_drawdown() if current_drawdown > self.alert_threshold: self.send_alert( f"⚠️ 警告: 回撤超过{self.alert_threshold*100}%," f"当前: {current_drawdown*100:.2f}%" ) def check_position_risk(self): """检查持仓风险""" for code, position in self.account.positions.items(): position_ratio = position['value'] / self.account.balance if position_ratio > 0.3: # 单只股票超过30% self.send_alert( f"⚠️ 警告: {code}持仓过重," f"占比: {position_ratio*100:.2f}%" ) def send_alert(self, message): """发送告警""" logger.warning(message) # 可以集成其他告警渠道: 邮件、短信、钉钉等 ``` --- ### 3. 优雅退出 #### ✅ 推荐做法 ```python import signal import sys class TradingSystem: """交易系统""" def __init__(self): self.running = True signal.signal(signal.SIGINT, self.signal_handler) signal.signal(signal.SIGTERM, self.signal_handler) def signal_handler(self, signum, frame): """信号处理器""" print(f"\n接收到信号{signum},准备退出...") self.running = False def cleanup(self): """清理资源""" # 保存状态 self.account.save_state() # 关闭数据库连接 DATABASE.client.close() # 关闭共享内存 if hasattr(self, 'writer'): self.writer.close() print("清理完成") def run(self): """运行交易系统""" try: while self.running: # 交易逻辑 pass except Exception as e: logger.error(f"系统错误: {e}", exc_info=True) finally: self.cleanup() sys.exit(0) ``` --- ## 📊 性能基准 ### 推荐配置对比 | 配置 | 账户操作 | 数据转换 | 数据传输 | 适用场景 | |------|---------|---------|---------|---------| | **基础Python** | 50ms | 450ms | 850ms | 学习/研究 | | **+Polars** | 50ms | 180ms | 450ms | 数据分析 | | **+QARS2** | 0.5ms | 180ms | 450ms | 高频交易 | | **+QADataSwap** | 0.5ms | 180ms | 120ms | 生产环境 | | **完整Rust** | 0.5ms | 180ms | 120ms | **推荐配置** | **加速比**: - 账户操作: **100x** - 数据转换: **2.5x** - 数据传输: **7.1x** --- ## 📚 总结清单 ### 性能优化 ✅ - [ ] 使用QARS2 Rust账户(100x加速) - [ ] 使用零拷贝数据转换(2.5x加速) - [ ] 使用共享内存传输(7x加速) - [ ] 使用向量化操作 - [ ] 批量处理数据 ### 代码质量 ✅ - [ ] 遵循命名规范 - [ ] 添加类型提示 - [ ] 编写文档字符串 - [ ] 配置管理 - [ ] 分层架构 ### 可靠性 ✅ - [ ] 完善的异常处理 - [ ] 输入验证 - [ ] 日志记录 - [ ] 监控告警 - [ ] 优雅退出 ### 测试 ✅ - [ ] 单元测试覆盖率>80% - [ ] 回测结果验证 - [ ] 性能基准测试 ### 安全 ✅ - [ ] 敏感信息使用环境变量 - [ ] 输入验证 - [ ] 访问控制 --- **@yutiansut @quantaxis** **最后更新**: 2025-10-25 --- ## File: doc/development/code-standards.md # 代码规范 **版本**: 2.1.0-alpha2 **作者**: @yutiansut @quantaxis **更新日期**: 2025-10-25 本文档规定QUANTAXIS项目的代码规范,确保代码质量和一致性。 --- ## 🎯 代码规范概览 ### 核心原则 1. **可读性优先**: 代码是写给人看的,其次才是机器 2. **一致性**: 遵循统一的编码风格 3. **简洁性**: 简单优于复杂,明确优于隐晦 4. **文档化**: 代码即文档,清晰的命名和注释 5. **可测试性**: 代码应该易于测试 --- ## 🐍 Python代码规范 ### 1. PEP 8 基础规范 ```python # ✅ 正确的导入顺序 import os import sys from typing import List, Dict, Optional import pandas as pd import numpy as np import QUANTAXIS as QA from QUANTAXIS.QAUtil import QA_util_log_info from QUANTAXIS.QAData import QA_DataStruct_Stock_day # ❌ 错误的导入 from QUANTAXIS import * # 避免使用 * # ✅ 正确的命名 class QADataStruct: # 类名:CapWords pass def fetch_stock_data(): # 函数名:lowercase_with_underscores pass MARKET_STOCK = 'stock' # 常量:UPPER_CASE_WITH_UNDERSCORES user_id = '123' # 变量:lowercase_with_underscores # ✅ 正确的空格使用 result = calculate_value(a, b) # 函数调用 x = 1 + 2 # 运算符两侧 my_list = [1, 2, 3] # 逗号后 # ❌ 错误的空格 result=calculate_value( a,b ) x=1+2 ``` ### 2. 类型注解 ```python from typing import List, Dict, Optional, Union import pandas as pd # ✅ 函数类型注解 def fetch_stock_day( code: str, start: str, end: str, format: str = 'pd' ) -> pd.DataFrame: """获取股票日线数据 Args: code: 股票代码 start: 开始日期 end: 结束日期 format: 返回格式,默认pandas Returns: 股票日线数据DataFrame """ pass # ✅ 类型注解 class QAAccount: def __init__( self, account_cookie: str, init_cash: float = 1000000.0 ) -> None: self.account_cookie: str = account_cookie self.init_cash: float = init_cash self.balance: float = init_cash self.positions: Dict[str, 'QAPosition'] = {} def get_position(self, code: str) -> Optional['QAPosition']: """获取持仓""" return self.positions.get(code) ``` ### 3. 文档字符串 ```python # ✅ Google风格文档字符串 def calculate_sharpe_ratio( returns: pd.Series, risk_free_rate: float = 0.03 ) -> float: """计算夏普比率 夏普比率衡量每单位风险的超额收益。 Args: returns: 收益率序列 risk_free_rate: 无风险利率,默认3% Returns: 夏普比率 Raises: ValueError: 如果收益率序列为空 Examples: >>> returns = pd.Series([0.01, 0.02, -0.01, 0.03]) >>> sharpe = calculate_sharpe_ratio(returns) >>> print(f"夏普比率: {sharpe:.2f}") """ if len(returns) == 0: raise ValueError("收益率序列不能为空") excess_returns = returns - risk_free_rate / 252 return excess_returns.mean() / excess_returns.std() * np.sqrt(252) # ✅ 类文档字符串 class QAStrategyCtaBase: """CTA策略基类 提供CTA策略开发的基础框架,包括事件驱动、持仓管理等功能。 Attributes: code: 交易标的代码 frequence: 数据频率('1min', '5min', '1day'等) start: 回测开始日期 end: 回测结束日期 init_cash: 初始资金 Examples: >>> class MyStrategy(QAStrategyCtaBase): ... def user_init(self): ... self.ma_period = 20 ... ... def on_bar(self, bar): ... # 策略逻辑 ... pass """ pass ``` ### 4. 错误处理 ```python # ✅ 正确的异常处理 def fetch_data_with_retry(code: str, max_retries: int = 3) -> pd.DataFrame: """带重试的数据获取""" for attempt in range(max_retries): try: data = QA.QA_fetch_stock_day(code, '2024-01-01', '2024-12-31') if data is None or len(data) == 0: raise ValueError(f"未获取到数据: {code}") return data except ConnectionError as e: if attempt == max_retries - 1: raise logger.warning(f"连接失败,重试 {attempt + 1}/{max_retries}: {e}") time.sleep(2 ** attempt) except ValueError: logger.error(f"数据验证失败: {code}") raise except Exception as e: logger.error(f"未知错误: {e}") raise raise RuntimeError(f"获取数据失败,已重试{max_retries}次") # ❌ 避免裸except try: data = fetch_data() except: # 不要这样做 pass # ✅ 使用具体的异常 try: data = fetch_data() except (ValueError, KeyError) as e: logger.error(f"数据错误: {e}") raise ``` ### 5. 代码组织 ```python # ✅ 良好的代码组织 class QAStrategy: """策略类""" # 1. 类变量 DEFAULT_INIT_CASH = 1000000 # 2. 初始化方法 def __init__(self, code: str, init_cash: float = None): """初始化策略""" self.code = code self.init_cash = init_cash or self.DEFAULT_INIT_CASH self._setup() # 3. 公共方法 def run_backtest(self) -> None: """运行回测""" self._prepare_data() self._execute_strategy() self._calculate_metrics() def get_performance(self) -> Dict: """获取性能指标""" return self._performance_metrics # 4. 私有方法(按调用顺序) def _setup(self) -> None: """设置策略""" pass def _prepare_data(self) -> None: """准备数据""" pass def _execute_strategy(self) -> None: """执行策略""" pass def _calculate_metrics(self) -> None: """计算指标""" pass # 5. 魔术方法 def __repr__(self) -> str: return f"QAStrategy(code={self.code}, cash={self.init_cash})" ``` --- ## 📝 命名规范 ### 1. 模块和包名 ```python # ✅ 正确 QUANTAXIS/ ├── QAFetch/ # 包名:短小,全小写 │ ├── __init__.py │ ├── QAQuery.py # 模块名:QA前缀 + 功能 │ └── QATdx.py ├── QAData/ └── QAStrategy/ # ❌ 错误 QUANTAXIS/ ├── Fetch_Module/ # 避免下划线 ├── data.py # 太通用 └── my_strategy.py # 避免my/temp等前缀 ``` ### 2. 类和函数名 ```python # ✅ 类名:大驼峰 class QADataStructStockDay: pass class QAStrategyCtaBase: pass # ✅ 函数名:小写+下划线 def fetch_stock_day(): pass def calculate_sharpe_ratio(): pass # ✅ 私有方法:单下划线前缀 def _internal_helper(): pass # ✅ 魔术方法:双下划线 def __init__(self): pass # ❌ 避免 class qaStrategy: # 首字母应大写 pass def FetchData(): # 函数名不应大写 pass def __private_method(): # 避免双下划线前缀(非魔术方法) pass ``` ### 3. 变量名 ```python # ✅ 正确的变量命名 stock_code = '000001' user_id = 'user123' init_cash = 1000000 max_position_size = 5 # ✅ 常量:全大写 MAX_RETRY_TIMES = 3 DEFAULT_FREQUENCE = '1day' MARKET_TYPE_STOCK = 'stock_cn' # ✅ 私有变量:单下划线前缀 self._internal_state = None self._cache = {} # ❌ 避免 sc = '000001' # 太短,不清晰 stockCode = '000001' # Python不使用驼峰 temp = 123 # 避免temp, tmp等无意义名称 ``` --- ## 🔧 最佳实践 ### 1. 函数设计 ```python # ✅ 单一职责 def fetch_stock_data(code: str) -> pd.DataFrame: """只负责获取数据""" return QA.QA_fetch_stock_day(code, '2024-01-01', '2024-12-31') def calculate_ma(data: pd.DataFrame, period: int) -> pd.Series: """只负责计算均线""" return data['close'].rolling(period).mean() # ❌ 多重职责 def fetch_and_calculate(code: str, period: int): """不推荐:一个函数做太多事""" data = fetch_stock_data(code) ma = calculate_ma(data, period) save_to_database(ma) send_notification() return ma # ✅ 函数参数不宜过多 def create_strategy( code: str, start: str, end: str, *, # 强制后续参数使用关键字 init_cash: float = 1000000, frequence: str = '1day', commission: float = 0.0003 ) -> 'QAStrategy': """使用默认值和关键字参数""" pass # ❌ 参数过多 def create_strategy(code, start, end, init_cash, frequence, commission, slippage, benchmark, risk_free): pass # ✅ 使用配置对象 from dataclasses import dataclass @dataclass class StrategyConfig: code: str start: str end: str init_cash: float = 1000000 frequence: str = '1day' commission: float = 0.0003 def create_strategy(config: StrategyConfig) -> 'QAStrategy': """使用配置对象""" pass ``` ### 2. 列表推导式和生成器 ```python # ✅ 列表推导式(数据量小) codes = ['000001', '000002', '600000'] stock_names = [get_stock_name(code) for code in codes] # ✅ 生成器(数据量大) def fetch_all_stocks(): """使用生成器避免内存占用""" codes = QA.QA_fetch_stock_list()['code'] for code in codes: yield QA.QA_fetch_stock_day(code, '2024-01-01', '2024-12-31') # ✅ 条件推导 positive_returns = [r for r in returns if r > 0] # ❌ 过于复杂的推导 result = [ process(x, y, z) for x in data1 for y in data2 if condition1(x) for z in data3 if condition2(y, z) ] # 改用普通循环 # ✅ 普通循环更清晰 result = [] for x in data1: if not condition1(x): continue for y in data2: for z in data3: if condition2(y, z): result.append(process(x, y, z)) ``` ### 3. 上下文管理器 ```python # ✅ 使用with语句 with open('data.csv', 'r') as f: data = f.read() # ✅ 数据库连接 from pymongo import MongoClient def fetch_from_mongodb(collection: str, query: dict): with MongoClient('mongodb://localhost:27017') as client: db = client.quantaxis return list(db[collection].find(query)) # ✅ 自定义上下文管理器 from contextlib import contextmanager @contextmanager def timer(name: str): """计时上下文管理器""" start = time.time() try: yield finally: elapsed = time.time() - start logger.info(f"{name} 耗时: {elapsed:.2f}s") # 使用 with timer("数据获取"): data = fetch_stock_data('000001') ``` ### 4. 装饰器 ```python import functools import time from typing import Callable # ✅ 缓存装饰器 def cache(func: Callable) -> Callable: """简单缓存装饰器""" _cache = {} @functools.wraps(func) def wrapper(*args, **kwargs): key = str(args) + str(kwargs) if key not in _cache: _cache[key] = func(*args, **kwargs) return _cache[key] return wrapper @cache def fetch_stock_list(): """获取股票列表(会被缓存)""" return QA.QA_fetch_stock_list() # ✅ 重试装饰器 def retry(max_attempts: int = 3, delay: float = 1.0): """重试装饰器""" def decorator(func: Callable) -> Callable: @functools.wraps(func) def wrapper(*args, **kwargs): for attempt in range(max_attempts): try: return func(*args, **kwargs) except Exception as e: if attempt == max_attempts - 1: raise time.sleep(delay * (2 ** attempt)) return None return wrapper return decorator @retry(max_attempts=3, delay=2.0) def fetch_data_from_api(code: str): """从API获取数据(带重试)""" pass ``` --- ## ✅ 代码质量检查 ### 1. 使用pylint ```bash # 安装pylint pip install pylint # 检查单个文件 pylint QUANTAXIS/QAStrategy/qactabase.py # 检查整个包 pylint QUANTAXIS/ # 使用配置文件 pylint --rcfile=.pylintrc QUANTAXIS/ ``` ### 2. 使用black格式化 ```bash # 安装black pip install black # 格式化代码 black QUANTAXIS/ # 检查但不修改 black --check QUANTAXIS/ ``` ### 3. 使用mypy类型检查 ```bash # 安装mypy pip install mypy # 类型检查 mypy QUANTAXIS/ # 配置文件 mypy.ini [mypy] python_version = 3.8 warn_return_any = True warn_unused_configs = True ``` --- ## 📊 性能优化规范 ```python # ✅ 使用局部变量 def calculate_total(data: pd.DataFrame) -> float: # 缓存属性访问 values = data['close'].values total = 0 for value in values: total += value return total # ❌ 重复属性访问 def calculate_total_slow(data: pd.DataFrame) -> float: total = 0 for i in range(len(data)): total += data['close'].iloc[i] # 每次都访问 return total # ✅ 使用向量化 import numpy as np def calculate_returns_fast(prices: np.ndarray) -> np.ndarray: """向量化计算收益率""" return np.diff(prices) / prices[:-1] # ❌ 使用循环 def calculate_returns_slow(prices: list) -> list: """循环计算(慢)""" returns = [] for i in range(1, len(prices)): returns.append((prices[i] - prices[i-1]) / prices[i-1]) return returns ``` --- ## 🔗 相关资源 - **测试指南**: [测试指南文档](./testing.md) - **性能优化**: [性能优化指南](../advanced/performance-tuning.md) - **PEP 8**: https://peps.python.org/pep-0008/ --- ## 📝 总结 代码规范要点: ✅ **遵循PEP 8**: Python官方代码风格指南 ✅ **类型注解**: 提高代码可读性和可维护性 ✅ **清晰命名**: 变量和函数名应具有描述性 ✅ **文档完善**: 使用docstring记录API ✅ **工具检查**: 使用pylint/black/mypy --- **作者**: @yutiansut @quantaxis **最后更新**: 2025-10-25 [返回开发指南](../README.md) --- ## File: doc/development/contributing.md # QUANTAXIS 捐赠列表 写代码不易...请作者喝杯咖啡呗? (PS: 支付的时候 请带上你的名字/昵称呀 会维护一个赞助列表~ ) ======================= - 2017-9-25 沈乐 - 2017-9-25 许海涵 - 2017-9-27 吕少麟 - 2017-9-27 doskoi - 2017-10-1 zz - 2017-10-4 Hakase - 2017-10-4 头上无毛 - 2017-10-5 庆斌 - 2017-10-09 成成 - 2017-10-09 Rainx 徐景 - 2017-10-09 Dice(steven) - 2017-10-12 沈乐 - 2017-10-12 空空子 - 2017-10-12 宇清 - 2017-10-13 昊 - 2017-10-13 恒光 - 2017-10-30 Ims 黎明 - 2017-11-16 威 - 2017-11-26 SunnyBoy00 - 2017-12-05 威 - 2017-12-06 PdlMojoMoo - 2017-12-07 威 - 2017-12-19 在云端 - 2017-12-21 双宏 - 2017-12-28 在云端 - 2018-02-03 *明龙 - 2018-04-08 *轶 - 2018-04-10 *林 - 2018-04-10 *荣霖(东北必胜) - 2018-04-11 *冠 - 2018-04-30 *冠 - 2018-05-04 *文(lid) - 2018-05-17 申长春 - 2018-06-06 stephen - 2018-07-13 W *薇 - 2018-07-13 *吉 - 2018-07-14 *剑 - 2018-07-14 叶鸿浩 - 2018-07-16 牧童 - 2018-07-17 lun - 2018-08-28 Hakase - 2018-09-04 宇清 - 2018-09-05 *琛 - 2018-09-11 *建明 - 2018-09-21 毛毛 - 2018-09-25 润之大佬 - 2018-10-16 *群 - 2018-12-25 *宁(解语问股) - 2019-01-09 张杰(哲人石) - 2019-01-10 hakase - 2019-01-13 jason(*杰鑫) - 2019-01-27 *冰 - 2019-02-21 *文星 - 2019-03-24 *百强 - 2019-03-29 *振忠 - 2019-04-09 *彬 - 2019-04-29 *五洲 - 2019-05-14 *长春 - 2019-05-16 *长春 - 2019-07-23 *五洲 - 2019-08-08 *博思 感谢@尧 zhongjy1992@outlook.com 对于1.0.32版本做出的巨大贡献 --- ## File: doc/deployment/docker.md # QUANTAXIS DOCKER 提纲挈领的讲 此段内容分为4部分 1. 安装docker 2. 配置qa-service的环境 3. 以上两步干完了你改干啥 4. 如果你还闲得慌想要深入学习下docker的话 5. 看完这个教程以后 可以继续看 http://www.yutiansut.com:3000/topic/5dc5da7dc466af76e9e3bc5d ## 1. 安装docker ### ubuntu 一键脚本(仅限linux!!!!! 看清楚!!!!) ``` wget https://raw.githubusercontent.com/QUANTAXIS/QUANTAXIS/master/config/install_docker.sh sudo bash install_docker.sh ``` ### win/mac 安装 win/mac 下的docker 需要手动安装一个docker desktop 非常简单 去docker网站下载win/mac的docker_desktop 或者 文件较大, 我在群文件也共享了 ps: quantaxis强烈推荐不要使用win10以下的系统...(好吧忽略我) > 注意在安装exe的时候 最后一步 关于在使用windows container的地方 一定不要勾选 !!!!!! ``` 到此处 你应该已经装起来了一个docker 然后我们往下看 ``` ## 2. 使用QA_SERVICE(配置qa-service的环境) qaservice是一个帮你预装/预拉起好一切东西的一个docker environment 你需要理解的是 这个environment 你如果只是想使用(指的是 包括且不限于: 就想写个回测/ 就想实盘 / 就想看个可视化 / 这类) 的话, 只需要拉起这个qaservice环境即可, 你不需要不需要不需要学docker!! 注意 不需要会用docker!!!! 如果你需要二次开发=> 对我说的就是特别喜欢魔改别人代码的你 或者 你需要和你现有的功能组合的话 ==> 也不建议用docker, 建议在本地调试本地部署完毕以后, 再学习怎么制作docker镜像==> 实现你的二次开发/分发需求 你需要注意的是 qaenvironment是需要做一些预处理的 1/ 我们需要创建两个docker volume (1个是qamg 用来装数据库的数据文件 1个是qacode 用来存你写的代码) 2/ 在你对于docker volume的理解里 docker volume 就是在docker级别的可移动硬盘 3/ docker volume仅需要创建一次 4/ 这个qaservice的environment 需要一个叫做docker-compose.yaml的文件 4.1/ 你不需要理解docker-compose.yaml文件里的内容, 你只需要知道 这个yaml 是关于这个环境配置的设置文件 4.2/ 你唯一需要做的就是 建一个文件夹(爱建在哪里建哪里) 下载这个docker-compose.yaml ==> 复制粘贴进去 以上都是对win/mac的小白用户说的, 如果你已经是一个linux用户, 我默认你是一个精通百度搜索的男人... ### linux下的qa-service使用 第一次使用 ``` wget https://raw.githubusercontent.com/QUANTAXIS/QUANTAXIS/master/docker/qaservice_docker.sh sudo bash qaservice_docker.sh ``` 后续使用 ==> cd 到有docker-compose.yaml的文件夹 ``` docker-compose up -d ``` ### mac/windows下的qa-service使用 第一次使用 1. 打开你的命令行, 输入 ``` docker volume create --name=qamg docker volume create --name=qacode ``` 2. 下载docker-compose.yaml (https://raw.githubusercontent.com/QUANTAXIS/QUANTAXIS/master/docker/qa-service/docker-compose.yaml) 如果你不知道咋下载 可以去qq群 群文件下载 3. 找到你心爱的文件夹, 把这个宝贵的yaml放进去, 并记住你的文件夹目录(比如D:/qa/) 4. 打开你的命令行继续输入 ``` cd D:/qa (此处就是你心爱的文件夹的目录) docker-compose up ``` 后续使用 ``` cd D:/qa (此处就是你心爱的文件夹的目录) docker-compose pull (这里的意思是更新docker文件) docker-compose up ``` ## 3.怎么用docker? 你需要知道的是 quantaxis致力于帮你把配置环境这些脏活干完以后, 他实现了 ==> 帮你直接开启你需要的服务 ==> 你可以直接访问html界面来写回测/ 看回测/ 上实盘等 ==> 如果你本地有python环境 你可以在本地写, 并使用qaservice帮你开启的环境(比如数据库环境/ 比如mq环境) 端口: - 27017 mongodb - 8888 jupyter - 8010 quantaxis_webserver - 81 quantaxis_community 社区版界面 - 61208 系统监控 - 15672 qa-eventmq 然后就可以开始你的量化之路了骚年! 你需要注意的事情是 1. docker和本地环境是可以并存的 没有人说过(就算说了也肯定不是我说的) 有了本地python就不能有docker了 2. docker 的目的是方便你快速拉起 如果你真的很有兴趣把我辛辛苦苦写的18个quantaxis及相关模块都本地部署一遍我是非常欢迎的 ## 4.后面内容为docker进阶部分(指的是 如果你看不懂且不愿意看 就不用看) ### 查看每天数据更新日志: docker logs cron容器名 日志只输出到容器前台,如果日志对你很重要,建议用专业的日志收集工具,从cron容器收集日志 ### 查看服务状态 ``` docker ps docker stats docker-compose top docker-compose ps ``` ### 停止/删除 QUANTAXIS 服务 (包括 QUANTAXIS,自动更新服务,数据库容器): !!! 注意 这两条真的超级管用!!!! 不信你可以试下 停止: ``` docker stop $(docker ps -a -q) ``` 删除: ``` docker rm $(docker ps -a -q) ``` ### 更新: ``` docker-compose pull ``` ### 数据库备份(备份到宿主机当前目录,文件名:dbbackup.tar): 1. 停止服务 ``` docker-compose stop ``` 2. 备份到当前目录 ``` docker run --rm -v qamg:/data/db \ -v $(pwd):/backup alpine \ tar zcvf /backup/dbbackup.tar /data/db ``` ### 数据库还原(宿主机当前目录下必要有以前备份过的文件,文件名:dbbackup.tar): 1. 停止服务 ``` docker-compose stop ``` 2. 还原当前目录下的dbbackup.tar到mongod数据库 ``` docker run --rm -v qamg:/data/db \ -v $(pwd):/backup alpine \ sh -c "cd /data/db \ && rm -rf diagnostic.data \ && rm -rf journal \ && rm -rf configdb \ && cd / \ && tar xvf /backup/dbbackup.tar" ``` 3. 重新启动服务 ``` docker-compose up -d ``` --- ## File: doc/deployment/kubernetes.md # Kubernetes部署 **版本**: 2.1.0-alpha2 **作者**: @yutiansut @quantaxis **更新日期**: 2025-10-25 本文档介绍如何在Kubernetes集群上部署QUANTAXIS完整系统。 --- ## 🎯 部署架构 ### 系统组件 ``` ┌─────────────────────────────────────────────┐ │ Kubernetes Cluster │ │ │ │ ┌─────────────┐ ┌─────────────┐ │ │ │ Ingress │ │ Service │ │ │ └──────┬──────┘ └──────┬──────┘ │ │ │ │ │ │ ┌──────▼──────────────────▼──────┐ │ │ │ XWebServer (3 replicas) │ │ │ └──────┬──────────────────┬──────┘ │ │ │ │ │ │ ┌──────▼──────┐ ┌─────▼──────┐ │ │ │ MongoDB │ │ RabbitMQ │ │ │ │ StatefulSet │ │ StatefulSet│ │ │ └─────────────┘ └────────────┘ │ │ │ │ ┌─────────────────────────────────┐ │ │ │ XQuant (Strategy Pods) │ │ │ └─────────────────────────────────┘ │ └─────────────────────────────────────────────┘ ``` --- ## 📦 前置要求 ### 1. Kubernetes集群 ```bash # 检查集群版本 kubectl version # 推荐版本 Kubernetes: v1.24+ ``` ### 2. 存储配置 ```yaml # storage-class.yaml apiVersion: storage.k8s.io/v1 kind: StorageClass metadata: name: quantaxis-storage provisioner: kubernetes.io/aws-ebs # 根据云厂商调整 parameters: type: gp3 fsType: ext4 reclaimPolicy: Retain volumeBindingMode: WaitForFirstConsumer ``` ```bash kubectl apply -f storage-class.yaml ``` --- ## 🚀 快速部署 ### 1. 创建命名空间 ```bash kubectl create namespace quantaxis kubectl config set-context --current --namespace=quantaxis ``` ### 2. 部署MongoDB ```yaml # mongodb-statefulset.yaml apiVersion: v1 kind: Service metadata: name: mongodb namespace: quantaxis spec: ports: - port: 27017 name: mongodb clusterIP: None selector: app: mongodb --- apiVersion: apps/v1 kind: StatefulSet metadata: name: mongodb namespace: quantaxis spec: serviceName: mongodb replicas: 1 selector: matchLabels: app: mongodb template: metadata: labels: app: mongodb spec: containers: - name: mongodb image: mongo:5.0 ports: - containerPort: 27017 name: mongodb env: - name: MONGO_INITDB_ROOT_USERNAME value: "admin" - name: MONGO_INITDB_ROOT_PASSWORD valueFrom: secretKeyRef: name: mongodb-secret key: password volumeMounts: - name: mongodb-data mountPath: /data/db resources: requests: memory: "4Gi" cpu: "2" limits: memory: "8Gi" cpu: "4" volumeClaimTemplates: - metadata: name: mongodb-data spec: accessModes: [ "ReadWriteOnce" ] storageClassName: quantaxis-storage resources: requests: storage: 100Gi ``` ```bash # 创建Secret kubectl create secret generic mongodb-secret \ --from-literal=password='your-password-here' \ -n quantaxis # 部署MongoDB kubectl apply -f mongodb-statefulset.yaml ``` ### 3. 部署RabbitMQ ```yaml # rabbitmq-statefulset.yaml apiVersion: v1 kind: Service metadata: name: rabbitmq namespace: quantaxis spec: ports: - port: 5672 name: amqp - port: 15672 name: management clusterIP: None selector: app: rabbitmq --- apiVersion: apps/v1 kind: StatefulSet metadata: name: rabbitmq namespace: quantaxis spec: serviceName: rabbitmq replicas: 1 selector: matchLabels: app: rabbitmq template: metadata: labels: app: rabbitmq spec: containers: - name: rabbitmq image: rabbitmq:3.11-management ports: - containerPort: 5672 name: amqp - containerPort: 15672 name: management env: - name: RABBITMQ_DEFAULT_USER value: "admin" - name: RABBITMQ_DEFAULT_PASS valueFrom: secretKeyRef: name: rabbitmq-secret key: password volumeMounts: - name: rabbitmq-data mountPath: /var/lib/rabbitmq resources: requests: memory: "2Gi" cpu: "1" limits: memory: "4Gi" cpu: "2" volumeClaimTemplates: - metadata: name: rabbitmq-data spec: accessModes: [ "ReadWriteOnce" ] storageClassName: quantaxis-storage resources: requests: storage: 20Gi ``` ```bash # 创建Secret kubectl create secret generic rabbitmq-secret \ --from-literal=password='your-password-here' \ -n quantaxis # 部署RabbitMQ kubectl apply -f rabbitmq-statefulset.yaml ``` ### 4. 部署Web服务 ``` /* Detailed source-code truncated for AI context efficiency. */ ``` ```bash kubectl apply -f xwebserver-deployment.yaml ``` ### 5. 配置Ingress ```yaml # ingress.yaml apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: quantaxis-ingress namespace: quantaxis annotations: nginx.ingress.kubernetes.io/rewrite-target: / cert-manager.io/cluster-issuer: letsencrypt-prod spec: ingressClassName: nginx tls: - hosts: - quantaxis.example.com secretName: quantaxis-tls rules: - host: quantaxis.example.com http: paths: - path: / pathType: Prefix backend: service: name: xwebserver port: number: 80 ``` ```bash kubectl apply -f ingress.yaml ``` --- ## 📊 策略Pod部署 ### 策略Deployment ``` /* Detailed source-code truncated for AI context efficiency. */ ``` ```bash kubectl apply -f strategy-deployment.yaml ``` --- ## 🔧 配置管理 ### 1. ConfigMap管理 ```bash # 查看ConfigMap kubectl get configmap -n quantaxis # 更新ConfigMap kubectl edit configmap xwebserver-config -n quantaxis # 重启Pod应用配置 kubectl rollout restart deployment/xwebserver -n quantaxis ``` ### 2. Secret管理 ```bash # 查看Secret kubectl get secret -n quantaxis # 更新Secret kubectl create secret generic mongodb-secret \ --from-literal=password='new-password' \ --dry-run=client -o yaml | kubectl apply -f - # 重启相关Pod kubectl rollout restart statefulset/mongodb -n quantaxis ``` --- ## 📈 监控和日志 ### 1. 部署Prometheus ```yaml # prometheus-config.yaml apiVersion: v1 kind: ConfigMap metadata: name: prometheus-config namespace: quantaxis data: prometheus.yml: | global: scrape_interval: 15s scrape_configs: - job_name: 'xwebserver' kubernetes_sd_configs: - role: pod namespaces: names: - quantaxis relabel_configs: - source_labels: [__meta_kubernetes_pod_label_app] action: keep regex: xwebserver ``` ### 2. 查看日志 ```bash # 查看Pod日志 kubectl logs -f deployment/xwebserver -n quantaxis # 查看特定容器日志 kubectl logs -f statefulset/mongodb -n quantaxis # 查看最近100行日志 kubectl logs --tail=100 deployment/strategy-runner -n quantaxis # 导出所有日志 kubectl logs deployment/xwebserver -n quantaxis > xwebserver.log ``` ### 3. 事件监控 ```bash # 查看事件 kubectl get events -n quantaxis --sort-by='.lastTimestamp' # 监控Pod状态 kubectl get pods -n quantaxis -w ``` --- ## 🔄 维护操作 ### 1. 滚动更新 ```bash # 更新镜像 kubectl set image deployment/xwebserver \ xwebserver=quantaxis/xwebserver:2.1.1 \ -n quantaxis # 查看更新状态 kubectl rollout status deployment/xwebserver -n quantaxis # 回滚 kubectl rollout undo deployment/xwebserver -n quantaxis # 查看历史版本 kubectl rollout history deployment/xwebserver -n quantaxis ``` ### 2. 扩缩容 ```bash # 手动扩容 kubectl scale deployment/xwebserver --replicas=5 -n quantaxis # 自动扩容(HPA) kubectl autoscale deployment/xwebserver \ --min=3 --max=10 \ --cpu-percent=80 \ -n quantaxis ``` ### 3. 数据备份 ```bash # MongoDB备份 kubectl exec -it mongodb-0 -n quantaxis -- \ mongodump --out /backup/$(date +%Y%m%d) # 复制备份到本地 kubectl cp quantaxis/mongodb-0:/backup ./mongodb-backup ``` --- ## ⚠️ 故障排查 ### 常见问题 **Q1: Pod无法启动** ```bash # 查看Pod详情 kubectl describe pod -n quantaxis # 查看事件 kubectl get events -n quantaxis # 常见原因: # 1. 镜像拉取失败 → 检查镜像名称和权限 # 2. 资源不足 → kubectl top nodes # 3. 配置错误 → kubectl logs ``` **Q2: 服务连接失败** ```bash # 检查Service kubectl get svc -n quantaxis # 测试连接 kubectl run -it --rm debug \ --image=busybox \ --restart=Never \ -n quantaxis \ -- sh # 在Pod内测试 nslookup mongodb telnet rabbitmq 5672 ``` **Q3: 存储问题** ```bash # 查看PVC状态 kubectl get pvc -n quantaxis # 查看PV kubectl get pv # 如果PVC处于Pending状态,检查StorageClass kubectl describe pvc -n quantaxis ``` --- ## 🔗 相关资源 - **生产环境**: [生产环境部署](./production.md) - **性能优化**: [性能优化指南](../advanced/performance-tuning.md) - **Docker**: [Docker部署](./overview.md) --- ## 📝 总结 Kubernetes部署QUANTAXIS提供: ✅ **高可用**: 多副本部署,自动故障转移 ✅ **可扩展**: 水平扩展,弹性伸缩 ✅ **易维护**: 滚动更新,版本管理 ✅ **监控完善**: Prometheus + Grafana ✅ **存储持久化**: StatefulSet + PV/PVC --- **作者**: @yutiansut @quantaxis **最后更新**: 2025-10-25 [返回部署指南](../README.md) --- ## File: doc/deployment/overview.md # QUANTAXIS 2.1.0 部署指南 **版本**: 2.1.0-alpha2 **更新日期**: 2025-10-25 **作者**: @yutiansut @quantaxis --- ## 📋 目录 1. [概述](#概述) 2. [Docker部署](#docker部署) 3. [Kubernetes部署](#kubernetes部署) 4. [Helm Charts部署](#helm-charts部署) 5. [多环境配置](#多环境配置) 6. [监控和日志](#监控和日志) 7. [备份和恢复](#备份和恢复) 8. [故障排查](#故障排查) 9. [最佳实践](#最佳实践) --- ## 概述 ### 系统架构 ``` ┌─────────────────────────────────────────────────────────────┐ │ QUANTAXIS 2.1.0 │ ├─────────────────────────────────────────────────────────────┤ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ │ Jupyter │ │ Web │ │ Monitor │ │ Collector│ │ │ │ :8888 │ │ :8080 │ │ :61208 │ │ :8011 │ │ │ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │ │ │ │ │ │ │ │ └─────────────┴──────────────┴─────────────┘ │ │ │ │ │ ┌──────────────────┴──────────────────┐ │ │ │ QUANTAXIS Core Service │ │ │ │ (资源管理器 + API) │ │ │ └──────────────────┬──────────────────┘ │ │ │ │ │ ┌────────────┬─────────┴────────┬──────────┬─────────┐ │ │ │ │ │ │ │ │ │ ▼ ▼ ▼ ▼ ▼ │ │ MongoDB RabbitMQ Redis ClickHouse Logs │ │ :27017 :5672 :6379 :8123 │ └─────────────────────────────────────────────────────────────┘ ``` ### 组件说明 | 组件 | 版本 | 端口 | 说明 | |------|------|------|------| | **MongoDB** | 7.0 | 27017 | 主数据存储 | | **RabbitMQ** | 3.13 | 5672, 15672 | 消息队列 | | **Redis** | 7.0 | 6379 | 缓存服务 | | **ClickHouse** | latest | 8123, 9000 | 分析数据库(可选) | | **QUANTAXIS Core** | 2.1.0 | 8010 | 核心服务 | | **Jupyter** | - | 8888 | 交互式开发 | | **Web UI** | - | 8080 | Web界面 | | **Monitor** | - | 61208 | 系统监控 | --- ## Docker部署 ### 前置要求 - Docker >= 20.10 - Docker Compose >= 2.0 - 可用内存 >= 8GB - 可用磁盘 >= 50GB ### 快速开始 #### 1. 基础部署 (核心服务) ```bash # 克隆仓库 git clone https://github.com/QUANTAXIS/QUANTAXIS.git cd QUANTAXIS/docker/qa-service-v2.1 # 复制环境变量配置 cp .env.example .env # 编辑.env修改密码(生产环境必须!) # 启动服务 docker-compose up -d # 查看日志 docker-compose logs -f ``` #### 2. 完整部署 (包含所有可选服务) ```bash # 启动所有服务(包括ClickHouse和行情采集) docker-compose --profile full up -d ``` #### 3. 指定profile部署 ```bash # 仅启动分析服务(包括ClickHouse) docker-compose --profile analytics up -d # 仅启动行情采集 docker-compose --profile market up -d ``` ### 服务访问 | 服务 | 访问地址 | 默认账号 | |------|---------|---------| | Jupyter | http://localhost:8888 | - | | Web UI | http://localhost:8080 | - | | RabbitMQ管理 | http://localhost:15672 | admin/admin | | 系统监控 | http://localhost:61208 | - | | QUANTAXIS API | http://localhost:8010 | - | ### 常用命令 ```bash # 查看服务状态 docker-compose ps # 查看资源使用 docker-compose stats # 查看日志 docker-compose logs -f [service_name] # 重启服务 docker-compose restart [service_name] # 停止服务 docker-compose stop # 完全清理(包括数据卷,危险!) docker-compose down -v ``` ### 数据持久化 数据存储在Docker volumes中: ```bash # 查看所有volumes docker volume ls | grep quantaxis # 数据卷列表 # - quantaxis_mongodb_data (MongoDB数据) # - quantaxis_rabbitmq_data (RabbitMQ数据) # - quantaxis_redis_data (Redis数据) # - quantaxis_clickhouse_data (ClickHouse数据) # - quantaxis_code (用户代码) # - quantaxis_logs (日志) ``` ### 数据备份 ```bash # 备份MongoDB docker run --rm \ -v quantaxis_mongodb_data:/data \ -v $(pwd)/backup:/backup \ alpine \ tar czf /backup/mongodb_$(date +%Y%m%d).tar.gz /data # 备份所有数据 ./scripts/backup-all.sh ``` ### 更新升级 ```bash # 拉取最新镜像 docker-compose pull # 重新创建容器 docker-compose up -d --force-recreate ``` --- ## Kubernetes部署 ### 前置要求 - Kubernetes >= 1.24 - kubectl配置正确 - 至少3个工作节点 - 可用内存 >= 16GB (每节点) - StorageClass可用 ### 快速开始 #### 1. 创建命名空间和基础资源 ```bash cd QUANTAXIS/docker/k8s-deployment # 1. 创建命名空间 kubectl apply -f 00-namespace.yaml # 2. 创建ConfigMap和Secret kubectl apply -f 01-configmap.yaml # 修改密码 (生产环境必须!) kubectl create secret generic mongodb-secret \ --from-literal=MONGO_ROOT_USER=root \ --from-literal=MONGO_ROOT_PASSWORD='your-strong-password' \ --from-literal=MONGO_USER=quantaxis \ --from-literal=MONGO_PASSWORD='quantaxis-password' \ --namespace=quantaxis --dry-run=client -o yaml | kubectl apply -f - # 3. 创建存储 kubectl apply -f 03-storage.yaml # 4. 部署数据库服务 kubectl apply -f 10-mongodb.yaml kubectl apply -f 11-rabbitmq.yaml kubectl apply -f 12-redis.yaml # 5. 等待数据库就绪 kubectl wait --for=condition=ready pod -l app=mongodb -n quantaxis --timeout=300s kubectl wait --for=condition=ready pod -l app=rabbitmq -n quantaxis --timeout=300s # 6. 部署QUANTAXIS核心服务 kubectl apply -f 50-quantaxis.yaml # 7. 验证部署 kubectl get pods -n quantaxis kubectl get svc -n quantaxis ``` #### 2. 查看部署状态 ```bash # 查看所有资源 kubectl get all -n quantaxis # 查看Pod详情 kubectl describe pod -n quantaxis # 查看日志 kubectl logs -f deployment/quantaxis -n quantaxis # 进入容器 kubectl exec -it deployment/quantaxis -n quantaxis -- bash ``` #### 3. 访问服务 ```bash # 方式1: 端口转发 kubectl port-forward -n quantaxis service/quantaxis-service 8888:8888 8010:8010 # 方式2: 获取LoadBalancer外部IP kubectl get svc quantaxis-service -n quantaxis # 方式3: Ingress (需要先配置Ingress Controller) kubectl apply -f 60-ingress.yaml ``` ### 扩缩容 ```bash # 手动扩容 kubectl scale deployment quantaxis --replicas=5 -n quantaxis # 查看HPA状态 kubectl get hpa -n quantaxis # HPA自动扩缩容配置在50-quantaxis.yaml中 # 基于CPU和内存使用率自动调整副本数 (2-10) ``` ### 滚动更新 ```bash # 更新镜像 kubectl set image deployment/quantaxis \ quantaxis=quantaxis/quantaxis:2.1.0-alpha3 \ -n quantaxis # 查看更新状态 kubectl rollout status deployment/quantaxis -n quantaxis # 回滚 kubectl rollout undo deployment/quantaxis -n quantaxis ``` ### 资源监控 ```bash # 查看资源使用 kubectl top nodes kubectl top pods -n quantaxis # 查看事件 kubectl get events -n quantaxis --sort-by='.lastTimestamp' ``` --- ## Helm Charts部署 ### 安装Helm ```bash # 下载Helm curl https://raw.githubusercontent.com/helm/helm/main/scripts/get-helm-3 | bash # 验证安装 helm version ``` ### 使用Helm部署 ```bash cd QUANTAXIS/docker/helm-charts # 1. 添加仓库(如果有) # helm repo add quantaxis https://quantaxis.github.io/charts # helm repo update # 2. 查看默认配置 helm show values ./quantaxis # 3. 自定义配置 cat > custom-values.yaml << EOF # MongoDB配置 mongodb: auth: rootPassword: "your-root-password" password: "your-quantaxis-password" persistence: size: 100Gi # QUANTAXIS配置 quantaxis: replicas: 3 resources: limits: cpu: 4 memory: 8Gi requests: cpu: 1 memory: 2Gi EOF # 4. 安装 helm install quantaxis ./quantaxis \ --namespace quantaxis \ --create-namespace \ --values custom-values.yaml # 5. 查看状态 helm status quantaxis -n quantaxis helm list -n quantaxis # 6. 升级 helm upgrade quantaxis ./quantaxis \ --namespace quantaxis \ --values custom-values.yaml # 7. 卸载 helm uninstall quantaxis -n quantaxis ``` ### Helm配置说明 主要配置项 (values.yaml): ```yaml # 全局配置 global: storageClass: "quantaxis-ssd" imagePullPolicy: IfNotPresent # MongoDB mongodb: enabled: true auth: rootPassword: "" password: "" persistence: size: 50Gi # RabbitMQ rabbitmq: enabled: true auth: username: admin password: "" persistence: size: 10Gi # Redis redis: enabled: true auth: password: "" persistence: size: 10Gi # ClickHouse (可选) clickhouse: enabled: false persistence: size: 100Gi # QUANTAXIS quantaxis: replicas: 2 image: tag: "2.1.0-alpha2" resources: limits: cpu: 4 memory: 8Gi requests: cpu: 1 memory: 2Gi # Ingress ingress: enabled: false className: "nginx" hosts: - host: quantaxis.example.com paths: - path: / pathType: Prefix ``` --- ## 多环境配置 ### 环境划分 | 环境 | 用途 | 副本数 | 资源配置 | |------|------|--------|---------| | **Development** | 开发测试 | 1 | 最小 | | **Staging** | 预生产 | 2 | 中等 | | **Production** | 生产 | 3+ | 完整 | ### Docker Compose多环境 #### 开发环境 ```yaml # docker-compose.dev.yaml version: '3.8' services: quantaxis: image: quantaxis/quantaxis:2.1.0-alpha2-dev environment: - DEPLOY_ENV=development - DEBUG=true resources: limits: cpus: '2' memory: 2G ``` ```bash # 启动开发环境 docker-compose \ -f docker-compose.yaml \ -f docker-compose.dev.yaml \ up -d ``` #### 生产环境 ```yaml # docker-compose.prod.yaml version: '3.8' services: quantaxis: image: quantaxis/quantaxis:2.1.0-alpha2 environment: - DEPLOY_ENV=production - DEBUG=false deploy: replicas: 3 resources: limits: cpus: '4' memory: 8G ``` ```bash # 启动生产环境 docker-compose \ -f docker-compose.yaml \ -f docker-compose.prod.yaml \ up -d ``` ### Kubernetes多环境 使用Kustomize管理多环境: ``` k8s-deployment/ ├── base/ # 基础配置 │ ├── kustomization.yaml │ ├── deployment.yaml │ └── service.yaml ├── overlays/ │ ├── dev/ # 开发环境 │ │ ├── kustomization.yaml │ │ └── patches/ │ ├── staging/ # 预生产环境 │ │ ├── kustomization.yaml │ │ └── patches/ │ └── prod/ # 生产环境 │ ├── kustomization.yaml │ └── patches/ ``` ```bash # 部署到不同环境 kubectl apply -k overlays/dev kubectl apply -k overlays/staging kubectl apply -k overlays/prod ``` --- ## 监控和日志 ### Prometheus监控 ```bash # 安装Prometheus Operator helm repo add prometheus-community \ https://prometheus-community.github.io/helm-charts helm install prometheus \ prometheus-community/kube-prometheus-stack \ --namespace monitoring \ --create-namespace # QUANTAXIS已配置Prometheus注解 # 自动被Prometheus发现和抓取指标 ``` ### Grafana仪表板 ```bash # 访问Grafana kubectl port-forward -n monitoring \ svc/prometheus-grafana 3000:80 # 登录: admin / prom-operator # 导入QUANTAXIS仪表板 (ID: TODO) ``` ### ELK日志 ```bash # 安装Elastic Stack helm repo add elastic https://helm.elastic.co helm install elasticsearch elastic/elasticsearch -n logging --create-namespace helm install kibana elastic/kibana -n logging helm install filebeat elastic/filebeat -n logging # QUANTAXIS日志会被Filebeat收集 ``` ### Loki日志 ```bash # 安装Loki Stack helm repo add grafana https://grafana.github.io/helm-charts helm install loki grafana/loki-stack -n logging --create-namespace # 在Grafana中添加Loki数据源 ``` --- ## 备份和恢复 ### MongoDB备份 #### Docker环境 ```bash # 备份 docker exec quantaxis-mongodb mongodump \ --out=/backup/$(date +%Y%m%d) # 复制备份文件到主机 docker cp quantaxis-mongodb:/backup ./mongodb-backup # 恢复 docker exec quantaxis-mongodb mongorestore \ /backup/20251025 ``` #### Kubernetes环境 ```bash # 创建备份Job kubectl apply -f backup-job.yaml # 手动触发备份 kubectl create job --from=cronjob/mongodb-backup \ mongodb-backup-manual -n quantaxis ``` ### 持久化卷备份 ```bash # 使用Velero备份整个命名空间 velero backup create quantaxis-backup \ --include-namespaces quantaxis # 恢复 velero restore create --from-backup quantaxis-backup ``` --- ## 故障排查 ### 常见问题 #### 1. MongoDB连接失败 ```bash # 检查MongoDB状态 kubectl get pods -l app=mongodb -n quantaxis kubectl logs -l app=mongodb -n quantaxis # 测试连接 kubectl run -it --rm mongo-test \ --image=mongo:7.0 \ --restart=Never \ --namespace=quantaxis \ -- mongosh mongodb://mongodb-service:27017 ``` #### 2. 内存不足 ```bash # 查看资源使用 kubectl top pods -n quantaxis # 增加资源限制 kubectl edit deployment quantaxis -n quantaxis # 修改resources.limits.memory ``` #### 3. Pod无法启动 ```bash # 查看Pod事件 kubectl describe pod -n quantaxis # 查看日志 kubectl logs -n quantaxis --previous ``` ### 调试工具 ```bash # 进入调试容器 kubectl debug -it -n quantaxis --image=busybox # 网络调试 kubectl run -it --rm debug \ --image=nicolaka/netshoot \ --restart=Never \ --namespace=quantaxis ``` --- ## 最佳实践 ### 安全 1. ✅ **修改所有默认密码** 2. ✅ **使用Secret管理敏感信息** 3. ✅ **启用RBAC权限控制** 4. ✅ **配置Network Policy** 5. ✅ **定期更新镜像和依赖** ### 性能 1. ✅ **合理配置资源请求和限制** 2. ✅ **使用SSD存储** 3. ✅ **启用持久化卷** 4. ✅ **配置亲和性和反亲和性** 5. ✅ **使用HPA自动扩缩容** ### 可靠性 1. ✅ **配置健康检查和就绪探针** 2. ✅ **设置Pod Disruption Budget** 3. ✅ **多副本部署** 4. ✅ **定期备份数据** 5. ✅ **配置监控和告警** ### 运维 1. ✅ **使用基础设施即代码 (IaC)** 2. ✅ **Git管理配置文件** 3. ✅ **自动化CI/CD流程** 4. ✅ **文档化运维流程** 5. ✅ **定期演练灾难恢复** --- ## 附录 ### A. 端口清单 | 服务 | 端口 | 协议 | 说明 | |------|------|------|------| | MongoDB | 27017 | TCP | 数据库连接 | | RabbitMQ | 5672 | TCP | AMQP协议 | | RabbitMQ管理 | 15672 | HTTP | 管理界面 | | RabbitMQ Prometheus | 15692 | HTTP | 指标 | | Redis | 6379 | TCP | 缓存连接 | | ClickHouse HTTP | 8123 | HTTP | HTTP接口 | | ClickHouse Native | 9000 | TCP | Native接口 | | QUANTAXIS API | 8010 | HTTP | API服务 | | Jupyter | 8888 | HTTP | 开发环境 | | Web UI | 8080 | HTTP | Web界面 | | Monitor | 61208 | HTTP | 监控界面 | | Market Collector | 8011 | HTTP | 行情采集 | ### B. 资源推荐配置 | 部署规模 | CPU | 内存 | 存储 | 节点数 | |---------|-----|------|------|--------| | **小型** | 8核 | 16GB | 100GB | 1 | | **中型** | 16核 | 32GB | 500GB | 3 | | **大型** | 32核 | 64GB | 1TB | 5+ | ### C. 相关链接 - [QUANTAXIS GitHub](https://github.com/QUANTAXIS/QUANTAXIS) - [Docker Hub](https://hub.docker.com/u/quantaxis) - [官方文档](https://doc.yutiansut.com/) - [社区论坛](http://www.yutiansut.com/) --- **作者**: @yutiansut @quantaxis **最后更新**: 2025-10-25 **版本**: 2.1.0-alpha2 如有问题,请提交Issue或加入QQ群: 563280067 ## 2. Official Technical Reference & Guides (yutiansut/yutiansut.github.io) # The Minimal Light Theme [](https://github.com/yaoyao-liu/minimal-light/blob/main/LICENSE) \[[Demo the theme](https://minimal-light-theme.yliu.me/)\] \[[简体中文](https://github.com/yaoyao-liu/minimal-light/blob/master/README_zh_Hans.md) | [繁體中文](https://github.com/yaoyao-liu/minimal-light/blob/master/README_zh_Hant.md) | [Deutsche](https://github.com/yaoyao-liu/minimal-light/blob/master/README_de.md)\] *This is the source code of my homepage. I build this website based on [minimal](https://github.com/orderedlist/minimal).* *Feel free to use and share the source code anywhere you like.* The latest version of my homepage is available here: [[link](https://github.com/yaoyao-liu/yaoyao-liu.github.io)] A template for Max Planck Institute for Informatics is available here: [[link](https://github.com/yaoyao-liu/minimal-light-theme-mpi-inf)] ## Features - Simple and elegant personal homepage theme - Jekyll theme, automatically deployed by GitHub Pages - Basic search engine optimization - Mobile friendly - Supporting Markdown - Supporting dark mode ## Project Architecture ``` . ├── _data | └── publications.yml # the YAML file for publications ├── _includes | ├── publications.md # the Markdown file for publications | └── services.md # the Markdown file for services ├── _layouts | └── homepage.html # the html template for the homepage ├── _sass | ├── minimal-light.scss # this file will be compiled into a CSS file to control the style of the page | └── minimal-light-no-dark-mode.scss # this file is similar to minimal-light.scss with the dark mode disabled ├── assets # some files ├── html_source_file # compiled HTML files ├── .gitignore # this file specifies intentionally untracked files that Git should ignore ├── CNAME # the custom domain, will be used by GitHub page sevice ├── Gemfile # a RubyGems related file ├── LICENSE # the license file ├── README.md # the readme file (English) ├── README_de.md # the readme file (German) ├── README_zh_Hans.md # the readme file (Simplified Chinese) ├── README_zh_Hant.md # the readme file (Traditional Chinese) ├── _config.yml # the Jekyll configuration file, including some options of the page └── index.md # the content of the index page, using Markdown ``` ## Getting Started This template can be used in the following two ways: - **Using with the GitHub Pages Service.** GitHub will provide you with a server to generate and host web pages. - **Using locally with Jekyll.** You may install Jekyll on your own computer and generate static web pages (i.e., HTML files) with this template. After that, you may upload the HTML files to your server. The detailed instructions are available below. ### Using with the GitHub Pages Service There are two ways to use this template on GitHub: #### Fork this repository - Fork this repository (or [use this repository as a template](https://docs.github.com/en/github/creating-cloning-and-archiving-repositories/creating-a-repository-from-a-template)) and change the name to `your-username.github.io`. - Enable the GitHub pages for that repository following the steps [here](https://docs.github.com/en/pages/getting-started-with-github-pages/creating-a-github-pages-site#creating-your-site). #### Using this repository as a remote theme To use this theme, add the following to your repository's `_config.yml`: ```yaml remote_theme: yaoyao-liu/minimal-light ``` Please note that adding the above line will directly apply all the default settings in this repository to yours. If you hope to edit any files (e.g., `index.md`), you still need to copy them to your repository. ### Using Locally with Jekyll First, install [Ruby](https://www.ruby-lang.org/en/) and [Jekyll](https://jekyllrb.com/). The install instructions can be found here: Then, clone this repository: ```bash git clone https://github.com/yaoyao-liu/minimal-light.git cd minimal-light ``` Install and run: ```bash bundle install bundle add webrick bundle exec jekyll server ``` View the live page using `localhost`: . You can get the HTML files in `_site` folder. ### Using the HTML version The compiled HTML files are available in the `html_source_file` folder. If you don't like Jekyll, you may directly edit and use the HTML version. ## Customizing ### Configuration variables The Minimal Light theme will respect the following variables, if set in your site's `_config.yml`: ```yaml # Basic Information title: Your Name position: Ph.D. Student affiliation: Your Affiliation email: yourname (at) example.edu # Search Engine Optimization (SEO) # The following information is used to improve the website traffic from search engines, e.g., Google. keywords: minimal light canonical: https://minimal-light-theme.yliu.me/ # Links # If you don't need one of them, you may delete the corresponding line. google_scholar: https://scholar.google.com/ cv_link: assets/files/curriculum_vitae.pdf github_link: https://github.com/ linkedin: https://www.linkedin.com/ twitter: https://twitter.com/ # Images (e.g., your profile picture and your website's favicon) # "favicon" and "favicon_dark" are used for the light and dark modes, respectively. avatar: ./assets/img/avatar.png favicon: ./assets/img/favicon.png favicon_dark: ./assets/img/favicon-dark.png # Footnote # You may use the option to disable the footnote, "Powered by Jekyll and Minimal Light theme." enable_footnote: true # Auto Dark Mode # You may use the option to disable the automatic dark theme auto_dark_mode: true # Font # You can use this option to choose between Serif or Sans Serif fonts. font: "Serif" # or "Sans Serif" # Google Analytics ID # Please remove this if you don't use Google Analytics google_analytics: UA-111540567-4 ``` ### Edit `index.md` Create `index.md` and add your personal information. It supports **Markdown** and **HTML** syntax. ### Edit included files There are two markdown files included in `index.md`. They are `_includes/publications.md` and `_includes/service.md`, respectively. These two files also support **Markdown** and **HTML** syntax. If you don't hope to include these two files, you may remove the following lines in `index.md`: https://github.com/yaoyao-liu/minimal-light/blob/b38070cd0b6bce45d8a885f3828549af8f82b7cb/index.md?plain=1#L21-L23 If you hope to edit the publication list without changing the format, you may edit `_data/publications.yml`: https://github.com/yaoyao-liu/minimal-light/blob/77b1b3b31d4561091bcd739f37a2e1880e8b5ca5/_data/publications.yml#L3-L11 ### Stylesheet If you'd like to add your own custom styles, you may edit `_sass/minimal-light.scss`. ### Layouts If you'd like to change the theme's HTML layout, you may edit `_layout/homepage.html`. ## License This work is licensed under a [Creative Commons Zero v1.0 Universal](https://github.com/yaoyao-liu/minimal-light/blob/master/LICENSE) License. ## Acknowledgements Our project uses the source code from the following repositories: * [pages-themes/minimal](https://github.com/pages-themes/minimal) * [orderedlist/minimal](https://github.com/orderedlist/minimal) * [al-folio](https://github.com/alshedivat/al-folio)