""" TradeSense AI — Market Data Quality Gate & Invariant Validator (Module 01) Validates quotes and historical bars against strict quantitative invariants, preventing malformed upstream data from silently reaching the quant engine or UI. """ import math from typing import Dict, List, Optional, Tuple, Any from datetime import datetime from backend.domain.market_data import CanonicalQuote, DataStatus, MarketStatus, QuoteQualityReport class MarketDataQualityValidator: """ Enforces mathematical and structural integrity on quotes and historical bars. Rejects negative prices, inverted OHLC, duplicate timestamps, and anomalous spikes. """ @staticmethod def validate_quote(quote: CanonicalQuote) -> Tuple[bool, List[str]]: """ Validates quote invariants. Returns: (is_valid, list_of_warning_messages) """ warnings: List[str] = [] # If data is not available, pricing fields may legitimately be None if quote.data_status != DataStatus.AVAILABLE: if quote.last_price is not None and quote.last_price <= 0: warnings.append(f"Non-positive last_price {quote.last_price} on unavailable quote") return True, warnings # For AVAILABLE quotes: last_price is mandatory and must be strictly positive! if quote.last_price is None: return False, ["AVAILABLE quote has missing (None) last_price"] if quote.last_price <= 0 or math.isnan(quote.last_price) or math.isinf(quote.last_price): return False, [f"Invalid last_price: {quote.last_price} (must be > 0 and finite)"] # Invariant: day_high >= day_low if quote.day_high is not None and quote.day_low is not None: if quote.day_high < quote.day_low: return False, [f"Inverted day range: high ({quote.day_high}) < low ({quote.day_low})"] # Last price sanity against day range (allow 10% buffer for pre/post-market ticks) if quote.last_price > quote.day_high * 1.15: warnings.append(f"last_price ({quote.last_price}) significantly exceeds day_high ({quote.day_high})") if quote.last_price < quote.day_low * 0.85: warnings.append(f"last_price ({quote.last_price}) significantly below day_low ({quote.day_low})") # Invariant: previous_close > 0 if quote.previous_close is not None: if quote.previous_close <= 0: warnings.append(f"Non-positive previous_close: {quote.previous_close}") else: # Mathematical consistency between last_price, previous_close, and change if quote.change is not None: expected_change = round(quote.last_price - quote.previous_close, 2) if abs(quote.change - expected_change) > 1.5: # Tolerance for currency rounding warnings.append(f"Change mismatch: reported {quote.change} vs expected {expected_change}") # Invariant: volume >= 0 if quote.volume is not None and quote.volume < 0: return False, [f"Negative volume: {quote.volume}"] return True, warnings @staticmethod def validate_historical_bar(bar: Dict[str, Any]) -> Tuple[bool, Optional[str]]: """ Validates OHLCV invariant relationships for a single bar. Rules: open, high, low, close > 0 high >= low high >= open high >= close low <= open low <= close volume >= 0 """ try: o = float(bar.get("open", 0)) h = float(bar.get("high", 0)) l = float(bar.get("low", 0)) c = float(bar.get("close", 0)) v = float(bar.get("volume", 0)) except (ValueError, TypeError) as e: return False, f"Non-numeric OHLCV value: {e}" if o <= 0 or h <= 0 or l <= 0 or c <= 0: return False, f"Non-positive price in OHLC: O={o}, H={h}, L={l}, C={c}" if any(math.isnan(x) or math.isinf(x) for x in (o, h, l, c, v)): return False, "NaN or infinite value in bar" if h < l: return False, f"High ({h}) is less than Low ({l})" if h < o or h < c: return False, f"High ({h}) is less than Open ({o}) or Close ({c})" if l > o or l > c: return False, f"Low ({l}) is greater than Open ({o}) or Close ({c})" if v < 0: return False, f"Negative volume: {v}" return True, None @classmethod def sanitize_historical_series( cls, bars: List[Dict[str, Any]] ) -> Tuple[List[Dict[str, Any]], Dict[str, Any]]: """ Filters malformed bars, ensures monotonic ordering, and eliminates duplicate timestamps. Returns: (sanitized_bars, quality_report) """ if not bars: return [], { "status": "EMPTY", "quality_score": 0.0, "total_input": 0, "valid_count": 0, "rejected_count": 0, "warnings": ["Zero bars received"] } sanitized: List[Dict[str, Any]] = [] rejected: int = 0 rejection_reasons: List[str] = [] seen_timestamps = set() for b in bars: is_valid, reason = cls.validate_historical_bar(b) if not is_valid: rejected += 1 if reason and len(rejection_reasons) < 5: rejection_reasons.append(reason) continue ts = b.get("time") or b.get("timestamp") if ts in seen_timestamps: # Deduplicate exact timestamps continue seen_timestamps.add(ts) sanitized.append(b) # Sort chronologically if timestamps are comparable try: sanitized.sort(key=lambda x: str(x.get("time") or x.get("timestamp") or "")) except Exception: pass total_input = len(bars) valid_count = len(sanitized) quality_score = round(valid_count / total_input, 3) if total_input > 0 else 0.0 return sanitized, { "status": "VALID" if quality_score >= 0.95 else ("DEGRADED" if quality_score >= 0.7 else "REJECTED"), "quality_score": quality_score, "total_input": total_input, "valid_count": valid_count, "rejected_count": rejected, "sample_rejections": rejection_reasons, } # Global Quality Validator Singleton quality_validator = MarketDataQualityValidator()