docs: 添加DataFrame vs Pydantic最佳实践与技术债务文档
- data_layer_design.md新增章节: * DataFrame vs Pydantic最佳实践 * 推荐做法:存储/缓存/计算全程DataFrame * 避免做法:频繁转换、混合使用 * 当前架构评估:数据层全程DataFrame * 架构边界图:清晰展示各层职责 - 创建technical_debt.md: * TD-001: 配置类改用Pydantic(中优先级) * TD-002: ValidationResult改用Pydantic(低优先级) * TD-003: DataFrame使用Pandera验证(低优先级) * TD-004: 业务对象使用Pydantic(Phase3需求) * TD-005: Redis分布式缓存(扩展性需求) * TD-006: 性能监控(生产需求) * 决策记录:暂不实施配置类Pydantic化 * 实施优先级矩阵 决策:当前架构已优秀,数据层全程DataFrame符合最佳实践,配置类等改进记录为技术债务,按需实施
This commit is contained in:
parent
9d2a3247bb
commit
357e25bdc3
@ -1046,6 +1046,269 @@ def test_data_service():
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## DataFrame vs Pydantic 最佳实践
|
||||||
|
|
||||||
|
### 设计原则
|
||||||
|
|
||||||
|
在数据密集型的量化交易系统中,合理使用 DataFrame 和 Pydantic 模型对性能和代码质量至关重要。
|
||||||
|
|
||||||
|
### ✅ 推荐做法
|
||||||
|
|
||||||
|
#### 1. 存储层返回 DataFrame
|
||||||
|
|
||||||
|
```python
|
||||||
|
# ✅ 正确:存储层直接返回 DataFrame
|
||||||
|
class MySQLStorage(StorageLayer):
|
||||||
|
def load_klines(self, symbol, period, ...) -> Optional[pd.DataFrame]:
|
||||||
|
df = pd.read_sql(query, engine)
|
||||||
|
return df # 直接返回 DataFrame,不转换
|
||||||
|
```
|
||||||
|
|
||||||
|
**优势:**
|
||||||
|
- 原始数据用 DataFrame(性能好)
|
||||||
|
- 避免中间转换开销
|
||||||
|
- 支持大批量数据处理
|
||||||
|
|
||||||
|
#### 2. 计算层全程 DataFrame
|
||||||
|
|
||||||
|
```python
|
||||||
|
# ✅ 正确:指标计算全程 DataFrame
|
||||||
|
class IndicatorManager:
|
||||||
|
def calculate_macd(self, klines: pd.DataFrame) -> pd.DataFrame:
|
||||||
|
# 输入 DataFrame
|
||||||
|
result = talib.MACD(klines['close'], ...)
|
||||||
|
# 输出 DataFrame
|
||||||
|
return pd.DataFrame({'macd_dif': ..., 'macd_dea': ...})
|
||||||
|
```
|
||||||
|
|
||||||
|
**优势:**
|
||||||
|
- 指标计算、因子计算、回测全程 DataFrame
|
||||||
|
- 不要频繁转换(性能杀手)
|
||||||
|
- 利用 pandas 向量化计算
|
||||||
|
|
||||||
|
#### 3. 缓存层全程 DataFrame
|
||||||
|
|
||||||
|
```python
|
||||||
|
# ✅ 正确:缓存直接存储 DataFrame
|
||||||
|
class CacheManager:
|
||||||
|
def __init__(self):
|
||||||
|
self._cache = {
|
||||||
|
"symbol_period": {
|
||||||
|
"klines": pd.DataFrame, # ← DataFrame
|
||||||
|
"macd": pd.DataFrame, # ← DataFrame
|
||||||
|
"meta": {...} # ← 元数据用 dict(可接受)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**优势:**
|
||||||
|
- 内存缓存高效
|
||||||
|
- 无序列化开销
|
||||||
|
- 快速切片和过滤
|
||||||
|
|
||||||
|
#### 4. API 边界用 Pydantic
|
||||||
|
|
||||||
|
```python
|
||||||
|
# ✅ 正确:API 层使用 Pydantic
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
class KlineRequest(BaseModel):
|
||||||
|
symbol: str
|
||||||
|
period: str
|
||||||
|
start_date: datetime
|
||||||
|
end_date: datetime
|
||||||
|
|
||||||
|
@app.post("/klines")
|
||||||
|
def get_klines(req: KlineRequest) -> KlineResponse:
|
||||||
|
# 1. Pydantic 输入验证
|
||||||
|
# 2. 调用 DataService(返回 DataFrame)
|
||||||
|
df = service.get_klines(req.symbol, req.period, ...)
|
||||||
|
# 3. DataFrame → Pydantic 输出序列化
|
||||||
|
return KlineResponse(data=df.to_dict('records'))
|
||||||
|
```
|
||||||
|
|
||||||
|
**优势:**
|
||||||
|
- 输入验证(类型、范围、格式)
|
||||||
|
- 输出序列化(JSON)
|
||||||
|
- 自动文档生成(Swagger)
|
||||||
|
|
||||||
|
#### 5. 业务对象用 Pydantic
|
||||||
|
|
||||||
|
```python
|
||||||
|
# ✅ 正确:业务对象使用 Pydantic
|
||||||
|
class Order(BaseModel):
|
||||||
|
order_id: str
|
||||||
|
symbol: str
|
||||||
|
price: Decimal
|
||||||
|
quantity: int
|
||||||
|
side: Literal["buy", "sell"]
|
||||||
|
status: OrderStatus
|
||||||
|
created_at: datetime
|
||||||
|
|
||||||
|
class Position(BaseModel):
|
||||||
|
symbol: str
|
||||||
|
quantity: int
|
||||||
|
avg_cost: Decimal
|
||||||
|
current_price: Decimal
|
||||||
|
|
||||||
|
@property
|
||||||
|
def market_value(self) -> Decimal:
|
||||||
|
return self.quantity * self.current_price
|
||||||
|
|
||||||
|
class BacktestConfig(BaseModel):
|
||||||
|
start_date: datetime
|
||||||
|
end_date: datetime
|
||||||
|
initial_capital: Decimal
|
||||||
|
symbols: List[str]
|
||||||
|
```
|
||||||
|
|
||||||
|
**优势:**
|
||||||
|
- 类型安全
|
||||||
|
- 业务逻辑封装
|
||||||
|
- 配置验证
|
||||||
|
|
||||||
|
### ❌ 避免做法
|
||||||
|
|
||||||
|
#### 1. 频繁转换(性能杀手)
|
||||||
|
|
||||||
|
```python
|
||||||
|
# ❌ 错误:频繁转换
|
||||||
|
def process_data(symbol):
|
||||||
|
df = storage.load_klines(symbol)
|
||||||
|
# 转换 1
|
||||||
|
data_dict = df.to_dict('records')
|
||||||
|
# 转换 2
|
||||||
|
pydantic_list = [KlineModel(**row) for row in data_dict]
|
||||||
|
# 转换 3
|
||||||
|
df_again = pd.DataFrame([m.dict() for m in pydantic_list])
|
||||||
|
# 计算指标
|
||||||
|
result = calculate_indicator(df_again)
|
||||||
|
return result
|
||||||
|
```
|
||||||
|
|
||||||
|
**问题:**
|
||||||
|
- 3次无意义的转换
|
||||||
|
- 性能开销巨大(O(n)×3)
|
||||||
|
- 内存占用翻倍
|
||||||
|
|
||||||
|
#### 2. 用 Pydantic List 做大批量计算
|
||||||
|
|
||||||
|
```python
|
||||||
|
# ❌ 错误:用 Pydantic 做计算
|
||||||
|
klines = [KlineModel(...) for _ in range(10000)]
|
||||||
|
for k in klines:
|
||||||
|
k.sma = calculate_sma(...) # 逐个计算,慢!
|
||||||
|
```
|
||||||
|
|
||||||
|
**问题:**
|
||||||
|
- Python for 循环慢
|
||||||
|
- 无法利用向量化计算
|
||||||
|
- 内存开销大
|
||||||
|
|
||||||
|
#### 3. DataFrame 传递业务对象(类型不安全)
|
||||||
|
|
||||||
|
```python
|
||||||
|
# ❌ 错误:DataFrame 存储业务对象
|
||||||
|
orders_df = pd.DataFrame({
|
||||||
|
'order': [Order(...), Order(...)] # 对象存在 DataFrame 中
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
**问题:**
|
||||||
|
- 类型不安全
|
||||||
|
- 无法利用 pandas 计算
|
||||||
|
- 序列化困难
|
||||||
|
|
||||||
|
#### 4. 混合使用导致边界不清
|
||||||
|
|
||||||
|
```python
|
||||||
|
# ❌ 错误:边界不清
|
||||||
|
def confusing_function(data):
|
||||||
|
# data 是什么?DataFrame?List[Model]?
|
||||||
|
if isinstance(data, pd.DataFrame):
|
||||||
|
...
|
||||||
|
elif isinstance(data, list):
|
||||||
|
...
|
||||||
|
# 混乱!
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🎯 当前架构评估
|
||||||
|
|
||||||
|
| 层次 | 当前实现 | 是否符合最佳实践 | 说明 |
|
||||||
|
| ------------- | ----------- | ---------------- | ------------------------------ |
|
||||||
|
| **Storage** | DataFrame ✅ | ✅ 完全符合 | `load_klines()` 返回 DataFrame |
|
||||||
|
| **Cache** | DataFrame ✅ | ✅ 完全符合 | 内存中直接存储 DataFrame |
|
||||||
|
| **Service** | DataFrame ✅ | ✅ 完全符合 | `get_klines()` 返回 DataFrame |
|
||||||
|
| **Indicator** | DataFrame ✅ | ✅ 完全符合 | 输入输出都是 DataFrame |
|
||||||
|
| **Validator** | DataFrame ✅ | ✅ 完全符合 | 验证 DataFrame 数据 |
|
||||||
|
| **配置** | dict | ⚠️ 可改进 | 建议改用 Pydantic(技术债务) |
|
||||||
|
| **验证结果** | 简单类 | ⚠️ 看场景 | 如果暴露 API 则改用 Pydantic |
|
||||||
|
|
||||||
|
### 📊 架构边界图
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────┐
|
||||||
|
│ API Layer (FastAPI) - 未来 │
|
||||||
|
│ ┌─────────────────────────────────────┐ │
|
||||||
|
│ │ Pydantic: 输入验证 + 输出序列化 │ │
|
||||||
|
│ └─────────────────────────────────────┘ │
|
||||||
|
└─────────────────────────────────────────────┘
|
||||||
|
↓ Pydantic → DataFrame
|
||||||
|
┌─────────────────────────────────────────────┐
|
||||||
|
│ Service Layer - 当前 ✅ │
|
||||||
|
│ ┌─────────────────────────────────────┐ │
|
||||||
|
│ │ DataFrame: get_klines(), get_indicator()│
|
||||||
|
│ └─────────────────────────────────────┘ │
|
||||||
|
└─────────────────────────────────────────────┘
|
||||||
|
↓ DataFrame
|
||||||
|
┌─────────────────────────────────────────────┐
|
||||||
|
│ Cache Layer - 当前 ✅ │
|
||||||
|
│ ┌─────────────────────────────────────┐ │
|
||||||
|
│ │ DataFrame: 内存缓存 │ │
|
||||||
|
│ └─────────────────────────────────────┘ │
|
||||||
|
└─────────────────────────────────────────────┘
|
||||||
|
↓ DataFrame
|
||||||
|
┌─────────────────────────────────────────────┐
|
||||||
|
│ Storage Layer - 当前 ✅ │
|
||||||
|
│ ┌─────────────────────────────────────┐ │
|
||||||
|
│ │ DataFrame: load/save │ │
|
||||||
|
│ └─────────────────────────────────────┘ │
|
||||||
|
└─────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 🎨 业务对象边界(未来)
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────┐
|
||||||
|
│ 业务对象 (Pydantic) │
|
||||||
|
│ ┌─────────────────────────────────────┐ │
|
||||||
|
│ │ Order, Position, Trade │ │
|
||||||
|
│ │ Strategy, Signal, Portfolio │ │
|
||||||
|
│ └─────────────────────────────────────┘ │
|
||||||
|
└─────────────────────────────────────────────┘
|
||||||
|
↓ 转换
|
||||||
|
┌─────────────────────────────────────────────┐
|
||||||
|
│ 数据流 (DataFrame) │
|
||||||
|
│ ┌─────────────────────────────────────┐ │
|
||||||
|
│ │ 持仓历史, 订单流水, 资金曲线 │ │
|
||||||
|
│ └─────────────────────────────────────┘ │
|
||||||
|
└─────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 结论
|
||||||
|
|
||||||
|
**当前架构状态:** ✅ **优秀**
|
||||||
|
|
||||||
|
- ✅ 数据层(Storage/Cache/Service)完全正确,全程 DataFrame
|
||||||
|
- ✅ 计算层(Indicator)全程 DataFrame
|
||||||
|
- ✅ 没有频繁转换的性能问题
|
||||||
|
- ✅ 边界清晰,职责明确
|
||||||
|
|
||||||
|
**改进建议:** 记录在技术债务文档,非紧急
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 总结
|
## 总结
|
||||||
|
|
||||||
### 核心优势
|
### 核心优势
|
||||||
|
|||||||
486
docs/technical_debt.md
Normal file
486
docs/technical_debt.md
Normal file
@ -0,0 +1,486 @@
|
|||||||
|
# 技术债务文档
|
||||||
|
|
||||||
|
> 记录当前架构中可以改进但非紧急的技术债务
|
||||||
|
> 版本:v1.0
|
||||||
|
> 日期:2025-12-20
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
本文档记录 QTrade 系统中已识别但暂未实现的技术改进项。这些改进项:
|
||||||
|
- ✅ 已被充分讨论和设计
|
||||||
|
- ⚠️ 当前架构可用,但有改进空间
|
||||||
|
- 📋 需要在合适的时机实施
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 债务分类
|
||||||
|
|
||||||
|
### 🔴 高优先级(影响性能或安全性)
|
||||||
|
需要在 Phase 3 前解决
|
||||||
|
|
||||||
|
### 🟡 中优先级(影响代码质量或可维护性)
|
||||||
|
可在 Phase 3 或 Phase 4 解决
|
||||||
|
|
||||||
|
### 🟢 低优先级(锦上添花)
|
||||||
|
可持续关注,按需实施
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 债务清单
|
||||||
|
|
||||||
|
### 🟡 TD-001: 配置类改用 Pydantic
|
||||||
|
|
||||||
|
**当前状态:** 使用 dict 管理配置
|
||||||
|
```python
|
||||||
|
# 当前实现
|
||||||
|
config = {
|
||||||
|
"cache": {
|
||||||
|
"enabled": True,
|
||||||
|
"mode": "static",
|
||||||
|
"max_memory_mb": 1024,
|
||||||
|
"auto_load": True,
|
||||||
|
"preload": {
|
||||||
|
"enabled": True,
|
||||||
|
"time_range": "1M",
|
||||||
|
"periods": ["1m", "1d"]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"database": {
|
||||||
|
"host": "localhost",
|
||||||
|
...
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**建议改进:** 使用 Pydantic 模型
|
||||||
|
```python
|
||||||
|
# 建议实现
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
from typing import Literal, List
|
||||||
|
|
||||||
|
class PreloadConfig(BaseModel):
|
||||||
|
enabled: bool = True
|
||||||
|
time_range: str = Field(default="1M", pattern=r"^\d+[MYD]$")
|
||||||
|
periods: List[str] = ["1m", "1d"]
|
||||||
|
|
||||||
|
class CacheConfig(BaseModel):
|
||||||
|
enabled: bool = True
|
||||||
|
mode: Literal["static", "dynamic"] = "static"
|
||||||
|
max_memory_mb: int = Field(default=1024, gt=0)
|
||||||
|
auto_load: bool = True
|
||||||
|
preload: PreloadConfig = PreloadConfig()
|
||||||
|
|
||||||
|
class DatabaseConfig(BaseModel):
|
||||||
|
host: str
|
||||||
|
port: int = Field(default=3306, gt=0, le=65535)
|
||||||
|
database: str
|
||||||
|
user: str
|
||||||
|
password: str
|
||||||
|
|
||||||
|
class Config(BaseModel):
|
||||||
|
cache: CacheConfig = CacheConfig()
|
||||||
|
database: DatabaseConfig
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
# 支持从环境变量读取
|
||||||
|
env_prefix = "QTRADE_"
|
||||||
|
```
|
||||||
|
|
||||||
|
**优势:**
|
||||||
|
- ✅ 类型安全(IDE 自动补全)
|
||||||
|
- ✅ 配置验证(启动时发现错误)
|
||||||
|
- ✅ 默认值管理(集中管理)
|
||||||
|
- ✅ 文档自动生成(配置说明)
|
||||||
|
- ✅ 环境变量支持(部署灵活)
|
||||||
|
|
||||||
|
**成本估算:**
|
||||||
|
- 工作量:2-3 小时
|
||||||
|
- 影响范围:需要更新所有读取配置的代码
|
||||||
|
- 风险:低(纯重构,不改变逻辑)
|
||||||
|
|
||||||
|
**实施建议:**
|
||||||
|
- **时机:** Phase 2.5 或 Phase 3 初期
|
||||||
|
- **前置条件:** 无
|
||||||
|
- **阻塞问题:** 无
|
||||||
|
|
||||||
|
**参考资料:**
|
||||||
|
- Pydantic 文档:https://docs.pydantic.dev/
|
||||||
|
- Settings Management:https://docs.pydantic.dev/latest/concepts/pydantic_settings/
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 🟢 TD-002: ValidationResult 改用 Pydantic
|
||||||
|
|
||||||
|
**当前状态:** 使用简单的 Python 类
|
||||||
|
```python
|
||||||
|
class ValidationResult:
|
||||||
|
def __init__(self, passed: bool, details: Dict[str, Any]):
|
||||||
|
self.passed = passed
|
||||||
|
self.details = details
|
||||||
|
```
|
||||||
|
|
||||||
|
**建议改进:** 使用 Pydantic 模型
|
||||||
|
```python
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
from typing import Dict, Any, List
|
||||||
|
|
||||||
|
class ValidationResult(BaseModel):
|
||||||
|
passed: bool
|
||||||
|
details: Dict[str, Any]
|
||||||
|
issues: List[str] = Field(default_factory=list)
|
||||||
|
total_records: int = 0
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
# 允许额外字段(向后兼容)
|
||||||
|
extra = "allow"
|
||||||
|
```
|
||||||
|
|
||||||
|
**优势:**
|
||||||
|
- ✅ 类型安全
|
||||||
|
- ✅ 序列化支持(JSON)
|
||||||
|
- ✅ 如果未来提供 API,可直接使用
|
||||||
|
|
||||||
|
**成本估算:**
|
||||||
|
- 工作量:1 小时
|
||||||
|
- 影响范围:小(只在验证器内部使用)
|
||||||
|
- 风险:低
|
||||||
|
|
||||||
|
**实施建议:**
|
||||||
|
- **时机:** 如果需要暴露验证 API 时实施
|
||||||
|
- **前置条件:** 无
|
||||||
|
- **阻塞问题:** 无
|
||||||
|
- **备注:** 当前实现已经足够,非必要改动
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 🟢 TD-003: 关键 DataFrame 使用 Pandera 验证
|
||||||
|
|
||||||
|
**当前状态:** DataFrame 没有 schema 验证
|
||||||
|
```python
|
||||||
|
# 当前实现
|
||||||
|
def process_klines(df: pd.DataFrame) -> pd.DataFrame:
|
||||||
|
# 假设 df 包含正确的列,但没有验证
|
||||||
|
result = df['close'].rolling(20).mean()
|
||||||
|
return result
|
||||||
|
```
|
||||||
|
|
||||||
|
**建议改进:** 使用 Pandera 定义 Schema
|
||||||
|
```python
|
||||||
|
import pandera as pa
|
||||||
|
from pandera.typing import DataFrame
|
||||||
|
|
||||||
|
# 定义 K线 Schema
|
||||||
|
class KlineSchema(pa.DataFrameModel):
|
||||||
|
timestamp: pa.typing.Index[pd.DatetimeIndex]
|
||||||
|
open: float = pa.Field(ge=0, nullable=False)
|
||||||
|
high: float = pa.Field(ge=0, nullable=False)
|
||||||
|
low: float = pa.Field(ge=0, nullable=False)
|
||||||
|
close: float = pa.Field(ge=0, nullable=False)
|
||||||
|
volume: float = pa.Field(ge=0, nullable=False)
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
strict = True # 不允许额外列
|
||||||
|
coerce = True # 自动类型转换
|
||||||
|
|
||||||
|
# 使用装饰器验证
|
||||||
|
@pa.check_types
|
||||||
|
def process_klines(df: DataFrame[KlineSchema]) -> pd.DataFrame:
|
||||||
|
# 如果 df 不符合 schema,抛出异常
|
||||||
|
result = df['close'].rolling(20).mean()
|
||||||
|
return result
|
||||||
|
```
|
||||||
|
|
||||||
|
**优势:**
|
||||||
|
- ✅ 防止列名拼写错误(编译时检查)
|
||||||
|
- ✅ 类型检查(IDE 支持)
|
||||||
|
- ✅ 数据验证(运行时检查)
|
||||||
|
- ✅ 文档化(Schema 即文档)
|
||||||
|
|
||||||
|
**劣势:**
|
||||||
|
- ❌ 增加依赖(pandera)
|
||||||
|
- ❌ 轻微性能开销(验证耗时)
|
||||||
|
- ❌ 学习成本
|
||||||
|
|
||||||
|
**成本估算:**
|
||||||
|
- 工作量:4-8 小时(定义所有 Schema)
|
||||||
|
- 影响范围:中等(核心数据流)
|
||||||
|
- 风险:中(可能发现隐藏的数据问题)
|
||||||
|
|
||||||
|
**实施建议:**
|
||||||
|
- **时机:** Phase 3 或 Phase 4
|
||||||
|
- **前置条件:** 系统稳定运行一段时间
|
||||||
|
- **阻塞问题:** 无
|
||||||
|
- **备注:** 可选功能,根据实际需求决定
|
||||||
|
|
||||||
|
**参考资料:**
|
||||||
|
- Pandera 文档:https://pandera.readthedocs.io/
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 🟢 TD-004: 业务对象使用 Pydantic(未来需求)
|
||||||
|
|
||||||
|
**当前状态:** 暂无业务对象定义
|
||||||
|
|
||||||
|
**未来需求:** 回测和实盘需要定义业务对象
|
||||||
|
|
||||||
|
**建议设计:**
|
||||||
|
```python
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
from decimal import Decimal
|
||||||
|
from datetime import datetime
|
||||||
|
from typing import Literal
|
||||||
|
from enum import Enum
|
||||||
|
|
||||||
|
class OrderStatus(str, Enum):
|
||||||
|
PENDING = "pending"
|
||||||
|
FILLED = "filled"
|
||||||
|
CANCELLED = "cancelled"
|
||||||
|
REJECTED = "rejected"
|
||||||
|
|
||||||
|
class OrderSide(str, Enum):
|
||||||
|
BUY = "buy"
|
||||||
|
SELL = "sell"
|
||||||
|
|
||||||
|
class Order(BaseModel):
|
||||||
|
"""订单对象"""
|
||||||
|
order_id: str
|
||||||
|
symbol: str
|
||||||
|
side: OrderSide
|
||||||
|
price: Decimal = Field(gt=0)
|
||||||
|
quantity: int = Field(gt=0)
|
||||||
|
status: OrderStatus = OrderStatus.PENDING
|
||||||
|
created_at: datetime = Field(default_factory=datetime.now)
|
||||||
|
filled_at: datetime | None = None
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
use_enum_values = True # 序列化时使用枚举值
|
||||||
|
|
||||||
|
class Position(BaseModel):
|
||||||
|
"""持仓对象"""
|
||||||
|
symbol: str
|
||||||
|
quantity: int
|
||||||
|
avg_cost: Decimal = Field(gt=0)
|
||||||
|
current_price: Decimal = Field(gt=0)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def market_value(self) -> Decimal:
|
||||||
|
"""市值"""
|
||||||
|
return self.quantity * self.current_price
|
||||||
|
|
||||||
|
@property
|
||||||
|
def profit_loss(self) -> Decimal:
|
||||||
|
"""浮盈浮亏"""
|
||||||
|
return (self.current_price - self.avg_cost) * self.quantity
|
||||||
|
|
||||||
|
@property
|
||||||
|
def profit_loss_pct(self) -> Decimal:
|
||||||
|
"""收益率"""
|
||||||
|
return (self.current_price - self.avg_cost) / self.avg_cost
|
||||||
|
|
||||||
|
class Trade(BaseModel):
|
||||||
|
"""成交对象"""
|
||||||
|
trade_id: str
|
||||||
|
order_id: str
|
||||||
|
symbol: str
|
||||||
|
side: OrderSide
|
||||||
|
price: Decimal
|
||||||
|
quantity: int
|
||||||
|
commission: Decimal = Field(default=Decimal("0"))
|
||||||
|
executed_at: datetime
|
||||||
|
|
||||||
|
class Portfolio(BaseModel):
|
||||||
|
"""投资组合"""
|
||||||
|
account_id: str
|
||||||
|
cash: Decimal = Field(ge=0)
|
||||||
|
positions: List[Position] = Field(default_factory=list)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def total_value(self) -> Decimal:
|
||||||
|
"""总资产"""
|
||||||
|
position_value = sum(p.market_value for p in self.positions)
|
||||||
|
return self.cash + position_value
|
||||||
|
|
||||||
|
@property
|
||||||
|
def total_profit_loss(self) -> Decimal:
|
||||||
|
"""总盈亏"""
|
||||||
|
return sum(p.profit_loss for p in self.positions)
|
||||||
|
```
|
||||||
|
|
||||||
|
**优势:**
|
||||||
|
- ✅ 类型安全
|
||||||
|
- ✅ 业务逻辑封装(@property)
|
||||||
|
- ✅ 验证规则(price > 0)
|
||||||
|
- ✅ 序列化支持(API、持久化)
|
||||||
|
|
||||||
|
**实施建议:**
|
||||||
|
- **时机:** Phase 3 回测模块开发时
|
||||||
|
- **前置条件:** 数据层稳定
|
||||||
|
- **阻塞问题:** 无
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 🟢 TD-005: Redis 分布式缓存(扩展性需求)
|
||||||
|
|
||||||
|
**当前状态:** 单机内存缓存
|
||||||
|
|
||||||
|
**未来需求:** 多进程/多机器共享缓存
|
||||||
|
|
||||||
|
**建议设计:**
|
||||||
|
```python
|
||||||
|
from redis import Redis
|
||||||
|
import pickle
|
||||||
|
|
||||||
|
class RedisCacheManager(CacheManager):
|
||||||
|
"""Redis 缓存管理器"""
|
||||||
|
|
||||||
|
def __init__(self, redis_client: Redis, ...):
|
||||||
|
self.redis = redis_client
|
||||||
|
super().__init__(...)
|
||||||
|
|
||||||
|
def get(self, symbol, period, ...):
|
||||||
|
key = self._make_key(symbol, period)
|
||||||
|
|
||||||
|
# 从 Redis 获取
|
||||||
|
data = self.redis.get(key)
|
||||||
|
if data:
|
||||||
|
df = pickle.loads(data) # 反序列化
|
||||||
|
return self._slice_data(df, start, end)
|
||||||
|
|
||||||
|
# 缓存未命中,加载并缓存
|
||||||
|
df = self.storage.load_klines(...)
|
||||||
|
if df is not None:
|
||||||
|
self.redis.set(key, pickle.dumps(df), ex=3600) # 1小时过期
|
||||||
|
|
||||||
|
return df
|
||||||
|
```
|
||||||
|
|
||||||
|
**优势:**
|
||||||
|
- ✅ 多进程共享缓存
|
||||||
|
- ✅ 持久化(重启不丢失)
|
||||||
|
- ✅ 分布式部署
|
||||||
|
|
||||||
|
**劣势:**
|
||||||
|
- ❌ 网络开销
|
||||||
|
- ❌ 序列化开销
|
||||||
|
- ❌ 运维复杂度
|
||||||
|
|
||||||
|
**实施建议:**
|
||||||
|
- **时机:** 当单机缓存不够用时
|
||||||
|
- **前置条件:** 有分布式部署需求
|
||||||
|
- **阻塞问题:** 需要 Redis 基础设施
|
||||||
|
- **备注:** 当前单机内存缓存足够
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 🟢 TD-006: 性能监控和 Profiling
|
||||||
|
|
||||||
|
**当前状态:** 基础日志
|
||||||
|
|
||||||
|
**建议改进:** 添加性能监控
|
||||||
|
```python
|
||||||
|
import time
|
||||||
|
from functools import wraps
|
||||||
|
|
||||||
|
def profile_time(func):
|
||||||
|
"""性能分析装饰器"""
|
||||||
|
@wraps(func)
|
||||||
|
def wrapper(*args, **kwargs):
|
||||||
|
start = time.time()
|
||||||
|
result = func(*args, **kwargs)
|
||||||
|
elapsed = time.time() - start
|
||||||
|
|
||||||
|
# 记录到监控系统
|
||||||
|
logger.info(f"{func.__name__} took {elapsed:.3f}s")
|
||||||
|
metrics.record(f"function.{func.__name__}.duration", elapsed)
|
||||||
|
|
||||||
|
return result
|
||||||
|
return wrapper
|
||||||
|
|
||||||
|
# 使用
|
||||||
|
@profile_time
|
||||||
|
def get_klines(self, symbol, period, ...):
|
||||||
|
...
|
||||||
|
```
|
||||||
|
|
||||||
|
**优势:**
|
||||||
|
- ✅ 发现性能瓶颈
|
||||||
|
- ✅ 监控系统健康度
|
||||||
|
- ✅ 性能回归检测
|
||||||
|
|
||||||
|
**实施建议:**
|
||||||
|
- **时机:** Phase 3 或生产部署前
|
||||||
|
- **前置条件:** 无
|
||||||
|
- **阻塞问题:** 需要选择监控方案(Prometheus、Grafana)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 实施优先级矩阵
|
||||||
|
|
||||||
|
| 债务编号 | 描述 | 优先级 | 工作量 | 价值 | 建议时机 |
|
||||||
|
| -------- | ------------------------------ | ------ | ------ | ---- | ----------- |
|
||||||
|
| TD-001 | 配置类改用 Pydantic | 🟡 中 | 2-3h | 高 | Phase 2.5/3 |
|
||||||
|
| TD-002 | ValidationResult 改用 Pydantic | 🟢 低 | 1h | 中 | 按需 |
|
||||||
|
| TD-003 | DataFrame 使用 Pandera | 🟢 低 | 4-8h | 中 | Phase 3/4 |
|
||||||
|
| TD-004 | 业务对象使用 Pydantic | 🟢 低 | 4-6h | 高 | Phase 3 |
|
||||||
|
| TD-005 | Redis 分布式缓存 | 🟢 低 | 8-16h | 中 | 按需 |
|
||||||
|
| TD-006 | 性能监控 | 🟢 低 | 4-8h | 高 | Phase 3 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 决策记录
|
||||||
|
|
||||||
|
### DR-001: 暂不实施配置类 Pydantic 化
|
||||||
|
|
||||||
|
**日期:** 2025-12-20
|
||||||
|
**决策:** 暂不改用 Pydantic,保持当前 dict 实现
|
||||||
|
**理由:**
|
||||||
|
1. 当前 dict 实现可用,没有阻塞性问题
|
||||||
|
2. Phase 2 重点是数据层稳定性,不引入新依赖
|
||||||
|
3. 可在 Phase 2.5 或 Phase 3 统一改进
|
||||||
|
|
||||||
|
**后续行动:**
|
||||||
|
- 记录在技术债务文档
|
||||||
|
- 在 Phase 3 规划中考虑
|
||||||
|
- 如果新增复杂配置项,重新评估
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### DR-002: 数据层全程使用 DataFrame
|
||||||
|
|
||||||
|
**日期:** 2025-12-20
|
||||||
|
**决策:** 数据层(Storage/Cache/Service/Indicator)全程使用 DataFrame
|
||||||
|
**理由:**
|
||||||
|
1. 符合最佳实践(避免频繁转换)
|
||||||
|
2. 性能最优(向量化计算)
|
||||||
|
3. 边界清晰(API 层才用 Pydantic)
|
||||||
|
|
||||||
|
**设计原则:**
|
||||||
|
```
|
||||||
|
数据流 (DataFrame) ← 存储/缓存/计算
|
||||||
|
↕ 转换边界(仅在 API 层)
|
||||||
|
业务对象 (Pydantic) ← API/配置/业务逻辑
|
||||||
|
```
|
||||||
|
|
||||||
|
**后续行动:**
|
||||||
|
- 保持当前架构不变
|
||||||
|
- 文档化最佳实践
|
||||||
|
- 未来 API 层使用 Pydantic
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 回顾计划
|
||||||
|
|
||||||
|
- **每季度回顾:** 评估债务的紧急程度
|
||||||
|
- **版本规划:** 在每个 Phase 规划时考虑技术债务
|
||||||
|
- **持续更新:** 发现新债务时及时记录
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 参考资料
|
||||||
|
|
||||||
|
- [数据层架构设计文档](./tech_designs/data_layer_design.md)
|
||||||
|
- [缓存机制设计文档](./tech_designs/cache_design.md)
|
||||||
|
- [Pydantic 官方文档](https://docs.pydantic.dev/)
|
||||||
|
- [Pandera 官方文档](https://pandera.readthedocs.io/)
|
||||||
Loading…
Reference in New Issue
Block a user