|
| 1 | +"""Shared signal snapshot payload helpers for platform reports.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from collections.abc import Mapping |
| 6 | +from datetime import date, datetime, timezone |
| 7 | +from typing import Any |
| 8 | + |
| 9 | +SIGNAL_SNAPSHOT_SCHEMA_VERSION = "signal_snapshot.v1" |
| 10 | + |
| 11 | +_INDICATOR_FIELDS = ( |
| 12 | + "benchmark_symbol", |
| 13 | + "benchmark_price", |
| 14 | + "long_trend_value", |
| 15 | + "exit_line", |
| 16 | + "active_risk_asset", |
| 17 | + "allocation_mode", |
| 18 | + "trend_symbol", |
| 19 | + "trend_price", |
| 20 | + "trend_ma", |
| 21 | + "trend_ma20", |
| 22 | + "trend_ma20_slope", |
| 23 | + "trend_rsi14", |
| 24 | + "trend_rsi14_dynamic_threshold", |
| 25 | + "trend_rsi14_effective_threshold", |
| 26 | + "trend_bb_upper", |
| 27 | + "blend_gate_volatility_delever_metric", |
| 28 | + "blend_gate_volatility_delever_triggered", |
| 29 | +) |
| 30 | + |
| 31 | + |
| 32 | +def _utcnow() -> datetime: |
| 33 | + return datetime.now(timezone.utc) |
| 34 | + |
| 35 | + |
| 36 | +def _json_safe(value: Any) -> Any: |
| 37 | + if isinstance(value, datetime): |
| 38 | + return value.isoformat() |
| 39 | + if isinstance(value, date): |
| 40 | + return value.isoformat() |
| 41 | + if isinstance(value, Mapping): |
| 42 | + return {str(key): _json_safe(item) for key, item in value.items()} |
| 43 | + if isinstance(value, (list, tuple, set)): |
| 44 | + return [_json_safe(item) for item in value] |
| 45 | + return value |
| 46 | + |
| 47 | + |
| 48 | +def _first_value(*values: Any) -> Any: |
| 49 | + for value in values: |
| 50 | + if value is not None and value != "": |
| 51 | + return value |
| 52 | + return None |
| 53 | + |
| 54 | + |
| 55 | +def _merge_signal_sources(*sources: Mapping[str, Any] | None) -> dict[str, Any]: |
| 56 | + merged: dict[str, Any] = {} |
| 57 | + for source in sources: |
| 58 | + if not isinstance(source, Mapping): |
| 59 | + continue |
| 60 | + annotations = source.get("execution_annotations") |
| 61 | + if isinstance(annotations, Mapping): |
| 62 | + merged.update(annotations) |
| 63 | + merged.update(source) |
| 64 | + return merged |
| 65 | + |
| 66 | + |
| 67 | +def _normalized_numeric_mapping(value: Any) -> dict[str, float]: |
| 68 | + if not isinstance(value, Mapping): |
| 69 | + return {} |
| 70 | + normalized: dict[str, float] = {} |
| 71 | + for key, raw_value in value.items(): |
| 72 | + symbol = str(key or "").strip().upper() |
| 73 | + if not symbol: |
| 74 | + continue |
| 75 | + try: |
| 76 | + normalized[symbol] = float(raw_value) |
| 77 | + except (TypeError, ValueError): |
| 78 | + continue |
| 79 | + return normalized |
| 80 | + |
| 81 | + |
| 82 | +def _target_payload( |
| 83 | + *, |
| 84 | + allocation: Mapping[str, Any] | None, |
| 85 | + explicit_target_weights: Mapping[str, Any] | None, |
| 86 | +) -> tuple[str | None, dict[str, float], dict[str, float]]: |
| 87 | + allocation = allocation if isinstance(allocation, Mapping) else {} |
| 88 | + target_mode = str(allocation.get("target_mode") or "").strip() or None |
| 89 | + targets = _normalized_numeric_mapping(explicit_target_weights or allocation.get("targets")) |
| 90 | + if target_mode == "value": |
| 91 | + return target_mode, {}, targets |
| 92 | + return target_mode, targets, {} |
| 93 | + |
| 94 | + |
| 95 | +def build_signal_snapshot( |
| 96 | + *, |
| 97 | + platform: str, |
| 98 | + strategy_profile: str | None = None, |
| 99 | + generated_at: datetime | None = None, |
| 100 | + diagnostics: Mapping[str, Any] | None = None, |
| 101 | + execution: Mapping[str, Any] | None = None, |
| 102 | + allocation: Mapping[str, Any] | None = None, |
| 103 | + metadata: Mapping[str, Any] | None = None, |
| 104 | + target_weights: Mapping[str, Any] | None = None, |
| 105 | +) -> dict[str, Any]: |
| 106 | + source = _merge_signal_sources(metadata, diagnostics, execution) |
| 107 | + target_mode, normalized_weights, normalized_values = _target_payload( |
| 108 | + allocation=allocation, |
| 109 | + explicit_target_weights=target_weights, |
| 110 | + ) |
| 111 | + indicators = { |
| 112 | + field: _json_safe(source[field]) |
| 113 | + for field in _INDICATOR_FIELDS |
| 114 | + if source.get(field) not in (None, "") |
| 115 | + } |
| 116 | + snapshot = { |
| 117 | + "schema_version": SIGNAL_SNAPSHOT_SCHEMA_VERSION, |
| 118 | + "platform": str(platform or "").strip(), |
| 119 | + "strategy_profile": _first_value(strategy_profile, source.get("strategy_profile")), |
| 120 | + "strategy_version": source.get("strategy_version"), |
| 121 | + "generated_at": _json_safe(generated_at or _utcnow()), |
| 122 | + "signal_as_of": _json_safe( |
| 123 | + _first_value( |
| 124 | + source.get("signal_as_of"), |
| 125 | + source.get("signal_date"), |
| 126 | + source.get("snapshot_as_of"), |
| 127 | + source.get("trade_date"), |
| 128 | + ) |
| 129 | + ), |
| 130 | + "market_date": _json_safe( |
| 131 | + _first_value( |
| 132 | + source.get("market_date"), |
| 133 | + source.get("signal_date"), |
| 134 | + source.get("snapshot_as_of"), |
| 135 | + source.get("trade_date"), |
| 136 | + ) |
| 137 | + ), |
| 138 | + "effective_date": _json_safe(source.get("effective_date")), |
| 139 | + "latest_price_source": _first_value( |
| 140 | + source.get("latest_price_source"), |
| 141 | + source.get("price_source_mode"), |
| 142 | + source.get("market_data_source"), |
| 143 | + source.get("signal_source"), |
| 144 | + ), |
| 145 | + "quote_overlay_used": source.get("quote_overlay_used"), |
| 146 | + "data_freshness_warning": _first_value( |
| 147 | + source.get("data_freshness_warning"), |
| 148 | + source.get("snapshot_price_fallback_used"), |
| 149 | + ), |
| 150 | + "signal": _first_value( |
| 151 | + source.get("signal_display"), |
| 152 | + source.get("signal_description"), |
| 153 | + source.get("signal_message"), |
| 154 | + ), |
| 155 | + "status": _first_value( |
| 156 | + source.get("status_display"), |
| 157 | + source.get("status_description"), |
| 158 | + source.get("market_status"), |
| 159 | + source.get("canary_status"), |
| 160 | + ), |
| 161 | + "target_mode": target_mode, |
| 162 | + "target_weights": normalized_weights, |
| 163 | + "target_values": normalized_values, |
| 164 | + "indicators": indicators, |
| 165 | + } |
| 166 | + return {key: _json_safe(value) for key, value in snapshot.items()} |
0 commit comments