178 lines
5.2 KiB
Markdown
178 lines
5.2 KiB
Markdown
# AGENTS.md - Quant Trading Project Guidelines
|
|
|
|
This document provides guidelines for agentic coding agents operating in this repository.
|
|
|
|
## 对话语言规则 (Conversation Language Rules)
|
|
|
|
- **请始终使用简体中文进行回复,除非我明确要求使用其他语言。**
|
|
- **涉及编程术语时,请保留英文原文并(在必要时)提供中文解释。**
|
|
|
|
## Project Overview
|
|
|
|
Python-based quantitative trading system with:
|
|
- Backtesting engine (`src/backtest_engine.py`)
|
|
- Multiple strategy implementations (`src/strategies/`)
|
|
- TQSdk integration for real-time trading (`src/tqsdk_engine.py`, `src/tqsdk_real_engine.py`)
|
|
- Strategy management (`strategy_manager/`)
|
|
- Data processing and analysis (`src/analysis/`)
|
|
|
|
## Build, Lint, and Test Commands
|
|
|
|
### Python Environment
|
|
```bash
|
|
# Install dependencies
|
|
pip install -r requirements.txt
|
|
|
|
# Run single test file
|
|
pytest test/test_file.py -v
|
|
|
|
# Run single test function
|
|
pytest test/test_file.py::TestClass::test_function -v
|
|
|
|
# Run tests with coverage
|
|
pytest --cov=src --cov-report=term-missing
|
|
|
|
# Run tests matching pattern
|
|
pytest -k "test_name_pattern"
|
|
```
|
|
|
|
### Jupyter Notebooks
|
|
Several research notebooks exist in root directory:
|
|
- `main.ipynb`, `main2.ipynb`, `main_multi.ipynb`
|
|
- `grid_search.ipynb`, `grid_search_multi_process.ipynb`
|
|
- `tqsdk_main.ipynb`, `tqsdk_main2.ipynb`
|
|
|
|
Run via Jupyter Lab:
|
|
```bash
|
|
jupyter lab
|
|
```
|
|
|
|
### Strategy Manager (Web Backend)
|
|
```bash
|
|
cd strategy_manager && python start.py
|
|
```
|
|
|
|
## Code Style Guidelines
|
|
|
|
### Imports
|
|
- Use absolute imports from `src` package:
|
|
```python
|
|
from src.backtest_engine import BacktestEngine
|
|
from src.strategies.base_strategy import Strategy
|
|
```
|
|
- Group imports: standard library → third-party → local modules
|
|
- Use `TYPE_CHECKING` for circular import avoidance with type hints:
|
|
```python
|
|
from typing import TYPE_CHECKING
|
|
if TYPE_CHECKING:
|
|
from src.core_data import Order
|
|
```
|
|
|
|
### Naming Conventions
|
|
- **Classes**: PascalCase (`BacktestEngine`, `SimpleLimitBuyStrategy`)
|
|
- **Functions/Variables**: snake_case (`get_current_positions`, `send_order`)
|
|
- **Constants**: UPPER_SNAKE_CASE (`BEIJING_TZ`, `TRADING_SESSIONS_TIMES`)
|
|
- **Private members**: Leading underscore (`_indicator_cache`, `_clean_params_for_hashing`)
|
|
|
|
### Type Annotations
|
|
- Use Python's `typing` module for type hints
|
|
- Common patterns:
|
|
```python
|
|
from typing import Dict, Any, Optional, List, Union
|
|
def func(param: Dict[str, Any]) -> Optional[float]:
|
|
```
|
|
- Use string annotations for forward references when needed:
|
|
```python
|
|
def send_order(self, order: "Order") -> Optional[Order]:
|
|
```
|
|
|
|
### Error Handling
|
|
- Use specific exception types, not bare `except:`
|
|
- Log errors with context:
|
|
```python
|
|
try:
|
|
# operation
|
|
except Exception as e:
|
|
self.log(f"Operation failed: {e}")
|
|
```
|
|
- Raise descriptive exceptions:
|
|
```python
|
|
raise ValueError("Step direction inconsistent with range")
|
|
```
|
|
|
|
### Docstrings and Comments
|
|
- Use Chinese for comments and docstrings (project convention)
|
|
- Document public methods with Args/Returns sections:
|
|
```python
|
|
def generate_parameter_range(start, end, step):
|
|
"""
|
|
根据开始、结束和步长生成参数值列表。
|
|
|
|
Args:
|
|
start: 参数范围的起始值
|
|
end: 参数范围的结束值
|
|
step: 参数的步长
|
|
|
|
Returns:
|
|
生成的参数值列表
|
|
"""
|
|
```
|
|
|
|
### Code Formatting
|
|
- No strict formatting rules (no ruff/black config found)
|
|
- Follow Python PEP 8 generally
|
|
- Maximum line length: 120 characters recommended
|
|
- Use 4 spaces for indentation
|
|
|
|
### Project-Specific Patterns
|
|
|
|
#### Strategy Implementation
|
|
All strategies inherit from `Strategy` ABC:
|
|
```python
|
|
from src.strategies.base_strategy import Strategy
|
|
|
|
class MyStrategy(Strategy):
|
|
def on_open_bar(self, open: float, symbol: str):
|
|
# Implement strategy logic
|
|
pass
|
|
```
|
|
|
|
#### Backtest Context
|
|
Strategies interact with `BacktestContext` for:
|
|
- Order management (`send_order`, `cancel_order`)
|
|
- Position tracking (`get_current_positions`)
|
|
- Historical data (`get_price_history`, `get_bar_history`)
|
|
|
|
#### Trading Sessions
|
|
Define trading hours in `src/common_utils.py`:
|
|
```python
|
|
TRADING_SESSIONS_TIMES: List[Tuple[time, time]] = [
|
|
(time(9, 0, 0), time(11, 30, 0)),
|
|
(time(13, 30, 0), time(15, 0, 0)),
|
|
(time(21, 0, 0), time(23, 0, 0))
|
|
]
|
|
```
|
|
|
|
## File Organization
|
|
|
|
```
|
|
NewQuant/
|
|
├── src/ # Core codebase
|
|
│ ├── strategies/ # Strategy implementations
|
|
│ ├── analysis/ # Result analysis tools
|
|
│ ├── indicators/ # Technical indicators
|
|
│ └── *.py # Engine and utility modules
|
|
├── futures_trading_strategies/ # Additional strategies by commodity
|
|
├── strategy_manager/ # Web backend and launcher
|
|
├── test/ # Tests (Jupyter notebooks)
|
|
├── data/ # Data files
|
|
└── *.ipynb # Research notebooks
|
|
```
|
|
|
|
## Key Files for Reference
|
|
|
|
- `src/strategies/base_strategy.py` - Strategy interface definition
|
|
- `src/backtest_engine.py` - Backtesting core
|
|
- `src/common_utils.py` - Utility functions and constants
|
|
- `strategy_manager/start.py` - Web service entry point
|