Files
sanguo_vnpy/docs/05-user-manual.md
2026-04-29 20:20:32 +08:00

205 lines
5.3 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 05 - 用户手册
**版本**: v1.0
**日期**: 2026-04-29
---
## 1. 概述
本手册面向三国量化团队所有成员,说明如何使用回测服务进行策略回测。
## 2. 服务地址
| 服务 | 地址 | 用途 |
|------|------|------|
| 回测API | `http://192.168.2.154:8088` | 提交/查询回测任务 |
| API文档 | `http://192.168.2.154:8088/docs` | Swagger交互式文档 |
| Jupyter | `http://192.168.2.154:8888` | 开发环境(token: sanguo123 |
## 3. 提交回测任务
### 3.1 策略代码要求
策略代码必须包含一个继承自 `CtaTemplate` 的类:
```python
from vnpy_ctastrategy import CtaTemplate
from vnpy.trader.object import BarData
class MyStrategy(CtaTemplate):
"""你的策略类名"""
parameters = [] # 策略参数列表
variables = [] # 策略变量列表
def on_init(self):
self.write_log("策略初始化")
def on_start(self):
self.write_log("策略启动")
def on_stop(self):
self.write_log("策略停止")
def on_bar(self, bar: BarData):
# 在这里写你的策略逻辑
pass
```
### 3.2 提交请求
**端点**: `POST http://192.168.2.154:8088/api/backtest/submit`
```json
{
"strategy_name": "my_ma_strategy",
"strategy_code": "from vnpy_ctastrategy import CtaTemplate\n\nclass MyStrategy(CtaTemplate):\n def on_bar(self, bar):\n pass",
"symbol": "510300.SSE",
"interval": "1d",
"start_date": "2024-01-01",
"end_date": "2024-12-31",
"capital": 1000000,
"engine_type": "cta"
}
```
**参数说明**:
| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| strategy_name | string | ✅ | 策略名称 |
| strategy_code | string | ✅ | 策略代码(含CtaTemplate子类) |
| symbol | string | ✅ | 合约代码(如 510300.SSE, IF888.CFFEX |
| interval | string | ✅ | K线周期(1m/5m/15m/1h/1d |
| start_date | date | ✅ | 开始日期(YYYY-MM-DD |
| end_date | date | ✅ | 结束日期(YYYY-MM-DD |
| capital | float | ✅ | 初始资金 |
| engine_type | string | ✅ | 引擎类型(固定为"cta" |
| tick_size | float | ❌ | 最小变动价位 |
### 3.3 Python调用示例
```python
import requests
import time
API_URL = "http://192.168.2.154:8088/api/backtest"
# 提交任务
response = requests.post(f"{API_URL}/submit", json={
"strategy_name": "dual_ma",
"strategy_code": open("my_strategy.py").read(),
"symbol": "510300.SSE",
"interval": "1d",
"start_date": "2024-01-01",
"end_date": "2024-12-31",
"capital": 1000000,
"engine_type": "cta"
})
task_id = response.json()["data"]["task_id"]
print(f"任务已提交: {task_id}")
# 轮询等待结果
while True:
status = requests.get(f"{API_URL}/status/{task_id}").json()
state = status["data"]["status"]
if state in ("completed", "failed"):
break
print(f"状态: {state}")
time.sleep(2)
# 获取结果
result = requests.get(f"{API_URL}/result/{task_id}").json()
if result["data"]["status"] == "completed":
stats = result["data"]["statistics"]
print(f"总收益率: {stats['total_return']:.2%}")
print(f"夏普比率: {stats['sharpe_ratio']:.2f}")
print(f"最大回撤: {stats['max_drawdown']:.2%}")
else:
print(f"回测失败: {result['data']['error_message']}")
```
### 3.4 curl调用示例
```bash
# 提交任务
TASK=$(curl -s -X POST http://192.168.2.154:8088/api/backtest/submit \
-H "Content-Type: application/json" \
-d '{
"strategy_name": "test",
"strategy_code": "from vnpy_ctastrategy import CtaTemplate\nclass T(CtaTemplate):\n def on_bar(self, bar): pass",
"symbol": "510300.SSE",
"interval": "1d",
"start_date": "2024-01-01",
"end_date": "2024-06-30",
"capital": 1000000,
"engine_type": "cta"
}')
TASK_ID=$(echo $TASK | python3 -c "import sys,json;print(json.load(sys.stdin)['data']['task_id'])")
# 查询状态
curl http://192.168.2.154:8088/api/backtest/status/$TASK_ID | python3 -m json.tool
# 获取结果
curl http://192.168.2.154:8088/api/backtest/result/$TASK_ID | python3 -m json.tool
```
## 4. 查询任务
### 4.1 单个任务状态
```bash
GET /api/backtest/status/{task_id}
```
返回字段:
- `status`: pending / running / completed / failed
- `created_at`: 创建时间
- `started_at`: 开始执行时间
- `completed_at`: 完成时间
### 4.2 任务列表
```bash
GET /api/backtest/list?page=1&page_size=10&status=completed
```
### 4.3 回测结果
```bash
GET /api/backtest/result/{task_id}
```
结果字段:
- `statistics`: 回测统计(收益率、夏普比率、最大回撤等)
- `error_message`: 失败时的错误信息
- `result_csv_path`: 结果CSV文件路径
- `equity_curve_png_path`: 资金曲线图路径
## 5. 常见问题
### Q: 策略提交后失败,提示"没有找到CtaTemplate子类"
**A**: 策略代码中必须定义一个继承自 `CtaTemplate` 的类。
### Q: 合约代码格式是什么?
**A**: `{合约代码}.{交易所代码}`,如:
- 沪深300ETF: `510300.SSE`
- 沪深300指数: `000300.SSE`
- 中证500股指: `IC888.CFFEX`
### Q: 支持哪些K线周期?
**A**: `1m`(1分钟), `5m`(5分钟), `15m`(15分钟), `1h`(1小时), `1d`(日线)
### Q: 数据从哪里来?
**A**: 当前使用akshare实时数据。如需完整历史数据,联系赵云(数据护军)。
---
*三国量化团队 · 姜维(平台总督)*