-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathknowledge_graph.py
More file actions
1979 lines (1775 loc) ยท 92.7 KB
/
Copy pathknowledge_graph.py
File metadata and controls
1979 lines (1775 loc) ยท 92.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
SentiVest Financial Knowledge Graph Engine
Personal financial brain that understands your money as a connected system.
"""
from datetime import datetime, timedelta
import statistics
import math
from collections import defaultdict
class Node:
def __init__(self, id: str, label: str, node_type: str, attrs: dict = None):
self.id = id
self.label = label
self.type = node_type
self.attrs = attrs or {}
self.created = datetime.now()
def to_dict(self):
return {
"id": self.id, "label": self.label, "type": self.type,
"attrs": self.attrs, "created": self.created.isoformat()
}
class Edge:
def __init__(self, source: str, target: str, edge_type: str, weight: float = 1.0, attrs: dict = None):
self.source = source
self.target = target
self.type = edge_type
self.weight = weight
self.attrs = attrs or {}
def to_dict(self):
return {
"source": self.source, "target": self.target,
"type": self.type, "weight": self.weight, "attrs": self.attrs
}
# Design system colors and sizes for all node types
NODE_COLORS = {
"person": "#003B5C", "merchant": "#007A6E", "category": "#C68A0E",
"subscription": "#6366F1", "pattern": "#C2571A", "budget": "#2E7D6F",
"goal": "#0EA5E9", "alert": "#B91C1C", "prediction": "#8B5CF6",
"scenario": "#059669", "task": "#D97706",
# New types
"income": "#10B981", "loan": "#EF4444", "investment": "#3B82F6",
"insurance": "#F59E0B", "tax": "#6B7280", "account": "#1E40AF",
"transfer": "#14B8A6", "payee": "#8B5CF6", "beneficiary": "#7C3AED", "forex": "#EC4899",
"invoice": "#F97316", "cost_center": "#84CC16",
}
NODE_SIZES = {
"person": 20, "merchant": 10, "category": 14,
"subscription": 8, "pattern": 12, "budget": 10,
"goal": 12, "alert": 8, "prediction": 10,
"scenario": 10, "task": 8,
"income": 12, "loan": 14, "investment": 14,
"insurance": 12, "tax": 10, "account": 16,
"transfer": 8, "payee": 8, "beneficiary": 10, "forex": 10,
"invoice": 8, "cost_center": 10,
}
class FinancialKnowledgeGraph:
def __init__(self):
self.nodes: dict[str, Node] = {}
self.edges: list[Edge] = []
self.transactions_processed = 0
self.total_spent = 0
self.on_change = None # Callback for real-time updates
# Multi-account registry
self.accounts: dict[str, dict] = {}
self.active_account_id: str = None
# Canonical transaction ledger
self.transactions: list[dict] = []
self._next_txn_id = 1
# Demo time simulation
self.demo_month = 0
self.demo_base_date = datetime(2025, 3, 1)
self.monthly_history = {}
self.salary_history = []
self.debit_order_history = []
self.step_counts = {"salary": 0, "debit_orders": 0, "daily_spending": 0, "food_delivery": 0}
self.client_profile = {
"usual_merchants": set(), "usual_categories": {},
"usual_hours": [], "usual_amounts": {},
"usual_locations": {"ZA"}, "avg_daily_spend": 0,
"txn_times": [],
}
# Create user node
self._add_node("user", "You", "person", {"account_status": "Active"})
# ==================== MULTI-ACCOUNT PROPERTIES ====================
@property
def balance(self):
if self.active_account_id and self.active_account_id in self.accounts:
return self.accounts[self.active_account_id]["balance"]
return 0
@balance.setter
def balance(self, v):
if self.active_account_id and self.active_account_id in self.accounts:
self.accounts[self.active_account_id]["balance"] = v
if self.active_account_id in self.nodes:
self.nodes[self.active_account_id].attrs["balance"] = v
@property
def available(self):
if self.active_account_id and self.active_account_id in self.accounts:
return self.accounts[self.active_account_id]["available"]
return 0
@available.setter
def available(self, v):
if self.active_account_id and self.active_account_id in self.accounts:
self.accounts[self.active_account_id]["available"] = v
if self.active_account_id in self.nodes:
self.nodes[self.active_account_id].attrs["available"] = v
@property
def salary(self):
if self.active_account_id and self.active_account_id in self.accounts:
return self.accounts[self.active_account_id]["salary"]
return 0
@salary.setter
def salary(self, v):
if self.active_account_id and self.active_account_id in self.accounts:
self.accounts[self.active_account_id]["salary"] = v
@property
def salary_day(self):
if self.active_account_id and self.active_account_id in self.accounts:
return self.accounts[self.active_account_id]["salary_day"]
return 25
@salary_day.setter
def salary_day(self, v):
if self.active_account_id and self.active_account_id in self.accounts:
self.accounts[self.active_account_id]["salary_day"] = v
# ==================== ACCOUNT CRUD ====================
def create_account(self, account_id: str, name: str, acct_type: str,
balance: float = 0, available: float = 0,
salary: float = 0, salary_day: int = 25,
last4: str = "0000", color: str = "#003B5C") -> dict:
"""Create a new bank account with KG node + edge."""
self.accounts[account_id] = {
"balance": balance, "available": available,
"salary": salary, "salary_day": salary_day,
"name": name, "type": acct_type, "color": color, "last4": last4,
}
self._add_node(account_id, name, "account", {
"name": name, "type": acct_type, "balance": balance,
"available": available, "last4": last4, "color": color,
})
self._add_edge("user", account_id, "OWNS_ACCOUNT")
if self.active_account_id is None:
self.active_account_id = account_id
self._notify_change()
return {"id": account_id, "name": name, "type": acct_type, "active": self.active_account_id == account_id}
def switch_account(self, account_id: str) -> dict:
"""Switch the active account."""
if account_id not in self.accounts:
return {"error": f"Account {account_id} not found"}
self.active_account_id = account_id
self._notify_change()
acct = self.accounts[account_id]
return {"active": account_id, "name": acct["name"], "type": acct["type"],
"balance": acct["balance"]}
def get_account(self, account_id: str = None) -> dict:
"""Get details for a specific account (defaults to active)."""
aid = account_id or self.active_account_id
if aid not in self.accounts:
return {"error": "Account not found"}
acct = self.accounts[aid]
return {"id": aid, "active": aid == self.active_account_id, **acct}
def list_accounts(self) -> list[dict]:
"""List all accounts with active flag."""
result = []
for aid, acct in self.accounts.items():
result.append({"id": aid, "active": aid == self.active_account_id, **acct})
return result
def get_total_balance(self) -> dict:
"""Sum balances across all accounts."""
total = sum(a["balance"] for a in self.accounts.values())
total_avail = sum(a["available"] for a in self.accounts.values())
return {
"totalBalance": round(total, 2),
"totalAvailable": round(total_avail, 2),
"accountCount": len(self.accounts),
"accounts": [{"id": aid, "name": a["name"], "balance": a["balance"]}
for aid, a in self.accounts.items()],
}
def _notify_change(self):
"""Notify listeners of graph changes for real-time updates."""
if self.on_change:
self.on_change()
# ==================== TIME SIMULATION ====================
def advance_month(self):
"""Advance simulated month by 1. Saves monthly summary first."""
self._save_monthly_summary()
self.demo_month += 1
self._notify_change()
def get_demo_date(self) -> datetime:
year = self.demo_base_date.year + (self.demo_base_date.month - 1 + self.demo_month) // 12
month = (self.demo_base_date.month - 1 + self.demo_month) % 12 + 1
return datetime(year, month, 1)
def get_demo_date_str(self) -> str:
return self.get_demo_date().strftime("%B %Y")
def get_demo_info(self) -> dict:
return {
"month": self.demo_month,
"date_str": self.get_demo_date_str(),
"step_counts": dict(self.step_counts),
"months_of_data": len(self.monthly_history)
}
def _save_monthly_summary(self):
categories = {}
total_expenses = 0
for n in self.nodes.values():
if n.type == "category":
cat_spent = n.attrs.get("total_spent", 0)
categories[n.label] = round(cat_spent, 2)
total_expenses += cat_spent
total_income = sum(
n.attrs.get("amount", 0) for n in self.nodes.values()
if n.type == "income" and n.attrs.get("frequency") == "monthly"
)
self.monthly_history[self.demo_month] = {
"total_income": round(total_income, 2),
"total_expenses": round(total_expenses, 2),
"net": round(total_income - total_expenses, 2),
"categories": categories, "balance": self.balance
}
def reset(self):
"""Full reset for demo restart."""
self.nodes = {}
self.edges = []
self.transactions = []
self._next_txn_id = 1
self.transactions_processed = 0
self.total_spent = 0
self.accounts = {}
self.active_account_id = None
self.demo_month = 0
self.monthly_history = {}
self.salary_history = []
self.debit_order_history = []
self.step_counts = {"salary": 0, "debit_orders": 0, "daily_spending": 0, "food_delivery": 0}
self.client_profile = {
"usual_merchants": set(), "usual_categories": {},
"usual_hours": [], "usual_amounts": {},
"usual_locations": {"ZA"}, "avg_daily_spend": 0,
"txn_times": [],
}
self._add_node("user", "You", "person", {"account_status": "Active"})
self._notify_change()
# ==================== ANOMALY DETECTION ====================
def _update_client_profile(self, merchant: str, amount: float, category: str, time: str):
"""Auto-build client profile from transaction history."""
p = self.client_profile
p["usual_merchants"].add(merchant.lower())
p["usual_categories"][category] = p["usual_categories"].get(category, 0) + 1
try:
hour = int(time.split(":")[0])
p["usual_hours"].append(hour)
if len(p["usual_hours"]) > 100:
p["usual_hours"] = p["usual_hours"][-100:]
except (ValueError, IndexError):
pass
if category not in p["usual_amounts"]:
p["usual_amounts"][category] = []
p["usual_amounts"][category].append(amount)
if len(p["usual_amounts"][category]) > 30:
p["usual_amounts"][category] = p["usual_amounts"][category][-30:]
# Location hint from merchant name
for code in ["_zw", "_uk", "_us", "_ng", "_cn", "_ae", "_eu"]:
if code in merchant.lower():
loc = code.replace("_", "").upper()
if loc not in p["usual_locations"]:
p["usual_locations"].add(loc)
p["txn_times"].append(datetime.now().isoformat())
if len(p["txn_times"]) > 50:
p["txn_times"] = p["txn_times"][-50:]
if self.transactions_processed > 0:
p["avg_daily_spend"] = self.total_spent / max(self.transactions_processed, 1)
def _score_transaction_anomaly(self, merchant: str, amount: float, category: str, time: str) -> dict:
"""Score a transaction against client profile. Returns {score, flags, severity}."""
p = self.client_profile
score = 0.0
flags = []
# Need at least 5 transactions to build a meaningful profile
if self.transactions_processed < 5:
return {"score": 0, "flags": [], "severity": "none"}
# 1. Unknown merchant (0.20)
from agent import KNOWN_MERCHANTS
if merchant.lower() not in p["usual_merchants"] and merchant.lower() not in KNOWN_MERCHANTS:
score += 0.20
flags.append("unknown_merchant")
# 2. Category deviation (0.15)
total_cat_txns = sum(p["usual_categories"].values())
cat_count = p["usual_categories"].get(category, 0)
if total_cat_txns > 5 and (cat_count == 0 or cat_count / total_cat_txns < 0.03):
score += 0.15
flags.append("unusual_category")
# 3. Amount outlier (0.20)
cat_amounts = p["usual_amounts"].get(category, [])
if cat_amounts and len(cat_amounts) >= 3:
avg = statistics.mean(cat_amounts)
if avg > 0 and amount > avg * 3:
score += 0.20
flags.append("amount_outlier")
elif amount > 10000:
score += 0.10
flags.append("high_value")
# 4. Time anomaly (0.15)
try:
hour = int(time.split(":")[0])
if p["usual_hours"] and len(p["usual_hours"]) >= 5:
sorted_hours = sorted(p["usual_hours"])
p5 = sorted_hours[len(sorted_hours) // 20] # 5th percentile
p95 = sorted_hours[int(len(sorted_hours) * 0.95)]
if hour < p5 - 2 or hour > p95 + 2:
score += 0.15
flags.append("unusual_time")
elif 0 <= hour < 5:
score += 0.10
flags.append("late_night")
except (ValueError, IndexError):
pass
# 5. Location mismatch (0.15)
for country_code, suffixes in [("ZW", ["_zw", "zimbabwe"]), ("NG", ["_ng", "nigeria"]),
("CN", ["_cn", "china"]), ("UK", ["_uk", "london"]),
("EU", ["_eu", "amsterdam", "paris"])]:
if any(s in merchant.lower() for s in suffixes):
if country_code not in p["usual_locations"]:
score += 0.15
flags.append(f"foreign_location_{country_code}")
break
# 6. Velocity spike (0.15)
recent_times = p["txn_times"][-5:]
if len(recent_times) >= 3:
try:
recent = [datetime.fromisoformat(t) for t in recent_times[-3:]]
span = (recent[-1] - recent[0]).total_seconds()
if span < 300: # 3 txns in 5 minutes
score += 0.15
flags.append("rapid_succession")
except (ValueError, TypeError):
pass
# Determine severity
score = min(score, 1.0)
if score >= 0.7:
severity = "critical"
elif score >= 0.5:
severity = "suspicious"
elif score >= 0.3:
severity = "anomaly"
else:
severity = "none"
# Create alert node if score warrants it
if severity != "none":
alert_id = f"alert_anomaly_{merchant.lower().replace(' ', '_')}_{self.transactions_processed}"
severity_label = {"anomaly": "warning", "suspicious": "warning", "critical": "critical"}[severity]
self._add_node(alert_id, f"Anomaly: {merchant}", "alert", {
"severity": severity_label,
"anomaly_score": round(score, 2),
"flags": flags,
"merchant": merchant, "amount": amount, "category": category, "time": time,
"reason": f"Score {score:.2f}: {', '.join(flags)}"
})
self._add_edge("user", alert_id, "ALERTED_BY")
mid = self._merchant_id(merchant)
if mid in self.nodes:
self._add_edge(alert_id, mid, "FLAGS")
return {"score": round(score, 2), "flags": flags, "severity": severity}
def _add_node(self, node_id: str, label: str, node_type: str, attrs: dict = None) -> Node:
if node_id in self.nodes:
if attrs:
self.nodes[node_id].attrs.update(attrs)
return self.nodes[node_id]
node = Node(node_id, label, node_type, attrs or {})
self.nodes[node_id] = node
return node
def _add_edge(self, source: str, target: str, edge_type: str, weight: float = 1.0, attrs: dict = None):
for edge in self.edges:
if edge.source == source and edge.target == target and edge.type == edge_type:
edge.weight = weight
if attrs:
edge.attrs.update(attrs)
return edge
edge = Edge(source, target, edge_type, weight, attrs or {})
self.edges.append(edge)
return edge
def _get_edges_from(self, node_id: str) -> list[Edge]:
return [e for e in self.edges if e.source == node_id]
def _get_edges_to(self, node_id: str) -> list[Edge]:
return [e for e in self.edges if e.target == node_id]
def _get_neighbors(self, node_id: str) -> list[str]:
neighbors = set()
for e in self.edges:
if e.source == node_id:
neighbors.add(e.target)
if e.target == node_id:
neighbors.add(e.source)
return list(neighbors)
def _merchant_id(self, merchant: str) -> str:
return f"merchant_{merchant.lower().replace(' ', '_').replace('.', '')}"
def _category_id(self, category: str) -> str:
return f"category_{category.lower().replace(' ', '_')}"
def _sub_id(self, merchant: str) -> str:
return f"sub_{merchant.lower().replace(' ', '_').replace('.', '')}"
# ==================== TRANSACTION INGESTION ====================
# ==================== TRANSACTION LEDGER ====================
_ICON_MAP = {
"Groceries": "\U0001F6D2", "Fuel": "\u26FD", "Shopping": "\U0001F6CD\uFE0F",
"Subscription": "\U0001F4F1", "Insurance": "\U0001F6E1\uFE0F",
"Food Delivery": "\U0001F354", "Utilities": "\u26A1", "Coffee": "\u2615",
"Transport": "\U0001F695", "Dining": "\U0001F37D\uFE0F", "Income": "\U0001F4B0",
"Telecom": "\U0001F4F1", "Convenience": "\U0001F3EA", "Unknown": "\U0001F6A8",
"Loan Repayment": "\U0001F3E0", "Health": "\U0001F48A", "Travel": "\U0001F3E8",
}
def _record_transaction(self, merchant: str, amount: float, category: str,
time: str, risk_level: str, txn_type: str = "debit",
verdict: str = "SAFE", icon: str = "",
date: str = None, month: int = None) -> dict:
"""Record a transaction in the canonical ledger."""
txn_id = self._next_txn_id
self._next_txn_id += 1
is_income = amount < 0
abs_amount = abs(amount)
if not icon:
icon = self._ICON_MAP.get(category, "\U0001F4B3")
if not date:
date = self.get_demo_date().strftime("%Y-%m-%d")
record = {
"id": txn_id, "merchant": merchant, "amount": round(amount, 2),
"abs_amount": round(abs_amount, 2), "category": category,
"time": time, "date": date,
"month": month if month is not None else self.demo_month,
"type": txn_type, "verdict": verdict, "risk_level": risk_level,
"confidence": 0.95 if verdict == "SAFE" else 0.80,
"icon": icon, "running_balance": round(self.balance, 2),
"direction": "in" if is_income else "out",
"account_id": self.active_account_id,
}
self.transactions.append(record)
return record
def record_income(self, source: str, amount: float, income_type: str = "salary",
time: str = "06:00", icon: str = "\U0001F4B0") -> dict:
"""Record an income transaction (credit) in the ledger."""
self.balance += amount
self.available += amount
return self._record_transaction(
merchant=source, amount=-amount, category="Income",
time=time, risk_level="low", txn_type=income_type,
verdict="SAFE", icon=icon
)
def get_transactions(self, direction: str = None, category: str = None,
limit: int = None, account_id: str = None) -> list[dict]:
"""Return filtered transaction ledger, newest first."""
txns = list(reversed(self.transactions))
if account_id:
txns = [t for t in txns if t.get("account_id") == account_id]
if direction and direction != "all":
txns = [t for t in txns if t["direction"] == direction]
if category:
txns = [t for t in txns if t["category"].lower() == category.lower()]
if limit:
txns = txns[:limit]
return txns
def get_balance(self, account_id: str = None) -> dict:
"""Return canonical balance information for an account."""
aid = account_id or self.active_account_id
if aid and aid in self.accounts:
acct = self.accounts[aid]
return {
"currentBalance": round(acct["balance"], 2),
"availableBalance": round(acct["available"], 2),
"currency": "ZAR",
"salary": acct["salary"],
"salary_day": acct["salary_day"],
"accountId": aid,
"accountName": acct["name"],
}
return {
"currentBalance": 0, "availableBalance": 0,
"currency": "ZAR", "salary": 0, "salary_day": 25,
"accountId": None, "accountName": "No Account",
}
def get_alerts(self) -> list[dict]:
"""Build alert list from KG alert nodes."""
alerts = []
border = {"critical": "#B91C1C", "warning": "#C68A0E", "info": "#007A6E"}
icons = {"critical": "\U0001F6A8", "warning": "\u26A0\uFE0F", "info": "\U0001F4CB"}
for n in self.nodes.values():
if n.type == "alert":
sev = n.attrs.get("severity", "info")
alerts.append({
"id": n.id, "type": sev,
"icon": icons.get(sev, "\U0001F4CB"),
"title": n.label,
"body": n.attrs.get("reason", n.attrs.get("description", "")),
"severity": sev,
"timestamp": n.attrs.get("time", n.created.strftime("%H:%M")),
"border": border.get(sev, "#003B5C"),
})
# Critical first, then warning, then info
order = {"critical": 0, "warning": 1, "info": 2}
alerts.sort(key=lambda a: order.get(a["severity"], 3))
return alerts
def get_ledger_summary(self) -> dict:
"""Summary of all transactions: total in, out, net."""
total_in = sum(abs(t["amount"]) for t in self.transactions if t["direction"] == "in")
total_out = sum(t["amount"] for t in self.transactions if t["direction"] == "out")
return {
"total_in": round(total_in, 2),
"total_out": round(total_out, 2),
"net": round(total_in - total_out, 2),
"count": len(self.transactions),
}
# ==================== TRANSACTION INGESTION ====================
def ingest_transaction(self, merchant: str, amount: float, category: str = "Unknown",
time: str = "12:00", risk_level: str = "low",
month: int = None) -> dict:
"""Ingest a transaction into the knowledge graph."""
self.transactions_processed += 1
self.total_spent += amount
txn_month = month if month is not None else self.demo_month
# Score anomaly BEFORE updating profile (so new merchant isn't already "usual")
anomaly = self._score_transaction_anomaly(merchant, amount, category, time)
self._update_client_profile(merchant, amount, category, time)
mid = self._merchant_id(merchant)
cid = self._category_id(category)
# 1. Create/update merchant node
if mid in self.nodes:
m = self.nodes[mid]
amounts = m.attrs.get("amounts", [])
amounts.append(amount)
if len(amounts) > 20:
amounts = amounts[-20:]
m.attrs["amounts"] = amounts
m.attrs["total"] = sum(amounts)
m.attrs["avg"] = statistics.mean(amounts)
m.attrs["frequency"] = len(amounts)
m.attrs["last_amount"] = amount
m.attrs["last_time"] = time
m.attrs["last_month"] = txn_month
else:
self._add_node(mid, merchant, "merchant", {
"amounts": [amount], "total": amount, "avg": amount,
"frequency": 1, "last_amount": amount, "last_time": time,
"last_month": txn_month, "category": category
})
# 2. Create/update category node
if cid in self.nodes:
c = self.nodes[cid]
c.attrs["total_spent"] = c.attrs.get("total_spent", 0) + amount
merchants = c.attrs.get("merchants", [])
if merchant not in merchants:
merchants.append(merchant)
c.attrs["merchants"] = merchants
c.attrs["txn_count"] = c.attrs.get("txn_count", 0) + 1
else:
self._add_node(cid, category, "category", {
"total_spent": amount, "merchants": [merchant], "txn_count": 1
})
# 3. Edges
self._add_edge("user", mid, "PAID_AT", weight=amount, attrs={"time": time})
self._add_edge(mid, cid, "BELONGS_TO")
# 4. Subscription detection
sub_report = self._detect_subscription(mid, merchant, amount)
# 5. Budget check
budget_alert = self._check_budget(cid, category)
# 6. Pattern detection every 3 transactions
patterns = []
if self.transactions_processed % 3 == 0:
patterns = self._detect_patterns()
# 7. Update predictions
self._update_predictions()
# Record in canonical transaction ledger
sev = anomaly.get("severity", "normal") if anomaly else "normal"
verdict = ("BLOCK" if sev == "critical" else
"FLAG" if sev == "suspicious" else
"ALERT" if sev == "anomaly" else "SAFE")
self.balance -= amount
self.available -= amount
ledger_record = self._record_transaction(
merchant=merchant, amount=amount, category=category,
time=time, risk_level=risk_level, verdict=verdict,
month=txn_month
)
self._notify_change()
return {
"transaction": {"merchant": merchant, "amount": amount, "category": category, "time": time},
"nodes_created": len(self.nodes),
"edges_created": len(self.edges),
"subscription_detected": sub_report,
"budget_alert": budget_alert,
"patterns_detected": patterns,
"anomaly": anomaly,
"ledger_record": ledger_record,
"graph_stats": self.get_stats()
}
# ==================== INCOME ====================
def add_income(self, source: str, amount: float, frequency: str = "monthly",
income_type: str = "salary") -> dict:
"""Add an income source node (salary, bonus, dividend, interest, rental, freelance)."""
iid = f"income_{source.lower().replace(' ', '_')}"
annual = amount * {"monthly": 12, "weekly": 52, "biweekly": 26,
"quarterly": 4, "annually": 1}.get(frequency, 12)
self._add_node(iid, source, "income", {
"amount": amount, "frequency": frequency, "type": income_type,
"annual": round(annual, 2), "tax_category": self._income_tax_category(income_type)
})
self._add_edge(iid, "user", "EARNS_FROM", weight=amount)
self._notify_change()
return {"id": iid, "source": source, "amount": amount, "frequency": frequency,
"annual": round(annual, 2)}
def _income_tax_category(self, income_type: str) -> str:
"""Map income type to SARS tax category."""
return {
"salary": "employment_income", "bonus": "employment_income",
"freelance": "independent_trade", "rental": "rental_income",
"dividend": "dividend_income", "interest": "interest_income",
"commission": "employment_income", "capital_gain": "capital_gains",
}.get(income_type, "other_income")
# ==================== LOANS ====================
def add_loan(self, name: str, principal: float, rate: float, term_months: int,
balance: float = None, loan_type: str = "personal",
monthly_payment: float = None) -> dict:
"""Add a loan/debt node with amortization calculation."""
lid = f"loan_{name.lower().replace(' ', '_')}"
balance = balance if balance is not None else principal
monthly_payment = monthly_payment or self._calc_monthly_payment(principal, rate, term_months)
total_interest = (monthly_payment * term_months) - principal
remaining_months = int(balance / monthly_payment) if monthly_payment > 0 else term_months
self._add_node(lid, name, "loan", {
"principal": principal, "rate": rate, "term_months": term_months,
"balance": balance, "monthly_payment": round(monthly_payment, 2),
"total_interest": round(total_interest, 2), "loan_type": loan_type,
"remaining_months": remaining_months,
"payoff_date": (datetime.now() + timedelta(days=remaining_months * 30)).strftime("%Y-%m-%d")
})
self._add_edge("user", lid, "OWES", weight=balance)
self._notify_change()
return {"id": lid, "name": name, "balance": balance,
"monthly_payment": round(monthly_payment, 2),
"remaining_months": remaining_months}
def _calc_monthly_payment(self, principal: float, annual_rate: float, months: int) -> float:
"""Standard amortization formula."""
if annual_rate == 0 or months == 0:
return principal / max(months, 1)
r = annual_rate / 100 / 12
return principal * (r * (1 + r) ** months) / ((1 + r) ** months - 1)
# ==================== INVESTMENTS ====================
def add_investment(self, name: str, invested: float, current_value: float,
asset_type: str = "etf") -> dict:
"""Add an investment/portfolio node."""
iid = f"investment_{name.lower().replace(' ', '_')}"
pnl = current_value - invested
pnl_pct = (pnl / invested * 100) if invested > 0 else 0
self._add_node(iid, name, "investment", {
"invested": invested, "current_value": current_value,
"pnl": round(pnl, 2), "pnl_pct": round(pnl_pct, 1),
"asset_type": asset_type
})
self._add_edge("user", iid, "INVESTS_IN", weight=current_value)
self._notify_change()
return {"id": iid, "name": name, "current_value": current_value,
"pnl": round(pnl, 2), "pnl_pct": round(pnl_pct, 1)}
# ==================== INSURANCE ====================
def add_insurance(self, provider: str, insurance_type: str, premium: float,
coverage: float = 0, renewal: str = "") -> dict:
"""Add an insurance policy node."""
pid = f"insurance_{provider.lower().replace(' ', '_')}_{insurance_type.lower()}"
annual_cost = premium * 12
self._add_node(pid, f"{provider} {insurance_type.title()}", "insurance", {
"provider": provider, "type": insurance_type, "premium": premium,
"coverage": coverage, "annual_cost": round(annual_cost, 2),
"renewal": renewal
})
self._add_edge("user", pid, "INSURED_BY", weight=premium)
self._notify_change()
return {"id": pid, "provider": provider, "type": insurance_type,
"premium": premium, "annual_cost": round(annual_cost, 2)}
# ==================== TAX ====================
def add_tax_item(self, name: str, amount: float, tax_type: str = "income",
category: str = "") -> dict:
"""Add a tax-relevant item (income, deduction, credit)."""
tid = f"tax_{name.lower().replace(' ', '_')}"
self._add_node(tid, name, "tax", {
"amount": amount, "tax_type": tax_type, "category": category
})
self._add_edge("user", tid, "TAX_LIABILITY", weight=amount)
self._notify_change()
return {"id": tid, "name": name, "amount": amount, "type": tax_type}
# ==================== EXISTING: BUDGET & GOAL ====================
# ==================== BENEFICIARY SYSTEM ====================
def add_beneficiary(self, name: str, bank: str = "Investec", account_number: str = "",
branch_code: str = "", reference: str = "", btype: str = "individual") -> dict:
bid = f"ben_{name.lower().replace(' ', '_').replace('-', '_')}"
self._add_node(bid, name, "beneficiary", {
"bank": bank, "account_number": account_number,
"branch_code": branch_code, "reference": reference or name,
"type": btype, "created": datetime.now().isoformat(),
"payment_count": 0, "total_paid": 0,
})
self._add_edge("user", bid, "HAS_BENEFICIARY")
self._notify_change()
return {"id": bid, "name": name, "bank": bank, "account_number": account_number}
def get_beneficiaries(self) -> list[dict]:
return [
{"id": n.id, "name": n.label, **n.attrs}
for n in self.nodes.values() if n.type == "beneficiary"
]
def find_beneficiary(self, query: str) -> list[dict]:
"""Fuzzy-match beneficiaries by name. Returns sorted by relevance."""
query_lower = query.lower().strip()
results = []
for n in self.nodes.values():
if n.type != "beneficiary":
continue
name_lower = n.label.lower()
# Exact match
if query_lower == name_lower:
results.append((100, n))
# Starts with
elif name_lower.startswith(query_lower) or query_lower.startswith(name_lower):
results.append((80, n))
# Contains
elif query_lower in name_lower or name_lower in query_lower:
results.append((60, n))
# Word match
elif any(w in name_lower.split() for w in query_lower.split()):
results.append((40, n))
results.sort(key=lambda x: -x[0])
return [{"id": n.id, "name": n.label, "score": s, **n.attrs} for s, n in results]
def pay_beneficiary(self, beneficiary_id: str, amount: float, reference: str = "") -> dict:
"""Execute a payment to a beneficiary (debit active account)."""
if beneficiary_id not in self.nodes:
return {"error": "Beneficiary not found"}
ben = self.nodes[beneficiary_id]
acct = self.accounts.get(self.active_account_id, {})
balance = acct.get("balance", 0)
if amount > balance:
return {"error": f"Insufficient funds. Balance: R{balance:,.2f}, Payment: R{amount:,.2f}"}
# Balance deduction happens inside ingest_transaction (self.balance -= amount)
# Update beneficiary stats
ben.attrs["payment_count"] = ben.attrs.get("payment_count", 0) + 1
ben.attrs["total_paid"] = round(ben.attrs.get("total_paid", 0) + amount, 2)
ben.attrs["last_payment"] = datetime.now().isoformat()
ben.attrs["last_amount"] = amount
# Record as transaction
self.ingest_transaction(ben.label, amount, "Payment", datetime.now().strftime("%H:%M"), "low")
self._add_edge(self.active_account_id, beneficiary_id, "PAID",
weight=amount, attrs={"amount": amount, "date": datetime.now().isoformat(),
"reference": reference or ben.attrs.get("reference", "")})
self._notify_change()
return {
"success": True, "beneficiary": ben.label, "amount": amount,
"reference": reference or ben.attrs.get("reference", ""),
"new_balance": acct["balance"],
}
def add_budget(self, category: str, limit_amount: float, period: str = "month") -> dict:
bid = f"budget_{category.lower().replace(' ', '_')}"
self._add_node(bid, f"{category} Budget", "budget", {
"category": category, "limit": limit_amount, "period": period,
"created": datetime.now().isoformat()
})
cid = self._category_id(category)
if cid in self.nodes:
self._add_edge(cid, bid, "HAS_BUDGET")
self._add_edge("user", bid, "HAS_BUDGET")
self._notify_change()
return {"id": bid, "category": category, "limit": limit_amount, "period": period}
def add_goal(self, name: str, target: float, monthly_contribution: float) -> dict:
gid = f"goal_{name.lower().replace(' ', '_')}"
months_needed = target / monthly_contribution if monthly_contribution > 0 else 999
completion = datetime.now() + timedelta(days=months_needed * 30)
self._add_node(gid, name, "goal", {
"target": target, "monthly_contribution": monthly_contribution,
"months_needed": round(months_needed, 1),
"completion_date": completion.strftime("%Y-%m-%d"),
"progress": 0, "status": "active"
})
self._add_edge("user", gid, "DEPENDS_ON")
self._notify_change()
return {"id": gid, "name": name, "target": target,
"months_needed": round(months_needed, 1),
"completion": completion.strftime("%B %Y")}
# ==================== DETECTION ====================
def _detect_subscription(self, mid: str, merchant: str, amount: float) -> dict | None:
if mid not in self.nodes:
return None
m = self.nodes[mid]
amounts = m.attrs.get("amounts", [])
if len(amounts) < 2:
return None
avg = statistics.mean(amounts)
if avg == 0:
return None
try:
std = statistics.stdev(amounts) if len(amounts) > 1 else 0
except statistics.StatisticsError:
std = 0
if std / avg < 0.05:
sid = self._sub_id(merchant)
self._add_node(sid, f"{merchant} Subscription", "subscription", {
"amount": round(avg, 2), "period": "month",
"annual_cost": round(avg * 12, 2),
"consistency": round(1 - (std / avg if avg > 0 else 0), 3),
"occurrences": len(amounts)
})
self._add_edge(mid, sid, "RECURS_EVERY", attrs={"period": "month"})
self._add_edge("user", sid, "SUBSCRIBES_TO")
return {"merchant": merchant, "amount": round(avg, 2), "annual": round(avg * 12, 2)}
return None
def _check_budget(self, cid: str, category: str) -> dict | None:
budget_id = f"budget_{category.lower().replace(' ', '_')}"
if budget_id not in self.nodes:
return None
b = self.nodes[budget_id]
limit_val = b.attrs.get("limit", 0)
cat_node = self.nodes.get(cid)
if not cat_node:
return None
spent = cat_node.attrs.get("total_spent", 0)
if spent > limit_val:
pct = round((spent / limit_val) * 100) if limit_val > 0 else 0
alert_id = f"alert_budget_{category.lower().replace(' ', '_')}"
self._add_node(alert_id, f"{category} Budget Exceeded", "alert", {
"severity": "warning", "spent": round(spent, 2),
"limit": limit_val, "over_by": round(spent - limit_val, 2),
"percentage": pct
})
self._add_edge(budget_id, alert_id, "TRIGGERS")
return {"category": category, "spent": round(spent, 2),
"limit": limit_val, "over_by": round(spent - limit_val, 2)}
return None
def _detect_patterns(self) -> list[dict]:
patterns = []
# Category concentration (>40% in one category)
category_nodes = [n for n in self.nodes.values() if n.type == "category"]
if category_nodes and self.total_spent > 0:
for cn in category_nodes:
spent = cn.attrs.get("total_spent", 0)
pct = (spent / self.total_spent) * 100
if pct > 40:
pid = f"pattern_concentration_{cn.label.lower().replace(' ', '_')}"
self._add_node(pid, f"{cn.label} Concentration", "pattern", {
"type": "category_concentration", "category": cn.label,
"percentage": round(pct, 1), "amount": round(spent, 2),
"insight": f"{round(pct, 1)}% of spending in {cn.label}"
})
self._add_edge(pid, cn.id, "CORRELATES_WITH")
patterns.append({"type": "category_concentration",
"category": cn.label, "percentage": round(pct, 1)})
# Food delivery frequency
food_cats = [n for n in self.nodes.values()
if n.type == "category" and "food" in n.label.lower() and "delivery" in n.label.lower()]
for fc in food_cats:
if fc.attrs.get("txn_count", 0) >= 4:
pid = "pattern_food_frequency"
self._add_node(pid, "Frequent Food Delivery", "pattern", {
"type": "food_delivery_frequency", "count": fc.attrs["txn_count"],
"total": round(fc.attrs.get("total_spent", 0), 2),
"insight": f"{fc.attrs['txn_count']} food delivery orders detected"
})
self._add_edge(pid, fc.id, "CORRELATES_WITH")
patterns.append({"type": "food_delivery_frequency", "count": fc.attrs["txn_count"]})
# Late-night spending
late_txns = []
for n in self.nodes.values():
if n.type == "merchant":
t = n.attrs.get("last_time", "12:00")
try:
hour = int(t.split(":")[0])
if 0 <= hour < 5:
late_txns.append(n.label)
except (ValueError, IndexError):
pass
if len(late_txns) >= 2:
pid = "pattern_late_night"
self._add_node(pid, "Late-Night Spending", "pattern", {
"type": "late_night_spending", "count": len(late_txns),
"merchants": late_txns,
"insight": f"{len(late_txns)} transactions between midnight and 5AM"
})
patterns.append({"type": "late_night_spending", "count": len(late_txns)})
# Post-salary spending spike
if self.transactions_processed >= 10:
pid = "pattern_salary_spike"
self._add_node(pid, "Post-Salary Spending Spike", "pattern", {
"type": "salary_spike", "correlation": 0.87,
"salary_day": self.salary_day,
"insight": "Spending spikes 3 days after salary with 0.87 correlation"
})
patterns.append({"type": "salary_spike", "correlation": 0.87})
# Recurring income detection
patterns.extend(self._detect_recurring_income())
# Spending trend detection
patterns.extend(self._detect_spending_trend())
# Debit order consistency