|
| 1 | +"""Forensic report structures for risk scoring and causal attribution.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from dataclasses import dataclass, field |
| 6 | + |
| 7 | +import networkx as nx |
| 8 | +import pandas as pd |
| 9 | + |
| 10 | +from detection.causal_attribution import CounterfactualAttributor |
| 11 | +from detection.model_inference import RiskScorer |
| 12 | +from detection.shap_explainer import ShapExplainer |
| 13 | + |
| 14 | + |
| 15 | +@dataclass(slots=True) |
| 16 | +class CausalAttribution: |
| 17 | + minimal_exonerating_trades: list[str] |
| 18 | + counterfactual_score: int |
| 19 | + root_cause_wallet: str | None |
| 20 | + causal_chain: list[dict] |
| 21 | + interventional_score_if_no_wash: int |
| 22 | + |
| 23 | + |
| 24 | +@dataclass(slots=True) |
| 25 | +class ForensicReport: |
| 26 | + wallet: str |
| 27 | + asset_pair: str |
| 28 | + risk_score: dict |
| 29 | + shap_explanations: list[dict] = field(default_factory=list) |
| 30 | + causal_attribution: CausalAttribution | None = None |
| 31 | + |
| 32 | + |
| 33 | +class ForensicReportGenerator: |
| 34 | + """Build a structured report for a scored wallet.""" |
| 35 | + |
| 36 | + def __init__(self, scorer: RiskScorer | None = None, explainer: ShapExplainer | None = None): |
| 37 | + self._scorer = scorer or RiskScorer() |
| 38 | + self._explainer = explainer or ShapExplainer() |
| 39 | + |
| 40 | + def generate( |
| 41 | + self, |
| 42 | + wallet: str, |
| 43 | + asset_pair: str, |
| 44 | + feature_row: pd.Series, |
| 45 | + wallet_trades: pd.DataFrame, |
| 46 | + activity=None, |
| 47 | + orderbook_events: pd.DataFrame | None = None, |
| 48 | + funding_graph: nx.DiGraph | None = None, |
| 49 | + all_pairs_df: pd.DataFrame | None = None, |
| 50 | + causal: bool = False, |
| 51 | + top_n: int = 5, |
| 52 | + ) -> ForensicReport: |
| 53 | + risk_score = self._scorer.score(feature_row) |
| 54 | + shap_explanations = [] |
| 55 | + try: |
| 56 | + shap_explanations = self._explainer.explain_ensemble( |
| 57 | + feature_row, self._scorer.models, top_n=top_n |
| 58 | + ) |
| 59 | + except Exception: # noqa: BLE001 |
| 60 | + shap_explanations = [] |
| 61 | + |
| 62 | + causal_attribution = None |
| 63 | + if causal: |
| 64 | + attributor = CounterfactualAttributor(self._scorer) |
| 65 | + minimal_set = ( |
| 66 | + attributor.minimal_exonerating_set( |
| 67 | + wallet, |
| 68 | + wallet_trades, |
| 69 | + activity=activity, |
| 70 | + orderbook_events=orderbook_events, |
| 71 | + funding_graph=funding_graph, |
| 72 | + all_pairs_df=all_pairs_df, |
| 73 | + ) |
| 74 | + or [] |
| 75 | + ) |
| 76 | + counterfactual = attributor.counterfactual_score( |
| 77 | + wallet, |
| 78 | + wallet_trades, |
| 79 | + minimal_set, |
| 80 | + activity=activity, |
| 81 | + orderbook_events=orderbook_events, |
| 82 | + funding_graph=funding_graph, |
| 83 | + all_pairs_df=all_pairs_df, |
| 84 | + ) |
| 85 | + scm = attributor.build_scm( |
| 86 | + wallet, |
| 87 | + wallet_trades, |
| 88 | + activities=[activity] if activity is not None else None, |
| 89 | + orderbook_events=orderbook_events, |
| 90 | + funding_graph=funding_graph, |
| 91 | + all_pairs_df=all_pairs_df, |
| 92 | + ) |
| 93 | + intervention_score = counterfactual["counterfactual_score"] |
| 94 | + intervention_key = next( |
| 95 | + (name for name in feature_row.index if name == "benford_chi_square_24h"), |
| 96 | + next( |
| 97 | + (name for name in feature_row.index if name.startswith("benford_chi_square_")), |
| 98 | + None, |
| 99 | + ), |
| 100 | + ) |
| 101 | + if intervention_key is not None: |
| 102 | + intervention_result = attributor.interventional_score( |
| 103 | + wallet, scm, {intervention_key: 0.0} |
| 104 | + ) |
| 105 | + intervention_score = intervention_result["score"] |
| 106 | + |
| 107 | + causal_attribution = CausalAttribution( |
| 108 | + minimal_exonerating_trades=minimal_set, |
| 109 | + counterfactual_score=counterfactual["counterfactual_score"], |
| 110 | + root_cause_wallet=attributor.root_cause_wallet( |
| 111 | + wallet, |
| 112 | + wallet_trades, |
| 113 | + funding_graph, |
| 114 | + activity=activity, |
| 115 | + orderbook_events=orderbook_events, |
| 116 | + all_pairs_df=all_pairs_df, |
| 117 | + ), |
| 118 | + causal_chain=attributor.causal_chain(wallet, funding_graph), |
| 119 | + interventional_score_if_no_wash=intervention_score, |
| 120 | + ) |
| 121 | + |
| 122 | + return ForensicReport( |
| 123 | + wallet=wallet, |
| 124 | + asset_pair=asset_pair, |
| 125 | + risk_score=risk_score, |
| 126 | + shap_explanations=shap_explanations, |
| 127 | + causal_attribution=causal_attribution, |
| 128 | + ) |
0 commit comments