核心组件: - ConfigLoader: 配置加载器(YAML支持) - StrategyConfig: 策略配置数据类 - framework/__init__.py: 框架统一入口 导出接口: - FactorBase, FactorRegistry, FactorCombiner - SignalGenerator, TopNSelector, TrendFollower, ReversalTrader - StrategyBase, RotationStrategy - RiskControl, StopLossControl, PositionLimitControl - Executor, BacktestExecutor, DryRunExecutor - ConfigLoader 集成测试: - 轮动策略完整流程验证 - 趋势策略完整流程验证 - 回调钩子完整流程验证 总计:62个测试全部通过,框架核心实现完成
83 lines
2.0 KiB
Python
83 lines
2.0 KiB
Python
"""
|
|
配置层抽象设计
|
|
|
|
核心组件:
|
|
- ConfigLoader: 配置加载器
|
|
"""
|
|
|
|
import yaml
|
|
from typing import Dict, Any, Optional
|
|
from pathlib import Path
|
|
from dataclasses import dataclass
|
|
|
|
|
|
@dataclass
|
|
class StrategyConfig:
|
|
"""策略配置"""
|
|
name: str
|
|
version: int
|
|
factors: list
|
|
signal: dict
|
|
callbacks: dict
|
|
params: dict
|
|
|
|
|
|
class ConfigLoader:
|
|
"""
|
|
配置加载器
|
|
|
|
支持YAML配置文件加载和验证
|
|
"""
|
|
|
|
def __init__(self, config_path: str):
|
|
"""
|
|
初始化配置加载器
|
|
|
|
Args:
|
|
config_path: 配置文件路径
|
|
"""
|
|
self._config_path = Path(config_path)
|
|
self._config = None
|
|
|
|
def load(self) -> Dict:
|
|
"""加载配置"""
|
|
if not self._config_path.exists():
|
|
raise FileNotFoundError(f"Config file not found: {self._config_path}")
|
|
|
|
with open(self._config_path, 'r', encoding='utf-8') as f:
|
|
self._config = yaml.safe_load(f)
|
|
|
|
return self._config
|
|
|
|
def validate(self) -> bool:
|
|
"""验证配置"""
|
|
if self._config is None:
|
|
self.load()
|
|
|
|
# 必须字段
|
|
required_fields = ['strategy', 'factors', 'signal']
|
|
|
|
for field in required_fields:
|
|
if field not in self._config:
|
|
raise ValueError(f"Missing required field: {field}")
|
|
|
|
return True
|
|
|
|
def get_strategy_config(self) -> StrategyConfig:
|
|
"""获取策略配置"""
|
|
if self._config is None:
|
|
self.load()
|
|
|
|
return StrategyConfig(
|
|
name=self._config['strategy']['name'],
|
|
version=self._config['strategy'].get('version', 1),
|
|
factors=self._config['factors'],
|
|
signal=self._config['signal'],
|
|
callbacks=self._config.get('callbacks', {}),
|
|
params=self._config.get('params', {})
|
|
)
|
|
|
|
@staticmethod
|
|
def from_yaml(yaml_str: str) -> Dict:
|
|
"""从YAML字符串加载"""
|
|
return yaml.safe_load(yaml_str) |