import numpy as np import pandas as pd class DataQualityAuditor: """Performs real-time transaction and sequence quality audits. Calculates the Data Quality Index (DQI) and updates scoring confidence. """ def __init__(self, sparsity_threshold=5, rounded_pct_limit=0.90): self.sparsity_threshold = sparsity_threshold self.rounded_pct_limit = rounded_pct_limit def audit_transaction_sequence(self, df_tx, current_balance, calculated_balance=None): """Audits a user's transaction history for consistency and realism. Returns: dict: Data quality flags and computed DQI. """ flags = { "transaction_sparsity": False, "corrupted_timestamps": False, "synthetic_fingerprint": False, "unrealistic_balance_dynamics": False, "missingness": False } n_tx = len(df_tx) # 1. Sparsity check if n_tx < self.sparsity_threshold: flags["transaction_sparsity"] = True # 2. Missingness check if df_tx[["transaction_date", "amount", "account_id"]].isnull().any().any(): flags["missingness"] = True # 3. Timestamps check (out of chronological order) if n_tx >= 2: dates = pd.to_datetime(df_tx["transaction_date"]) if not dates.is_monotonic_increasing: flags["corrupted_timestamps"] = True # 4. Synthetic fingerprinting # Standard generators produce perfectly rounded amounts (e.g. $10.00, $15.00) # We check the percentage of transaction amounts that are integers/perfectly rounded. if n_tx >= 5: amounts = df_tx["amount"].dropna().values cents = amounts - np.floor(amounts) perfect_rounds = np.sum(cents == 0.0) / len(amounts) if perfect_rounds > self.rounded_pct_limit: flags["synthetic_fingerprint"] = True # 5. Balance Dynamics check if calculated_balance is not None and abs(current_balance - calculated_balance) > 0.01: flags["unrealistic_balance_dynamics"] = True # Compute DQI # DQI starts at 1.0 and drops for each active flag penalty = 0.0 if flags["transaction_sparsity"]: penalty += 0.30 if flags["missingness"]: penalty += 0.20 if flags["corrupted_timestamps"]: penalty += 0.20 if flags["synthetic_fingerprint"]: penalty += 0.15 if flags["unrealistic_balance_dynamics"]: penalty += 0.15 dqi = float(np.clip(1.0 - penalty, 0.1, 1.0)) return { "dqi": dqi, "flags": flags, "transaction_count": n_tx } def scale_confidence_and_bounds(self, confidence_score, conformal_bounds, dqi): """Automatically scales down model confidence score and widens prediction intervals under poor DQI.""" if dqi >= 0.95: return confidence_score, conformal_bounds # Scale down confidence scaled_conf = float(np.clip(confidence_score * dqi, 0.10, 1.0)) # Widen conformal bounds scaled_bounds = {} for risk_type, bounds in conformal_bounds.items(): lower = bounds["lower"] upper = bounds["upper"] width = bounds["uncertainty"] # Widen interval proportional to 1.0 - DQI expansion = (1.0 - dqi) * 0.20 new_lower = float(np.clip(lower - expansion, 0.0, 1.0)) new_upper = float(np.clip(upper + expansion, 0.0, 1.0)) scaled_bounds[risk_type] = { "lower": new_lower, "upper": new_upper, "uncertainty": float(new_upper - new_lower) } return scaled_conf, scaled_bounds