|
| 1 | +"""Centralized configuration validation utilities. |
| 2 | +
|
| 3 | +Provides a helper to validate all first-class YAML configuration files used |
| 4 | +by QuantTradeAI and emit consolidated JSON/CSV reports. Validation reuses the |
| 5 | +project's existing Pydantic schemas and loader helpers to mirror runtime |
| 6 | +behavior. |
| 7 | +""" |
| 8 | + |
| 9 | +from __future__ import annotations |
| 10 | + |
| 11 | +import csv |
| 12 | +import json |
| 13 | +from dataclasses import dataclass |
| 14 | +from datetime import datetime, timezone |
| 15 | +from pathlib import Path |
| 16 | +from typing import Callable, Dict, Iterable, Mapping |
| 17 | + |
| 18 | +import yaml |
| 19 | +from pydantic import ValidationError |
| 20 | + |
| 21 | +from quanttradeai.utils.config_schemas import ( |
| 22 | + BacktestConfigSchema, |
| 23 | + FeaturesConfigSchema, |
| 24 | + ModelConfigSchema, |
| 25 | + PositionManagerConfig, |
| 26 | + RiskManagementConfig, |
| 27 | +) |
| 28 | +from quanttradeai.utils.impact_loader import ImpactConfigError, load_impact_config |
| 29 | + |
| 30 | + |
| 31 | +DEFAULT_CONFIG_PATHS: Dict[str, Path] = { |
| 32 | + "model_config": Path("config/model_config.yaml"), |
| 33 | + "features_config": Path("config/features_config.yaml"), |
| 34 | + "backtest_config": Path("config/backtest_config.yaml"), |
| 35 | + "impact_config": Path("config/impact_config.yaml"), |
| 36 | + "risk_config": Path("config/risk_config.yaml"), |
| 37 | + "streaming_config": Path("config/streaming.yaml"), |
| 38 | + "position_manager_config": Path("config/position_manager.yaml"), |
| 39 | +} |
| 40 | + |
| 41 | + |
| 42 | +@dataclass |
| 43 | +class ValidationResult: |
| 44 | + """Serializable validation outcome.""" |
| 45 | + |
| 46 | + name: str |
| 47 | + path: str |
| 48 | + passed: bool |
| 49 | + details: Dict | None = None |
| 50 | + error: str | None = None |
| 51 | + |
| 52 | + def to_dict(self) -> Dict: |
| 53 | + payload = { |
| 54 | + "path": self.path, |
| 55 | + "passed": self.passed, |
| 56 | + } |
| 57 | + if self.details: |
| 58 | + payload["details"] = self.details |
| 59 | + if self.error: |
| 60 | + payload["error"] = self.error |
| 61 | + return payload |
| 62 | + |
| 63 | + |
| 64 | +def _load_yaml(path: Path) -> Dict: |
| 65 | + if not path.exists(): |
| 66 | + raise FileNotFoundError(f"Config file not found: {path}") |
| 67 | + with path.open("r", encoding="utf-8") as f: |
| 68 | + data = yaml.safe_load(f) |
| 69 | + if data is None: |
| 70 | + raise ValueError(f"Config file is empty: {path}") |
| 71 | + if not isinstance(data, dict): |
| 72 | + raise ValueError(f"Config file must contain a mapping at root: {path}") |
| 73 | + return data |
| 74 | + |
| 75 | + |
| 76 | +def _validate_model_config(path: Path) -> Dict: |
| 77 | + raw = _load_yaml(path) |
| 78 | + cfg = ModelConfigSchema(**raw) |
| 79 | + return { |
| 80 | + "symbols": list(cfg.data.symbols), |
| 81 | + "timeframe": cfg.data.timeframe, |
| 82 | + "test_window": { |
| 83 | + "start": cfg.data.test_start, |
| 84 | + "end": cfg.data.test_end, |
| 85 | + }, |
| 86 | + } |
| 87 | + |
| 88 | + |
| 89 | +def _validate_features_config(path: Path) -> Dict: |
| 90 | + raw = _load_yaml(path) |
| 91 | + cfg = FeaturesConfigSchema(**raw) |
| 92 | + steps: Iterable[str] = cfg.pipeline.steps if cfg.pipeline else [] |
| 93 | + return { |
| 94 | + "pipeline_steps": list(steps), |
| 95 | + "price_features": sorted(cfg.price_features.enabled), |
| 96 | + } |
| 97 | + |
| 98 | + |
| 99 | +def _validate_backtest_config(path: Path) -> Dict: |
| 100 | + raw = _load_yaml(path) |
| 101 | + cfg = BacktestConfigSchema(**raw) |
| 102 | + execution = cfg.execution |
| 103 | + return { |
| 104 | + "transaction_costs": execution.transaction_costs.enabled, |
| 105 | + "slippage": execution.slippage.enabled, |
| 106 | + "impact": execution.impact.enabled, |
| 107 | + "liquidity": execution.liquidity.enabled, |
| 108 | + "borrow_fee": execution.borrow_fee.enabled, |
| 109 | + "intrabar": execution.intrabar.enabled, |
| 110 | + } |
| 111 | + |
| 112 | + |
| 113 | +def _validate_impact_config(path: Path) -> Dict: |
| 114 | + validated = load_impact_config(path) |
| 115 | + return {"asset_classes": sorted(validated)} |
| 116 | + |
| 117 | + |
| 118 | +def _validate_risk_config(path: Path) -> Dict: |
| 119 | + raw = _load_yaml(path) |
| 120 | + cfg = RiskManagementConfig(**raw.get("risk_management", raw)) |
| 121 | + dd_cfg = cfg.drawdown_protection |
| 122 | + to_cfg = cfg.turnover_limits |
| 123 | + return { |
| 124 | + "drawdown_protection_enabled": dd_cfg.enabled, |
| 125 | + "turnover_limits": { |
| 126 | + "daily_max": to_cfg.daily_max, |
| 127 | + "weekly_max": to_cfg.weekly_max, |
| 128 | + "monthly_max": to_cfg.monthly_max, |
| 129 | + }, |
| 130 | + } |
| 131 | + |
| 132 | + |
| 133 | +def _validate_streaming_config(path: Path) -> Dict: |
| 134 | + raw = _load_yaml(path) |
| 135 | + streaming_cfg = raw.get("streaming") |
| 136 | + if not isinstance(streaming_cfg, dict): |
| 137 | + raise ValueError("streaming config must include a 'streaming' mapping") |
| 138 | + providers = streaming_cfg.get("providers") |
| 139 | + provider_count = len(providers) if isinstance(providers, list) else 0 |
| 140 | + return { |
| 141 | + "providers": provider_count, |
| 142 | + "symbols": streaming_cfg.get("symbols", []), |
| 143 | + } |
| 144 | + |
| 145 | + |
| 146 | +def _validate_position_manager_config(path: Path) -> Dict: |
| 147 | + raw = _load_yaml(path) |
| 148 | + cfg = PositionManagerConfig(**raw.get("position_manager", raw)) |
| 149 | + return { |
| 150 | + "mode": cfg.mode, |
| 151 | + "reconciliation": cfg.reconciliation, |
| 152 | + "risk_management": { |
| 153 | + "drawdown_enabled": cfg.risk_management.drawdown_protection.enabled, |
| 154 | + }, |
| 155 | + } |
| 156 | + |
| 157 | + |
| 158 | +VALIDATORS: Dict[str, Callable[[Path], Dict]] = { |
| 159 | + "model_config": _validate_model_config, |
| 160 | + "features_config": _validate_features_config, |
| 161 | + "backtest_config": _validate_backtest_config, |
| 162 | + "impact_config": _validate_impact_config, |
| 163 | + "risk_config": _validate_risk_config, |
| 164 | + "streaming_config": _validate_streaming_config, |
| 165 | + "position_manager_config": _validate_position_manager_config, |
| 166 | +} |
| 167 | + |
| 168 | + |
| 169 | +def _run_validator(name: str, path: Path) -> ValidationResult: |
| 170 | + validator = VALIDATORS[name] |
| 171 | + try: |
| 172 | + details = validator(path) |
| 173 | + return ValidationResult(name=name, path=str(path), passed=True, details=details) |
| 174 | + except (ValidationError, ImpactConfigError, FileNotFoundError, ValueError) as exc: |
| 175 | + return ValidationResult(name=name, path=str(path), passed=False, error=str(exc)) |
| 176 | + except Exception as exc: # pragma: no cover - defensive |
| 177 | + return ValidationResult( |
| 178 | + name=name, path=str(path), passed=False, error=repr(exc) |
| 179 | + ) |
| 180 | + |
| 181 | + |
| 182 | +def _write_reports(output_dir: Path, summary: Dict, timestamp: str) -> Dict[str, str]: |
| 183 | + output_dir.mkdir(parents=True, exist_ok=True) |
| 184 | + json_path = output_dir / f"config_validation_{timestamp}.json" |
| 185 | + with json_path.open("w", encoding="utf-8") as f: |
| 186 | + json.dump(summary, f, indent=2, default=str) |
| 187 | + |
| 188 | + csv_path = output_dir / f"config_validation_{timestamp}.csv" |
| 189 | + with csv_path.open("w", encoding="utf-8", newline="") as f: |
| 190 | + writer = csv.DictWriter(f, fieldnames=["name", "path", "passed", "error"]) |
| 191 | + writer.writeheader() |
| 192 | + for name, result in summary["results"].items(): |
| 193 | + writer.writerow( |
| 194 | + { |
| 195 | + "name": name, |
| 196 | + "path": result["path"], |
| 197 | + "passed": result["passed"], |
| 198 | + "error": result.get("error", ""), |
| 199 | + } |
| 200 | + ) |
| 201 | + |
| 202 | + return {"json": str(json_path), "csv": str(csv_path)} |
| 203 | + |
| 204 | + |
| 205 | +def validate_all( |
| 206 | + config_paths: Mapping[str, Path | str] | None = None, |
| 207 | + *, |
| 208 | + output_dir: Path | str = "reports/config_validation", |
| 209 | +) -> Dict: |
| 210 | + """Validate all known configuration files and persist a summary report.""" |
| 211 | + |
| 212 | + resolved_paths: Dict[str, Path] = {k: v for k, v in DEFAULT_CONFIG_PATHS.items()} |
| 213 | + if config_paths: |
| 214 | + for name, path in config_paths.items(): |
| 215 | + if name not in VALIDATORS: |
| 216 | + continue |
| 217 | + resolved_paths[name] = Path(path) |
| 218 | + |
| 219 | + results: Dict[str, Dict] = {} |
| 220 | + for name, path in resolved_paths.items(): |
| 221 | + result = _run_validator(name, path) |
| 222 | + results[name] = result.to_dict() |
| 223 | + |
| 224 | + timestamp = datetime.now(timezone.utc).strftime("%Y%m%d_%H%M%S") |
| 225 | + summary = { |
| 226 | + "timestamp": timestamp, |
| 227 | + "all_passed": all(r["passed"] for r in results.values()), |
| 228 | + "results": results, |
| 229 | + } |
| 230 | + report_paths = _write_reports(Path(output_dir), summary, timestamp) |
| 231 | + summary["report_paths"] = report_paths |
| 232 | + return summary |
0 commit comments