-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathllm_sections.py
More file actions
2169 lines (1878 loc) · 97.2 KB
/
llm_sections.py
File metadata and controls
2169 lines (1878 loc) · 97.2 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
import os
import io
import json
import time
import math
import hashlib
from typing import Any, Dict, List, Optional, Tuple
from dotenv import load_dotenv
from openai import OpenAI
load_dotenv()
# Public entrypoint:
# run_report_sections(questionnaire_id: int, client_facts: dict, model: Optional[str]) -> Dict[str, dict]
#
# Expectations:
# - client_facts is a compact JSON with:
# {
# "questionnaire_id": int,
# "personal": {"name": str, "age": number, "dependents_count": int},
# "income": {"annualIncome": number, "monthlyExpenses": number, "monthlyEmi": number},
# "insurance": {"lifeCover": number, "healthCover": number},
# "savings": {"savingsPercent": number},
# "goals": [{"name": str, "target_amount": number, "horizon_years": number}, ...],
# "bank": {"total_inflows": number, "total_outflows": number, "net_cashflow": number},
# "portfolio": {...} # optional
# "analysis": {
# "riskProfile": str,
# "advancedRisk": {...},
# "surplusBand": str,
# "insuranceGap": str,
# "debtStress": str,
# "liquidity": str,
# "ihs": {"band": str, "score": number, "breakdown": {...}},
# "_diagnostics": {"emiPct": number, "liquidityMonths": number, "requiredLifeCover": number}
# }
# }
OUTPUT_DIR = os.getenv("OUTPUT_DIR", "output")
SECTIONS_DIR_NAME = "sections"
DEFAULT_MODEL = os.getenv("LLM_MODEL", "gpt-5.2")
# ------------------------ Financial Assumptions (Configurable) ------------------------ #
# These assumptions are used for SIP calculations and are displayed in reports
ASSUMED_INFLATION_RATE = 0.06 # 6% annual inflation
ASSUMED_RETURNS = {
"aggressive": {"annual": 0.14, "monthly": 0.011, "label": "14% p.a. (Aggressive Equity)"},
"growth": {"annual": 0.114, "monthly": 0.009, "label": "11.4% p.a. (Growth/Balanced)"},
"moderate": {"annual": 0.114, "monthly": 0.009, "label": "11.4% p.a. (Moderate)"},
"conservative": {"annual": 0.074, "monthly": 0.006, "label": "7.4% p.a. (Conservative/Debt)"},
}
WITHDRAWAL_RATE_RETIREMENT = 0.07 # 7% safe withdrawal rate for retirement corpus
def _ensure_dir(path: str):
os.makedirs(path, exist_ok=True)
def _json_dumps(obj: Any) -> str:
return json.dumps(obj, ensure_ascii=False, sort_keys=True)
def _sha256_text(s: str) -> str:
return hashlib.sha256(s.encode("utf-8")).hexdigest()
def _now_ts() -> int:
return int(time.time())
def _coerce_float(x: Any, default: float = 0.0) -> float:
try:
if x is None:
return default
if isinstance(x, (int, float)):
return float(x)
sx = str(x).strip()
if sx == "":
return default
# strip commas and currency symbols
sx = sx.replace(",", "")
for sym in ["₹", "Rs.", "Rs", "$"]:
sx = sx.replace(sym, "")
if sx.endswith("-"):
sx = "-" + sx[:-1]
return float(sx)
except Exception:
return default
# ------------------------ LLM Client Wrapper ------------------------ #
class LLMClient:
def __init__(self, api_key: Optional[str] = None, model: Optional[str] = None, temperature: float = 0.2, request_timeout: int = 60):
self.api_key = api_key or os.getenv("OPENAI_API_KEY")
if not self.api_key:
raise RuntimeError("OPENAI_API_KEY is not set")
self.model = model or DEFAULT_MODEL
self.temperature = temperature
self.request_timeout = request_timeout
self._client = OpenAI(api_key=self.api_key)
def complete_json(self, system: str, user: str, retry_on_schema_error: bool = True) -> Tuple[Dict[str, Any], Dict[str, Any]]:
usage = {}
try:
resp = self._client.chat.completions.create(
model=self.model,
messages=[
{"role": "system", "content": system},
{"role": "user", "content": user},
],
response_format={"type": "json_object"},
temperature=self.temperature,
)
usage = {
"prompt_tokens": getattr(resp.usage, "prompt_tokens", None),
"completion_tokens": getattr(resp.usage, "completion_tokens", None),
"total_tokens": getattr(resp.usage, "total_tokens", None),
}
txt = resp.choices[0].message.content
data = json.loads(txt)
return data, usage
except Exception as e:
if retry_on_schema_error:
# One retry with a stricter reminder
try:
resp = self._client.chat.completions.create(
model=self.model,
messages=[
{"role": "system", "content": system},
{"role": "user", "content": user + "\n\nCRITICAL: Return STRICT valid JSON only. Do not include any text outside JSON."},
],
response_format={"type": "json_object"},
temperature=self.temperature,
)
usage = {
"prompt_tokens": getattr(resp.usage, "prompt_tokens", None),
"completion_tokens": getattr(resp.usage, "completion_tokens", None),
"total_tokens": getattr(resp.usage, "total_tokens", None),
}
txt = resp.choices[0].message.content
data = json.loads(txt)
return data, usage
except Exception as e2:
raise e2
raise e
# ------------------------ Base Section Runner ------------------------ #
class SectionRunner:
name: str = "base"
def __init__(self, llm: LLMClient, qid: int, base_dir: str):
self.llm = llm
self.qid = qid
self.base_dir = base_dir
def digest(self, facts: Dict[str, Any]) -> Dict[str, Any]:
# Must be implemented by subclasses
raise NotImplementedError
def prompt(self, digest: Dict[str, Any]) -> Tuple[str, str]:
# Returns (system, user)
raise NotImplementedError
def validate(self, obj: Dict[str, Any]) -> bool:
# Basic schema: title: str, bullets: list[str], paragraphs: list[str], actions: list[str]
if not isinstance(obj, dict):
return False
if "title" not in obj:
return False
for k in ["bullets", "paragraphs", "actions"]:
if k in obj and not isinstance(obj[k], list):
return False
return True
def run(self, facts: Dict[str, Any]) -> Optional[Dict[str, Any]]:
dg = self.digest(facts)
if dg is None:
return None
dg_str = _json_dumps(dg)
dg_hash = _sha256_text(dg_str)
sec_dir = os.path.join(self.base_dir, self.name)
_ensure_dir(sec_dir)
out_path = os.path.join(sec_dir, f"{self.name}.json")
# Cache check
if os.path.isfile(out_path):
try:
with open(out_path, "r", encoding="utf-8") as f:
cached = json.load(f)
if cached.get("_meta", {}).get("facts_hash") == dg_hash:
return cached.get("content")
except Exception:
pass
system, user = self.prompt(dg)
data, usage = self.llm.complete_json(system, user, retry_on_schema_error=True)
if not self.validate(data):
raise RuntimeError(f"Schema validation failed for section {self.name}")
payload = {
"_meta": {
"questionnaire_id": self.qid,
"section": self.name,
"model": self.llm.model,
"ts": _now_ts(),
"facts_hash": dg_hash,
"prompt": {
"system": system,
"user": user[:4000], # avoid huge files
},
"usage": usage,
},
"content": data,
}
with open(out_path, "w", encoding="utf-8") as f:
json.dump(payload, f, ensure_ascii=False, indent=2)
return data
# ------------------------ Helpers for Deterministic Goal Math ------------------------ #
def _choose_monthly_rate(final_category: Optional[str], horizon_years: Optional[float]) -> float:
"""Select monthly expected return based on risk category and horizon."""
cat = (final_category or "").lower()
h = float(horizon_years) if horizon_years not in (None, "") else None
# Use constants for rate selection
if cat in ["very aggressive", "aggressive"]:
base = ASSUMED_RETURNS["aggressive"]["monthly"]
elif cat in ["growth", "moderate"]:
base = ASSUMED_RETURNS["growth"]["monthly"]
else:
base = ASSUMED_RETURNS["conservative"]["monthly"]
# Short horizons use more conservative rates
if h is not None:
if h <= 3:
base = min(base, ASSUMED_RETURNS["conservative"]["monthly"])
elif h <= 7:
base = min(base, ASSUMED_RETURNS["growth"]["monthly"])
return base
def _get_return_assumptions(final_category: Optional[str], horizon_years: Optional[float]) -> Dict[str, Any]:
"""Get return assumptions for display in reports."""
cat = (final_category or "").lower()
h = float(horizon_years) if horizon_years not in (None, "") else None
if cat in ["very aggressive", "aggressive"]:
ret = ASSUMED_RETURNS["aggressive"]
elif cat in ["growth", "moderate"]:
ret = ASSUMED_RETURNS["growth"]
else:
ret = ASSUMED_RETURNS["conservative"]
# Adjust label for short horizon
effective_annual = ret["annual"]
if h is not None and h <= 3:
effective_annual = ASSUMED_RETURNS["conservative"]["annual"]
elif h is not None and h <= 7:
effective_annual = min(ret["annual"], ASSUMED_RETURNS["growth"]["annual"])
return {
"expected_return_percent": round(effective_annual * 100, 1),
"inflation_percent": round(ASSUMED_INFLATION_RATE * 100, 1),
"real_return_percent": round((effective_annual - ASSUMED_INFLATION_RATE) * 100, 1),
}
def compute_goal_priority(
horizon_years: Optional[float],
importance: Optional[str],
gap_exists: bool,
shortfall_percent: float = 0
) -> Tuple[int, str]:
"""
Compute goal priority score and tier.
Lower score = higher priority.
Returns: (priority_score, priority_tier)
Tiers: "Immediate" (<=3 yrs), "Short-term" (3-7 yrs), "Long-term" (>7 yrs)
"""
base_score = 100
# Importance factor (essential goals get highest priority)
imp = str(importance or "").strip().lower()
if imp == "essential":
base_score -= 40
elif imp == "important":
base_score -= 20
# lifestyle goals stay at base
# Horizon urgency (shorter horizon = higher priority)
tier = "Long-term"
if horizon_years:
h = float(horizon_years)
if h <= 3:
base_score -= 30
tier = "Immediate"
elif h <= 5:
base_score -= 20
tier = "Short-term"
elif h <= 7:
base_score -= 10
tier = "Short-term"
# Gap factor: achievable goals get slight priority boost
# But severely underfunded goals (>50% shortfall) need attention too
if not gap_exists:
base_score -= 10 # Achievable goals get priority
elif shortfall_percent > 50:
base_score -= 5 # Severely underfunded needs attention
return (base_score, tier)
def compute_goal_sip(target_amount: float, horizon_years: Optional[float], final_category: Optional[str]) -> Optional[float]:
try:
target = _coerce_float(target_amount, 0.0)
if target <= 0:
return None
n_years = float(horizon_years) if horizon_years not in (None, "") else None
if n_years is None or n_years <= 0:
return None
n = int(round(n_years * 12))
r = _choose_monthly_rate(final_category, n_years)
denom = (math.pow(1.0 + r, n) - 1.0)
if denom <= 0:
return None
sip = target * r / denom
return round(sip, 2)
except Exception:
return None
def compute_realistic_target(monthly_sip: float, horizon_years: Optional[float], final_category: Optional[str]) -> Optional[float]:
"""Calculate what target amount is achievable with available monthly SIP."""
try:
sip = _coerce_float(monthly_sip, 0.0)
if sip <= 0:
return None
n_years = float(horizon_years) if horizon_years not in (None, "") else None
if n_years is None or n_years <= 0:
return None
n = int(round(n_years * 12))
r = _choose_monthly_rate(final_category, n_years)
# Future Value of SIP: FV = P * [((1+r)^n - 1) / r]
fv = sip * ((math.pow(1.0 + r, n) - 1.0) / r)
return round(fv, 2)
except Exception:
return None
def compute_required_horizon(target_amount: float, monthly_sip: float, final_category: Optional[str]) -> Optional[float]:
"""Calculate years needed to reach target with given monthly SIP using iterative approximation."""
try:
target = _coerce_float(target_amount, 0.0)
sip = _coerce_float(monthly_sip, 0.0)
if target <= 0 or sip <= 0:
return None
# Binary search for the required horizon (in years)
low, high = 0.5, 50.0 # Search between 6 months and 50 years
for _ in range(50): # Max iterations
mid = (low + high) / 2.0
achievable = compute_realistic_target(sip, mid, final_category)
if achievable is None:
return None
if abs(achievable - target) < target * 0.01: # Within 1% tolerance
return round(mid, 1)
if achievable < target:
low = mid
else:
high = mid
return round((low + high) / 2.0, 1)
except Exception:
return None
def compute_goal_risk_category(
horizon_years: Optional[float],
risk_tolerance: Optional[str],
goal_importance: Optional[str],
goal_flexibility: Optional[str],
behavior: Optional[str] = None
) -> str:
"""
Compute risk category for a single goal based on its specific parameters.
Returns one of: 'Conservative', 'Moderate', 'Growth', 'Aggressive'
"""
# Base score from horizon (0-3)
horizon_score = 0
if horizon_years is not None:
try:
h = float(horizon_years)
if h < 3:
horizon_score = 0
elif h < 5:
horizon_score = 1
elif h < 7:
horizon_score = 2
else:
horizon_score = 3
except (ValueError, TypeError):
pass
# Tolerance score (0-2)
tol_map = {"low": 0, "medium": 1, "med": 1, "high": 2}
tol_score = tol_map.get(str(risk_tolerance).strip().lower(), 1)
# Importance adjustment (-1 to +1)
imp_map = {"essential": -1, "important": 0, "lifestyle": 1}
imp_adj = imp_map.get(str(goal_importance).strip().lower(), 0)
# Flexibility adjustment (-1 to +1)
flex_map = {"critical": -1, "fixed": 0, "flexible": 1}
flex_adj = flex_map.get(str(goal_flexibility).strip().lower(), 0)
# Behavior adjustment (-1 to +1)
behavior_map = {"sell": -1, "reduce": -1, "hold": 0, "buy": 1, "aggressive buy": 1, "aggressive_buy": 1}
behavior_adj = behavior_map.get(str(behavior).strip().lower(), 0) if behavior else 0
# Total score: horizon (0-3) + tolerance (0-2) + adjustments (-3 to +3) = range -3 to 8
total = horizon_score + tol_score + imp_adj + flex_adj + behavior_adj
# Map to category
if total <= 1:
return "Conservative"
elif total <= 3:
return "Moderate"
elif total <= 5:
return "Growth"
else:
return "Aggressive"
# ------------------------ Priority Allocation Engine ------------------------ #
def generate_bridge_recommendations(shortfall: float, current_surplus: float) -> List[Dict]:
"""
Generate specific recommendations to bridge the goal funding gap.
Called when user cannot afford all their goals with current surplus.
"""
if shortfall <= 0:
return []
recs = []
# Option 1: Reduce expenses
expense_reduction = shortfall
recs.append({
"option": "Reduce Expenses",
"amount": round(expense_reduction),
"action": f"Reduce monthly expenses by Rs. {expense_reduction:,.0f} to fully fund all goals"
})
# Option 2: Increase income (need ~30% more gross income due to taxes/savings rate)
income_increase = shortfall * 1.3
recs.append({
"option": "Increase Income",
"amount": round(income_increase),
"action": f"Increase monthly income by Rs. {income_increase:,.0f} (assuming current savings rate)"
})
# Option 3: Accept partial achievement and increase over time
if current_surplus > 0:
achievable_pct = (current_surplus / (current_surplus + shortfall)) * 100
recs.append({
"option": "Start Now, Increase Later",
"amount": None,
"action": f"Start SIPs now at Rs. {current_surplus:,.0f}/month ({achievable_pct:.0f}% of goals) and increase contributions annually"
})
# Option 4: Extend timelines
recs.append({
"option": "Extend Goal Timelines",
"amount": None,
"action": "Extend goal target dates to reduce monthly SIP requirement"
})
return recs
class PriorityAllocationEngine:
"""
Allocates available monthly surplus following priority order:
Priority 1: Term Insurance Premium (if gap exists & has dependents)
Priority 2: Health Insurance Premium (if gap exists)
Priority 3+: Emergency Fund + Goals (remaining surplus distributed EQUALLY)
NEW Features (Manager feedback):
- Use available savings for insurance purchase first (lump sum from savings)
- If user confirms having insurance (tickmark), skip that allocation
- Treat Emergency Fund as a goal with low-risk allocation
- Divide remaining surplus EQUALLY among Emergency Fund + Goals
- Generate per-goal SIP table with corpus created and shortfall columns
- Allocate existing investments equally among goals, rebalance per goal risk
"""
@staticmethod
def estimate_term_premium(cover_gap: float, age: int = 35) -> float:
"""Estimate yearly term insurance premium based on cover gap and age."""
if cover_gap <= 0:
return 0.0
# Rough estimate: Rs. 500-1200 per lakh depending on age
rate_per_lakh = 500 if age < 35 else (700 if age < 45 else 1200)
return (cover_gap / 100000) * rate_per_lakh
@staticmethod
def estimate_health_premium(cover_gap: float, age: int = 35) -> float:
"""Estimate yearly health insurance premium based on cover gap and age."""
if cover_gap <= 0:
return 0.0
# Rough estimate: Rs. 2500-5000 per lakh for family floater
rate_per_lakh = 2500 if age < 35 else (3500 if age < 45 else 5000)
return (cover_gap / 100000) * rate_per_lakh
@staticmethod
def compute_allocation(
monthly_surplus: float,
term_insurance_gap: float,
health_insurance_gap: float,
goals: List[Dict],
age: int = 35,
has_dependents: bool = True,
# NEW Parameters (Manager feedback)
available_savings: float = 0.0,
has_term_insurance_confirmed: bool = False,
has_health_insurance_confirmed: bool = False,
emergency_fund_target: float = 0.0,
emergency_fund_current: float = 0.0,
existing_investments: float = 0.0,
existing_sip_commitments: float = 0.0, # Already running SIP (counts towards total investing)
) -> Dict[str, Any]:
"""
Compute priority-based allocation of monthly surplus with enhanced logic.
NEW Logic:
1. If user confirmed having insurance (tickmark), set that gap to zero
2. Use available savings for insurance purchase first (lump sum)
3. Only create insurance SIP for next year's premium if savings don't cover it
4. Divide remaining surplus EQUALLY among Emergency Fund + Goals
5. Generate per-goal table with corpus created vs required SIP
6. Existing investments divided equally among goals and rebalanced per goal risk
Args:
monthly_surplus: Available monthly savings after expenses/EMI
term_insurance_gap: Gap in term cover (Rs.)
health_insurance_gap: Gap in health cover (Rs.)
goals: List of goal dicts with 'ideal_sip', 'name', 'priority_rank', 'risk_category', 'horizon_years'
age: Client age for premium estimation
has_dependents: Whether client has financial dependents
available_savings: One-time savings that can be used for insurance purchase (NEW)
has_term_insurance_confirmed: Frontend checkbox - user confirms having term insurance (NEW)
has_health_insurance_confirmed: Frontend checkbox - user confirms having health insurance (NEW)
emergency_fund_target: Target emergency fund amount (6 months expenses) (NEW)
emergency_fund_current: Current emergency fund amount (NEW)
existing_investments: Total current investment value that can be allocated to goals (NEW)
existing_sip_commitments: Already running SIPs that count towards total investing (NEW)
Returns:
Dict with priority breakdown, per-goal table, achievement %, and bridge recommendations
"""
priority_items = []
# --- Step 1: Handle insurance with tickmark logic ---
# If user confirmed having insurance, set gap to zero
effective_term_gap = 0 if has_term_insurance_confirmed else term_insurance_gap
effective_health_gap = 0 if has_health_insurance_confirmed else health_insurance_gap
# Calculate yearly premiums
term_premium_yearly = PriorityAllocationEngine.estimate_term_premium(effective_term_gap, age) if has_dependents else 0
health_premium_yearly = PriorityAllocationEngine.estimate_health_premium(effective_health_gap, age)
total_insurance_yearly = term_premium_yearly + health_premium_yearly
# --- Step 2: Use savings for insurance purchase ---
insurance_from_savings = min(available_savings, total_insurance_yearly)
remaining_savings_after_insurance = available_savings - insurance_from_savings
insurance_shortfall_yearly = max(0, total_insurance_yearly - insurance_from_savings)
monthly_insurance_sip = insurance_shortfall_yearly / 12 # SIP for next year's premium
# Build priority items for insurance
if has_term_insurance_confirmed:
term_status = "Already Covered"
term_note = "Term insurance confirmed - no additional coverage needed"
term_monthly = 0
term_from_savings = 0
elif term_premium_yearly > 0:
term_from_savings = min(insurance_from_savings, term_premium_yearly)
term_status = "Use Savings" if term_from_savings >= term_premium_yearly else "Partial from Savings"
term_note = f"Use Rs. {term_from_savings:,.0f} from savings for this year. Cover gap: Rs. {effective_term_gap:,.0f}"
term_monthly = max(0, (term_premium_yearly - term_from_savings) / 12)
else:
term_status = "Not Required" if not has_dependents else "Adequate"
term_note = "Adequate coverage" if not has_dependents else "No gap exists"
term_monthly = 0
term_from_savings = 0
priority_items.append({
"priority": 1,
"name": "Term Insurance",
"monthly_amount": round(term_monthly, 0),
"yearly_amount": round(term_premium_yearly, 0),
"from_savings": round(term_from_savings, 0),
"status": term_status,
"note": term_note
})
if has_health_insurance_confirmed:
health_status = "Already Covered"
health_note = "Health insurance confirmed - no additional coverage needed"
health_monthly = 0
health_from_savings = 0
elif health_premium_yearly > 0:
savings_left_for_health = max(0, insurance_from_savings - term_from_savings)
health_from_savings = min(savings_left_for_health, health_premium_yearly)
health_status = "Use Savings" if health_from_savings >= health_premium_yearly else "Partial from Savings"
health_note = f"Use Rs. {health_from_savings:,.0f} from savings for this year. Cover gap: Rs. {effective_health_gap:,.0f}"
health_monthly = max(0, (health_premium_yearly - health_from_savings) / 12)
else:
health_status = "Adequate"
health_note = "Adequate coverage"
health_monthly = 0
health_from_savings = 0
priority_items.append({
"priority": 2,
"name": "Health Insurance",
"monthly_amount": round(health_monthly, 0),
"yearly_amount": round(health_premium_yearly, 0),
"from_savings": round(health_from_savings, 0),
"status": health_status,
"note": health_note
})
# Total insurance SIP needed monthly (for next year's premiums)
total_insurance_sip_monthly = term_monthly + health_monthly
# --- Step 3: Remaining surplus for emergency fund + goals ---
# Subtract existing SIP (already committed) before calculating what's available for NEW goals
# Formula: remaining = surplus - existing_sip - insurance
remaining_for_goals_and_emergency = max(0, monthly_surplus - existing_sip_commitments - total_insurance_sip_monthly)
# --- Step 4: Emergency Fund as a goal ---
emergency_fund_gap = max(0, emergency_fund_target - emergency_fund_current)
has_emergency_gap = emergency_fund_gap > 0
# Count total items to divide equally: emergency fund (if gap) + goals
num_allocation_buckets = len(goals) + (1 if has_emergency_gap else 0)
per_bucket_sip = remaining_for_goals_and_emergency / num_allocation_buckets if num_allocation_buckets > 0 else 0
# --- Step 5: Generate per-goal SIP table ---
goal_sip_table = []
total_ideal_sip = 0.0
total_allocated_sip = 0.0
# Emergency Fund Entry (if gap exists)
if has_emergency_gap:
emergency_sip = per_bucket_sip
emergency_risk = "Low"
# Corpus created in 1 year with this SIP (conservative return)
corpus_1_year = compute_realistic_target(emergency_sip, 1, "Conservative") or 0
# Calculate months to reach target
if emergency_sip > 0:
months_to_target = emergency_fund_gap / (emergency_sip * 1.005) # ~6% annual
years_to_target = round(months_to_target / 12, 1)
else:
years_to_target = None
goal_sip_table.append({
"name": "Emergency Fund",
"is_emergency": True,
"allocated_sip": round(emergency_sip, 0),
"risk_category": emergency_risk,
"corpus_created_1yr": round(corpus_1_year, 0),
"ideal_sip": round(emergency_sip, 0),
"shortfall": 0,
"target_amount": round(emergency_fund_gap, 0),
"years_to_target": years_to_target,
"fund_type": "Liquid Fund / Savings Account",
})
total_allocated_sip += emergency_sip
# Regular Goals with equal SIP allocation
for g in goals:
goal_name = g.get("name") or "Goal"
ideal_sip = _coerce_float(g.get("ideal_sip"), 0.0)
risk_cat = g.get("risk_category") or "Moderate"
horizon = g.get("horizon_years")
target_amount = _coerce_float(g.get("target_amount"), 0.0)
allocated_sip = per_bucket_sip
shortfall = max(0, ideal_sip - allocated_sip)
# Calculate corpus created with allocated SIP
corpus_created = compute_realistic_target(allocated_sip, horizon, risk_cat) if horizon else None
# Fund type recommendation based on risk
fund_type = _get_fund_type_recommendation(risk_cat)
goal_sip_table.append({
"name": goal_name,
"is_emergency": False,
"allocated_sip": round(allocated_sip, 0),
"risk_category": risk_cat,
"corpus_created": round(corpus_created, 0) if corpus_created else None,
"ideal_sip": round(ideal_sip, 0),
"shortfall": round(shortfall, 0),
"target_amount": round(target_amount, 0),
"horizon_years": horizon,
"fund_type": fund_type,
})
total_ideal_sip += ideal_sip
total_allocated_sip += allocated_sip
# Add goals summary as priority 3
goal_achievement_pct = min(100.0, (total_allocated_sip / total_ideal_sip) * 100) if total_ideal_sip > 0 else 100.0
total_shortfall = max(0, total_ideal_sip - total_allocated_sip)
goal_status = "Full" if goal_achievement_pct >= 100 else ("Partial" if goal_achievement_pct > 0 else "Cannot Fund")
priority_items.append({
"priority": 3,
"name": "Emergency Fund + Goal SIPs",
"monthly_amount": round(remaining_for_goals_and_emergency, 0),
"ideal_amount": round(total_ideal_sip, 0),
"status": goal_status,
"note": f"Divided equally: Rs. {per_bucket_sip:,.0f}/month each for {num_allocation_buckets} items"
})
# --- Step 6: Existing Investments Allocation ---
investments_per_goal = []
if existing_investments > 0 and len(goals) > 0:
investment_per_goal = existing_investments / len(goals)
for g in goals:
risk_cat = g.get("risk_category") or "Moderate"
equity_alloc = _get_equity_allocation_for_risk(risk_cat)
investments_per_goal.append({
"goal_name": g.get("name"),
"allocated_amount": round(investment_per_goal, 0),
"target_equity_pct": equity_alloc["equity"],
"target_debt_pct": equity_alloc["debt"],
"rebalance_note": f"Rebalance to {equity_alloc['equity']}% equity, {equity_alloc['debt']}% debt for {risk_cat} risk"
})
# Generate bridge recommendations if shortfall exists
bridge_recs = generate_bridge_recommendations(total_shortfall, remaining_for_goals_and_emergency) if total_shortfall > 0 else []
# Calculate total investing (existing SIP + new allocations after insurance)
new_allocations_after_insurance = remaining_for_goals_and_emergency
total_investing = existing_sip_commitments + new_allocations_after_insurance
# Calculate what % of goal requirement is being funded
goal_funding_pct = (total_investing / total_ideal_sip * 100) if total_ideal_sip > 0 else 100.0
return {
"priority_breakdown": priority_items,
"monthly_surplus": round(monthly_surplus, 0),
"available_savings": round(available_savings, 0),
"insurance_from_savings": round(insurance_from_savings, 0),
"insurance_sip_monthly": round(total_insurance_sip_monthly, 0),
"remaining_for_goals": round(remaining_for_goals_and_emergency, 0),
"per_goal_sip": round(per_bucket_sip, 0),
"num_allocation_buckets": num_allocation_buckets,
"goal_sip_table": goal_sip_table,
"total_ideal_sip_needed": round(total_ideal_sip, 0),
"total_allocated_sip": round(total_allocated_sip, 0),
"goal_achievement_percent": round(goal_achievement_pct, 1),
"savings_shortfall": round(total_shortfall, 0) if total_shortfall > 0 else 0,
"bridge_recommendations": bridge_recs,
"existing_investments_allocation": investments_per_goal,
# NEW: Existing SIP tracking for proper report messages
"existing_sip_running": round(existing_sip_commitments, 0),
"new_allocations_available": round(new_allocations_after_insurance, 0),
"total_investing": round(total_investing, 0),
"goal_funding_percent": round(goal_funding_pct, 1),
"summary": (
f"With Rs. {monthly_surplus:,.0f}/month surplus: "
f"Rs. {total_insurance_sip_monthly:,.0f} for insurance, "
f"Rs. {remaining_for_goals_and_emergency:,.0f} remaining for goals. "
+ (f"Already investing Rs. {existing_sip_commitments:,.0f}/month. " if existing_sip_commitments > 0 else "")
+ f"Total investing: Rs. {total_investing:,.0f}/month ({goal_funding_pct:.1f}% of goal requirement)."
),
"insurance_recommendation": {
"use_savings": insurance_from_savings > 0,
"savings_used": round(insurance_from_savings, 0),
"savings_remaining": round(remaining_savings_after_insurance, 0),
"monthly_sip_for_next_year": round(total_insurance_sip_monthly, 0),
"note": f"Use Rs. {insurance_from_savings:,.0f} from savings for this year's insurance. Set up Rs. {total_insurance_sip_monthly:,.0f}/month SIP for next year's premium." if insurance_from_savings > 0 else None
},
# Keep backward compatibility
"allocated_to_insurance": round(total_insurance_sip_monthly, 0),
}
def _get_fund_type_recommendation(risk_category: str) -> str:
"""Get recommended fund type based on risk category."""
cat = (risk_category or "").lower()
if cat in ["conservative", "low"]:
return "Debt Funds / Liquid Funds"
elif cat == "moderate":
return "Balanced / Hybrid Funds"
elif cat == "growth":
return "Equity Funds / Flexi-cap"
elif cat in ["aggressive", "very aggressive"]:
return "Small/Mid-cap Equity Funds"
return "Balanced Funds"
def _get_equity_allocation_for_risk(risk_category: str) -> Dict[str, int]:
"""Get target equity/debt allocation based on risk category for rebalancing."""
cat = (risk_category or "").lower()
if cat in ["conservative", "low"]:
return {"equity": 30, "debt": 70}
elif cat == "moderate":
return {"equity": 50, "debt": 50}
elif cat == "growth":
return {"equity": 70, "debt": 30}
elif cat in ["aggressive", "very aggressive"]:
return {"equity": 85, "debt": 15}
return {"equity": 50, "debt": 50}
# ------------------------ Concrete Section Runners ------------------------ #
class FlagsExplainerRunner(SectionRunner):
name = "flags_explainer"
def digest(self, facts: Dict[str, Any]) -> Dict[str, Any]:
analysis = facts.get("analysis") or {}
flags = analysis.get("flags") or facts.get("flags") or []
kpis = {
"surplusBand": analysis.get("surplusBand"),
"insuranceGap": analysis.get("insuranceGap"),
"debtStress": analysis.get("debtStress"),
"liquidity": analysis.get("liquidity"),
"ihsBand": ((analysis.get("ihs") or {}).get("band")),
"emiPct": ((analysis.get("_diagnostics") or {}).get("emiPct")),
"liquidityMonths": ((analysis.get("_diagnostics") or {}).get("liquidityMonths")),
}
return {
"flags": flags[:10],
"kpis": kpis,
"client": {
"age": (facts.get("personal") or {}).get("age"),
"dependents": (facts.get("personal") or {}).get("dependents_count"),
},
}
def prompt(self, digest: Dict[str, Any]) -> Tuple[str, str]:
system = (
"You are a senior financial planner writing for Indian retail clients. "
"IMPORTANT: All monetary values MUST be in Indian Rupees (₹ or Rs.). NEVER use dollars ($) or any other currency. "
"Be precise, neutral, and practical. No guarantees or forward-looking promises. "
"Return valid JSON with keys: title (string), bullets (array of short points), paragraphs (2-3 short paragraphs), actions (checklist items)."
)
user = (
"Section: Flags and Actions\n"
"FactsDigest JSON (<=2KB):\n"
f"{_json_dumps(digest)}\n\n"
"Constraints:\n"
"- Max 6 bullets, each <= 20 words.\n"
"- 1-2 paragraphs, each <= 80 words.\n"
"- Max 5 actions, each actionable and specific.\n"
)
return system, user
class ProtectionPlanRunner(SectionRunner):
name = "protection_plan"
def digest(self, facts: Dict[str, Any]) -> Dict[str, Any]:
analysis = facts.get("analysis") or {}
personal = facts.get("personal") or {}
insurance = facts.get("insurance") or {}
income = facts.get("income") or {}
return {
"age": personal.get("age"),
"dependents": personal.get("dependents_count"),
"insuranceGap": analysis.get("insuranceGap"),
"lifeCover": insurance.get("lifeCover"),
"healthCover": insurance.get("healthCover"),
"annualIncome": income.get("annualIncome"),
"requiredLifeCover": ((analysis.get("_diagnostics") or {}).get("requiredLifeCover")),
}
def prompt(self, digest: Dict[str, Any]) -> Tuple[str, str]:
annual_income = _coerce_float(digest.get("annualIncome"), 0.0)
required_cover = _coerce_float(digest.get("requiredLifeCover"), annual_income * 10)
current_life = _coerce_float(digest.get("lifeCover"), 0.0)
current_health = _coerce_float(digest.get("healthCover"), 0.0)
age = _coerce_float(digest.get("age"), 35)
# Estimate term premium (rough: Rs. 500-800 per lakh for 30-40 age group)
cover_gap = max(0, required_cover - current_life)
estimated_premium = (cover_gap / 100000) * (500 if age < 35 else 700 if age < 45 else 1200)
system = (
"You are a senior financial planner. Draft a protection (life/health) section for Indian clients. "
"IMPORTANT: All monetary values MUST be in Indian Rupees (₹ or Rs.). NEVER use dollars ($) or any other currency. "
"Provide SPECIFIC coverage amounts and estimates. Avoid naming specific insurers but be specific about amounts."
)
user = (
"Section: Protection Plan\n"
f"FactsDigest:\n{_json_dumps(digest)}\n\n"
"INSTRUCTIONS:\n"
f"1. Life Insurance Gap: Required Rs.{required_cover:,.0f}, Current Rs.{current_life:,.0f}, Gap Rs.{cover_gap:,.0f}\n"
f" - If gap exists, recommend term insurance with specific cover amount\n"
f" - Estimated premium: approx Rs.{estimated_premium:,.0f}/year (varies by age, health, insurer)\n"
f"2. Health Insurance: Current Rs.{current_health:,.0f}\n"
" - Recommend Rs.10-15 lakh family floater for adequate coverage\n"
" - If current < Rs.5 lakh, flag as critical gap\n"
"3. Priority Order: Term life first if dependents exist, then health cover\n\n"
"Output JSON keys: title, bullets, paragraphs, actions.\n"
"Length limits: <=6 bullets, <=2 paragraphs, <=5 actions."
)
return system, user
class CashflowRunner(SectionRunner):
name = "cashflow"
def digest(self, facts: Dict[str, Any]) -> Dict[str, Any]:
analysis = facts.get("analysis") or {}
bank = facts.get("bank") or {}
return {
"surplusBand": analysis.get("surplusBand"),
"bank": {
"total_inflows": bank.get("total_inflows"),
"total_outflows": bank.get("total_outflows"),
"net_cashflow": bank.get("net_cashflow"),
}
}
def prompt(self, digest: Dict[str, Any]) -> Tuple[str, str]:
system = (
"You are a financial planner for Indian clients. Explain cashflows clearly, with practical advice to improve savings. "
"IMPORTANT: All monetary values MUST be in Indian Rupees (₹ or Rs.). NEVER use dollars ($) or any other currency."
)
user = (
"Section: Cashflow Overview\n"
f"FactsDigest:\n{_json_dumps(digest)}\n\n"
"Return JSON: title, bullets, paragraphs, actions. Keep concise and actionable."
)
return system, user
class DebtStrategyRunner(SectionRunner):
name = "debt_strategy"
def digest(self, facts: Dict[str, Any]) -> Dict[str, Any]:
analysis = facts.get("analysis") or {}
diag = analysis.get("_diagnostics") or {}
income = facts.get("income") or {}
return {
"debtStress": analysis.get("debtStress"),
"emiPct": diag.get("emiPct"),
"monthlyEmi": income.get("monthlyEmi"),
"annualIncome": income.get("annualIncome"),
}
def prompt(self, digest: Dict[str, Any]) -> Tuple[str, str]:
monthly_emi = _coerce_float(digest.get("monthlyEmi"), 0.0)
annual_income = _coerce_float(digest.get("annualIncome"), 0.0)
emi_pct = _coerce_float(digest.get("emiPct"), 0.0)
monthly_income = annual_income / 12 if annual_income > 0 else 0
# Calculate suggested prepayment from surplus (if EMI is >30%, suggest aggressive prepayment)
target_emi_pct = 30.0
excess_emi = max(0, monthly_emi - (monthly_income * target_emi_pct / 100))
system = (
"You craft debt optimization advice for Indian retail clients. "
"Be specific about which debts to pay first and prepayment amounts. "
"IMPORTANT: All monetary values MUST be in Indian Rupees (₹ or Rs.). NEVER use dollars ($)."
)
user = (
"Section: Debt Strategy\n"
f"FactsDigest:\n{_json_dumps(digest)}\n\n"
"INSTRUCTIONS:\n"
f"1. Current EMI: Rs.{monthly_emi:,.0f}/month ({emi_pct:.1f}% of income)\n"
f" - Benchmark: Keep EMI below 30-40% of income\n"
f"2. DEBT PRIORITY (always recommend this order):\n"
" - Credit card debt (18-42% interest) - Pay off FIRST\n"
" - Personal loans (12-20% interest) - Pay off SECOND\n"
" - Car loans (8-12% interest) - Pay off THIRD\n"
" - Home loans (7-9% interest) - Lowest priority\n"
f"3. PREPAYMENT: If EMI exceeds 30%, suggest monthly prepayment of Rs.{excess_emi:,.0f}\n"
" - Focus prepayment on highest-interest debt first\n"
"4. Avoid new unsecured debt until EMI < 30%\n\n"
"JSON output keys: title, bullets, paragraphs, actions. "