QTrade/src/core/strategy_context.py
cuizhan 0f23037448 重构架构:实现单一职责原则和最小接口设计
主要修改:
1. CacheManager 负责数据库降级(单一职责)
   - 缓存未命中自动从数据库加载
   - 移除 StrategyManager/Context 的 db_manager 依赖

2. 添加 StrategyContext 核心组件
   - Position: 持仓管理
   - Capital: 资金管理
   - RiskState: 风险控制
   - BaseStrategy: 策略基类

3. 配置与类型修复
   - global.yaml 添加完整缓存配置
   - 修复 Pylance 类型推断错误
   - Config.load_with_global() 合并全局配置

4. 技术设计文档
   - 架构重构总结
   - 缓存设计方案
   - Context 共享策略
   - 接口最小化原则
2025-12-27 22:52:40 +08:00

317 lines
9.3 KiB
Python
Raw 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.

"""
策略上下文 (StrategyContext)
策略运行的上下文环境,提供数据访问和状态管理
设计原则:
1. Context 是策略访问所有资源的唯一入口
2. 直接持有共享资源(cache_manager、db_manager)
3. 对外提供高层接口,隐藏实现细节
4. 每个策略实例有独立的 Context
"""
from typing import Optional
import pandas as pd
import logging
from src.core.position import Position
from src.core.capital import Capital
from src.core.risk_state import RiskState
logger = logging.getLogger(__name__)
class StrategyContext:
"""
策略上下文(直接提供所有方法)
共享资源:通过传入同一个实例实现共享
独立状态:每个Context有自己的Position、Capital、RiskState
"""
def __init__(
self,
cache_manager,
instance_id: str,
symbol: str,
instance_config: dict,
):
"""
初始化策略上下文
Args:
cache_manager: 缓存管理器(共享实例)
instance_id: 策略实例ID
symbol: 交易标的
instance_config: 实例配置
"""
# ==================== 共享资源(私有) ====================
# 注意:这是传入的共享实例,不是新创建的
self._cache_manager = cache_manager
# ==================== 实例信息 ====================
self.instance_id = instance_id
self.symbol = symbol
self.config = instance_config
# ==================== 独立状态 ====================
self._position = Position(
symbol=symbol,
shares=instance_config.get("initial_shares", 0),
cost=instance_config.get("initial_cost", 0.0),
)
self._capital = Capital(
initial_cash=instance_config.get("initial_capital", 1000000.0)
)
self._risk_state = RiskState(
max_position_ratio=instance_config.get("max_position_ratio", 0.5),
stop_loss_ratio=instance_config.get("stop_loss_ratio", 0.05),
stop_profit_ratio=instance_config.get("stop_profit_ratio", 0.20),
max_single_loss=instance_config.get("max_single_loss", 10000.0),
)
logger.info(
f"StrategyContext initialized: instance_id={instance_id}, "
f"symbol={symbol}, capital={self._capital.initial_cash:.2f}"
)
# ==================== 数据访问接口(直接实现) ====================
def get_klines(
self,
symbol: Optional[str] = None,
period: str = "1m",
last_n: Optional[int] = None,
start: Optional[pd.Timestamp] = None,
end: Optional[pd.Timestamp] = None,
) -> Optional[pd.DataFrame]:
"""
获取K线数据(直接从缓存获取)
这是策略访问数据的主要方式
Args:
symbol: 标的代码,默认使用实例的 symbol
period: 周期
last_n: 最近N条
start: 开始时间
end: 结束时间
Returns:
K线DataFrame,如果不存在返回None
"""
target_symbol = symbol or self.symbol
# 1. 从缓存读取
try:
data = self._cache_manager.get_klines(target_symbol, period)
if data is None:
logger.debug(
f"[{self.instance_id}] No cache data for {target_symbol}_{period}"
)
return self._handle_cache_miss(
target_symbol, period, last_n, start, end
)
df = data.get("klines")
if df is None or df.empty:
logger.debug(
f"[{self.instance_id}] Empty cache for {target_symbol}_{period}"
)
return self._handle_cache_miss(
target_symbol, period, last_n, start, end
)
# 2. 根据参数过滤数据
result = self._filter_klines(df, last_n, start, end)
if result is not None and not result.empty:
return result
else:
logger.warning(
f"[{self.instance_id}] Filtered result is empty for {target_symbol}_{period}"
)
return None
except Exception as e:
logger.error(
f"[{self.instance_id}] Error getting klines: {e}", exc_info=True
)
return None
def _filter_klines(
self,
df: pd.DataFrame,
last_n: Optional[int] = None,
start: Optional[pd.Timestamp] = None,
end: Optional[pd.Timestamp] = None,
) -> Optional[pd.DataFrame]:
"""
过滤K线数据
Args:
df: 原始DataFrame
last_n: 最近N条
start: 开始时间
end: 结束时间
Returns:
过滤后的DataFrame
"""
result = df.copy()
# 时间范围过滤
if "timestamp" in result.columns:
if start is not None:
result = result[result["timestamp"] >= start]
if end is not None:
result = result[result["timestamp"] <= end]
# 最近N条
if last_n is not None and last_n > 0:
result = result.tail(last_n)
return result
def _handle_cache_miss(
self,
symbol: str,
period: str,
last_n: Optional[int],
start: Optional[pd.Timestamp],
end: Optional[pd.Timestamp],
) -> Optional[pd.DataFrame]:
"""
处理缓存未命中
Args:
symbol: 标的代码
period: 周期
last_n: 最近N条
start: 开始时间
end: 结束时间
Returns:
None(缓存未命中直接返回None,CacheManager会自动处理数据库降级)
"""
# 缓存未命中,返回None
# 注意:CacheManager已经在get_klines时处理了数据库降级
logger.warning(f"[{self.instance_id}] No data available: {symbol}_{period}")
return None
def get_indicators(
self,
symbol: Optional[str] = None,
period: str = "1m",
indicator_type: str = "MACD",
) -> Optional[pd.DataFrame]:
"""
获取指标数据
Args:
symbol: 标的代码,默认使用实例的 symbol
period: 周期
indicator_type: 指标类型
Returns:
指标DataFrame,如果不存在返回None
"""
target_symbol = symbol or self.symbol
try:
return self._cache_manager.get_indicator(
target_symbol, period, indicator_type
)
except Exception as e:
logger.error(
f"[{self.instance_id}] Error getting indicators: {e}", exc_info=True
)
return None
# ==================== 状态访问接口 ====================
def get_position(self) -> Position:
"""获取持仓信息(独立状态)"""
return self._position
def get_capital(self) -> Capital:
"""获取资金信息(独立状态)"""
return self._capital
def get_risk_state(self) -> RiskState:
"""获取风险状态(独立状态)"""
return self._risk_state
def update_position(self, shares_change: float, cost_change: float):
"""
更新持仓
Args:
shares_change: 持仓变化
cost_change: 成本变化
"""
self._position.update(shares_change, cost_change)
def update_capital(self, amount: float):
"""
更新资金
Args:
amount: 资金变化
"""
self._capital.update(amount)
# ==================== 工具方法 ====================
def get_cache_info(self, symbol: Optional[str] = None, period: str = "1m") -> dict:
"""
获取缓存信息(用于调试)
Args:
symbol: 标的代码
period: 周期
Returns:
缓存信息字典
"""
target_symbol = symbol or self.symbol
try:
data = self._cache_manager.get_klines(target_symbol, period)
if data is None:
return {"exists": False}
df = data.get("klines")
if df is None or df.empty:
return {"exists": True, "rows": 0}
return {
"exists": True,
"rows": len(df),
"columns": list(df.columns),
"first_timestamp": df["timestamp"].iloc[0]
if "timestamp" in df.columns
else None,
"last_timestamp": df["timestamp"].iloc[-1]
if "timestamp" in df.columns
else None,
}
except Exception as e:
logger.error(f"[{self.instance_id}] Error getting cache info: {e}")
return {"error": str(e)}
def get_status(self) -> dict:
"""
获取上下文状态
Returns:
状态字典
"""
return {
"instance_id": self.instance_id,
"symbol": self.symbol,
"position": self._position.to_dict(),
"capital": self._capital.to_dict(),
"risk_state": self._risk_state.to_dict(),
}