import pandas as pd
from datetime import datetime
from sklearn.ensemble import IsolationForest
# Mock imports for LLM and Alerting
from langchain.prompts import PromptTemplate
from notification_client import send_cfo_alert
class CashTwinEngine:
def __init__(self, threshold_score=-0.5):
self.model = IsolationForest(contamination=0.01)
self.cash_positions = pd.DataFrame()
def ingest_streams(self, swift_gpi_data, bank_api_data, erp_forecast):
"""
Merges real-time actuals (API/gpi) with future expectations (ERP).
"""
# Combine data sources into a unified timeline
current_state = self.reconcile(swift_gpi_data, bank_api_data)
self.cash_positions = self.apply_forecast(current_state, erp_forecast)
def detect_anomalies(self):
"""
Scans for deviations in value, timing, or currency location.
"""
features = self.cash_positions[['amount', 'time_delta_hours', 'region_code']]
predictions = self.model.fit_predict(features)
# Filter for outliers (-1 is an outlier in IsolationForest)
anomalies = self.cash_positions[predictions == -1]
return anomalies
def generate_narrative(self, anomaly):
"""
Creates a human-readable story explaining the anomaly.
"""
prompt = PromptTemplate(
template="""
Context: You are a Treasury Analyst AI.
Anomaly Detected: Transaction of {currency} {amount} from {source} to {dest}.
Deviation: This transaction is {deviation_type} (Expected: {expected}, Actual: {actual}).
Impact: This shifts the projected liquidity by {impact_pct}%.
Task: Write a 2-sentence executive summary explaining this to a CFO.
Narrative:
""",
input_variables=["currency", "amount", "source", "dest", "deviation_type", "expected", "actual", "impact_pct"]
)
# In production, this calls an LLM API
narrative = llm_client.generate(prompt.format(**anomaly))
return narrative
def evaluate_alert_cadence(self, anomaly, narrative):
"""
Determines if the CFO needs to know NOW or in the morning.
"""
severity = "LOW"
# Business Logic for Alerting
if anomaly['impact_pct'] > 20 or anomaly['type'] == 'FRAUD_SUSPECT':
severity = "CRITICAL"
channel = "SMS + Voice Call"
elif anomaly['impact_pct'] > 5:
severity = "HIGH"
channel = "Slack/Teams"
else:
severity = "INFO"
channel = "Daily Digest Email"
if severity in ["CRITICAL", "HIGH"]:
self.trigger_alert(anomaly, narrative, channel)
def trigger_alert(self, anomaly, narrative, channel):
payload = {
"title": f"⚠️ Liquidity Anomaly: {anomaly['entity']}",
"narrative": narrative,
"drill_down_link": f"dashboard/twin/view/{anomaly['id']}",
"timestamp": datetime.now().isoformat()
}
send_cfo_alert(channel, payload)
# --- Main Execution Loop (Simulated) ---
if __name__ == "__main__":
twin = CashTwinEngine()
# 1. Ingest Data
swift_data = get_swift_gpi_updates() # e.g., "Payment Accepted"
bank_data = get_bank_balances() # e.g., "Current Balance $5M"
erp_data = get_sap_forecast() # e.g., "Payroll due in 2 days"
twin.ingest_streams(swift_data, bank_data, erp_data)
# 2. Analyze
anomalies = twin.detect_anomalies()
# 3. Act
for index, row in anomalies.iterrows():
story = twin.generate_narrative(row)
twin.evaluate_alert_cadence(row, story)