life-settlement-model / valuation_engine.py
jacobbecker's picture
Fix: Use IRR comparison for hurdle determination in waterfall
1ca24fb
Raw History Blame Contribute Delete
77.1 kB
""" Life Settlements Valuation Engine Calculates life expectancy, premium streams, and policy valuations """ import pandas as pd import numpy as np from scipy.interpolate import CubicSpline from sklearn.ensemble import RandomForestRegressor from sklearn.preprocessing import LabelEncoder from datetime import datetime, timedelta import pickle import os import warnings warnings.filterwarnings('ignore') # Get the directory where this script is located SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) DATA_DIR = os.path.join(SCRIPT_DIR, 'data') class LifeSettlementsEngine: def __init__(self, data_dir=None): # Use provided data_dir or default to script's data directory self.data_dir = data_dir or DATA_DIR # Check for cached model to speed up startup model_cache_path = os.path.join(self.data_dir, 'trained_model.pkl') if os.path.exists(model_cache_path): print("="*80) print("LOADING CACHED MODEL & DATA") print("="*80) print(f"Found cached model at {model_cache_path}") print("Loading from cache (this should take ~2 seconds)...") try: with open(model_cache_path, 'rb') as f: cached = pickle.load(f) # Load model and training data self.mortality_model = cached['model'] self.label_encoders = cached['label_encoders'] self.training_df = cached['training_df'] self.feature_names = cached['feature_names'] # Load all data files from cache self.screener_questions = cached['screener_questions'] self.mapped_impairments = cached['mapped_impairments'] self.vbt_tables = cached['vbt_tables'] self.premiums_df = cached['premiums_df'] self.certificates_df = cached['certificates_df'] print("✓ Model and all data loaded from cache!") print(f"✓ Training data: {len(self.training_df)} certificates") print(f"✓ VBT tables: {len(self.vbt_tables)} tables") print(f"✓ Premiums data: {len(self.premiums_df)} rows") print("="*80 + "\n") return # Skip training and data loading except Exception as e: print(f"⚠️ Error loading cached model: {e}") print("Will train model from scratch...") print("="*80 + "\n") # Otherwise, load data and train as normal print("No cached model found - training from scratch...") self.load_data() self.train_mortality_model() def load_data(self): """Load all reference data files""" print("Loading data files...") # Load screener questions self.screener_questions = pd.read_excel(os.path.join(self.data_dir, 'screener_questions_v2.xlsx')) # Load mapped impairments self.mapped_impairments = pd.read_excel(os.path.join(self.data_dir, 'mapped_impairments__1_.xlsx')) # Load VBT mortality tables self.vbt_tables = { 'Female_NS': pd.read_excel(os.path.join(self.data_dir, 'VBT_Female_NS.xlsx')), 'Female_S': pd.read_excel(os.path.join(self.data_dir, 'VBT_Female_S.xlsx')), 'Male_NS': pd.read_excel(os.path.join(self.data_dir, 'VBT_Male_NS.xlsx')), 'Male_S': pd.read_excel(os.path.join(self.data_dir, 'VBT_Male_S.xlsx')) } # Load premiums data self.premiums_df = pd.read_excel(os.path.join(self.data_dir, 'premiums_for_model.xlsx'), header=None) # Load certificates data for training self.certificates_df = pd.read_csv(os.path.join(self.data_dir, 'Certificates for claude.csv')) # Add supplemental impairment mappings for new conditions self._add_supplemental_impairments() print("Data loaded successfully!") def _add_supplemental_impairments(self): """Add additional impairment mappings not in the Excel file""" new_impairments = [ # Pulmonary Fibrosis - same severity as COPD (3-4) {'Category': 'Pulmonary', 'Condition': 'Pulmonary fibrosis', 'Ranking (1-5)': 4, 'Mapped Question': 'Q7_PF'}, {'Category': 'Pulmonary', 'Condition': 'Interstitial lung disease', 'Ranking (1-5)': 4, 'Mapped Question': 'Q7_PF'}, # HIV - tiered severity based on control status {'Category': 'Infectious Disease', 'Condition': 'HIV well-controlled undetectable', 'Ranking (1-5)': 2, 'Mapped Question': 'Q_HIV_a'}, {'Category': 'Infectious Disease', 'Condition': 'HIV controlled on ART', 'Ranking (1-5)': 3, 'Mapped Question': 'Q_HIV_a'}, {'Category': 'Infectious Disease', 'Condition': 'HIV uncontrolled', 'Ranking (1-5)': 5, 'Mapped Question': 'Q_HIV_a'}, {'Category': 'Infectious Disease', 'Condition': 'AIDS diagnosis', 'Ranking (1-5)': 5, 'Mapped Question': 'Q_HIV_b'}, # ALS (already had impairments but adding explicit mapping) {'Category': 'Neurological', 'Condition': 'ALS', 'Ranking (1-5)': 5, 'Mapped Question': 'Q9_ALS'}, {'Category': 'Neurological', 'Condition': 'Motor neuron disease', 'Ranking (1-5)': 5, 'Mapped Question': 'Q9_ALS'}, ] # Convert to DataFrame and append new_df = pd.DataFrame(new_impairments) self.mapped_impairments = pd.concat([self.mapped_impairments, new_df], ignore_index=True) print(f" Added {len(new_impairments)} supplemental impairment mappings") def train_mortality_model(self): """Back-solve mortality multipliers from certificates and train RandomForest model""" print("="*80) print("PART 1: BACK-SOLVING MORTALITY MULTIPLIERS FROM CERTIFICATES") print("="*80) # Prepare training data df = self.certificates_df.copy() # Remove rows with missing critical data df = df.dropna(subset=['ANB', 'Gender', 'Smoking', 'BMI', 'avgle']) # CRITICAL FIX: avgle is in YEARS, not months! Convert to months df['avgle_months'] = df['avgle'] * 12 print(f"\nProcessing {len(df)} certificates to back-solve multipliers...") # DEBUG: Check avgle statistics print(f"\nDEBUG - avgle statistics (CONVERTED TO MONTHS):") print(f" Original avgle in YEARS:") print(f" Min: {df['avgle'].min():.1f} years") print(f" Max: {df['avgle'].max():.1f} years") print(f" Mean: {df['avgle'].mean():.1f} years") print(f" Median: {df['avgle'].median():.1f} years") print(f" Converted to MONTHS:") print(f" Min: {df['avgle_months'].min():.1f} months ({df['avgle_months'].min()/12:.1f} years)") print(f" Max: {df['avgle_months'].max():.1f} months ({df['avgle_months'].max()/12:.1f} years)") print(f" Mean: {df['avgle_months'].mean():.1f} months ({df['avgle_months'].mean()/12:.1f} years)") print(f" Median: {df['avgle_months'].median():.1f} months ({df['avgle_months'].median()/12:.1f} years)") # DEBUG: Show first 10 certificates print("\nDEBUG - Sample certificates before back-solving:") for i in range(min(10, len(df))): row = df.iloc[i] print(f" [{i}] Age {row['ANB']:.0f}, {row['Gender']}, {row['Smoking']}: avgle={row['avgle']:.1f} YEARS = {row['avgle_months']:.1f} months") # Back-solve multiplier for each certificate multipliers = [] for idx, row in df.iterrows(): age = row['ANB'] gender = row['Gender'] smoking = row['Smoking'] actual_le = row['avgle_months'] # FIXED: Now in months # Get VBT baseline LE (with debug for first certificate) baseline_le = self._calculate_vbt_baseline_le(age, gender, smoking, debug=(idx == 0)) if baseline_le is None or baseline_le == 0: if idx < 5: print(f"\n⚠️ Certificate {idx}: baseline_le is None or 0, using default 1.5x") multipliers.append(1.5) # Default fallback continue # Back-solve multiplier using iterative approach best_multiplier, best_le = self._backsolve_multiplier(age, gender, smoking, actual_le, baseline_le, debug=(idx < 3)) multipliers.append(best_multiplier) # DEBUG: Show details for first 5 certificates if idx < 5: print(f"\nDEBUG - Back-solving certificate {idx}:") print(f" Age: {age:.0f}, Gender: {gender}, Smoking: {smoking}") print(f" Target avgle: {actual_le:.1f} months ({actual_le/12:.1f} years)") print(f" VBT baseline LE (1.0x): {baseline_le:.1f} months ({baseline_le/12:.1f} years)") print(f" Trying multipliers from 0.5 to 10.0...") print(f" Best multiplier found: {best_multiplier:.2f}x") print(f" Calculated LE with that multiplier: {best_le:.1f} months ({best_le/12:.1f} years)") print(f" Error: {abs(best_le - actual_le):.1f} months ({abs(best_le - actual_le)/12:.1f} years)") # Show direction check if actual_le < baseline_le: print(f" ⚠️ Person is SICKER than baseline (actual < baseline)") print(f" → Need multiplier > 1.0 to INCREASE mortality and REDUCE LE") print(f" → Got multiplier = {best_multiplier:.2f}x {'✓' if best_multiplier > 1.0 else '✗ ERROR'}") else: print(f" ⚠️ Person is HEALTHIER than baseline (actual > baseline)") print(f" → Need multiplier < 1.0 to DECREASE mortality and INCREASE LE") print(f" → Got multiplier = {best_multiplier:.2f}x {'✓' if best_multiplier < 1.0 else '✗ ERROR'}") if (idx + 1) % 1000 == 0: print(f" Processed {idx + 1}/{len(df)} certificates...") df['multiplier'] = multipliers print(f"\n✓ Back-solved {len(df)} multipliers!") print(f"\nMultiplier statistics:") print(f" Min: {df['multiplier'].min():.2f}x") print(f" Max: {df['multiplier'].max():.2f}x") print(f" Mean: {df['multiplier'].mean():.2f}x") print(f" Median: {df['multiplier'].median():.2f}x") print(f" Std: {df['multiplier'].std():.2f}") # Encode categorical variables le_gender = LabelEncoder() le_smoking = LabelEncoder() df['gender_encoded'] = le_gender.fit_transform(df['Gender'].fillna('M')) df['smoking_encoded'] = le_smoking.fit_transform(df['Smoking'].fillna('N')) # Store encoders self.label_encoders = { 'gender': le_gender, 'smoking': le_smoking } # Add condition severities feature_names = ['ANB', 'BMI', 'gender_encoded', 'smoking_encoded'] for cond_col in ['Condition A', 'Condition B', 'Condition C']: if cond_col in df.columns: df[f'{cond_col}_severity'] = df[cond_col].apply( lambda x: self._get_condition_severity(x) ) feature_names.append(f'{cond_col}_severity') # Build feature matrix X = df[feature_names].fillna(0).values y = df['multiplier'].values # Train Random Forest model print("\nTraining RandomForest model on back-solved multipliers...") self.mortality_model = RandomForestRegressor( n_estimators=100, max_depth=10, random_state=42, n_jobs=-1 ) self.mortality_model.fit(X, y) self.feature_names = feature_names print(f"✓ Model trained successfully!") print(f"\nFeature importance:") for fname, importance in zip(feature_names, self.mortality_model.feature_importances_): print(f" {fname}: {importance:.3f}") print(f"\nSample breakdown by severity (Condition A):") if 'Condition A_severity' in df.columns: for severity in sorted(df['Condition A_severity'].dropna().unique()): subset = df[df['Condition A_severity'] == severity] if len(subset) > 0: print(f" Severity {int(severity)}: {len(subset)} samples, avg multiplier: {subset['multiplier'].mean():.2f}x") # Store df for later analysis self.training_df = df # Save trained model AND all data to cache for faster startup model_cache_path = os.path.join(self.data_dir, 'trained_model.pkl') print("\nSaving trained model and all data to cache...") try: with open(model_cache_path, 'wb') as f: pickle.dump({ # Model and training data 'model': self.mortality_model, 'label_encoders': self.label_encoders, 'training_df': self.training_df, 'feature_names': self.feature_names, # All data files 'screener_questions': self.screener_questions, 'mapped_impairments': self.mapped_impairments, 'vbt_tables': self.vbt_tables, 'premiums_df': self.premiums_df, 'certificates_df': self.certificates_df }, f) print(f"✓ Model and all data saved to {model_cache_path}") print(f" Next startup will be MUCH faster (~2 seconds instead of ~30 seconds)!") print(f" All Excel/CSV files will be loaded from cache instead of disk") except Exception as e: print(f"⚠️ Error saving model cache: {e}") print(f" Model will still work, but startup won't be cached") print("="*80 + "\n") def _calculate_vbt_baseline_le(self, age, gender, smoking, debug=False): """Calculate baseline LE from VBT tables using annual calculation - NO MULTIPLIER""" # Select appropriate VBT table gender_key = 'Male' if gender in ['M', 'Male'] else 'Female' smoking_key = 'S' if smoking in ['S', 'Smoker'] else 'NS' table_key = f"{gender_key}_{smoking_key}" vbt_table = self.vbt_tables[table_key] # Round age to nearest integer for table lookup age_int = int(round(age)) age_int = max(60, min(95, age_int)) # Clamp to table range # Get mortality row mortality_row = vbt_table[vbt_table['Age'] == age_int] if len(mortality_row) == 0: return None if debug: print(f"\nDEBUG - VBT baseline calculation:") print(f" Gender: {gender} → {gender_key}") print(f" Smoking: {smoking} → {smoking_key}") print(f" Table: {table_key}") print(f" Age: {age:.1f} → {age_int} (clamped to 60-95)") # ANNUAL CALCULATION (same as _calculate_le_with_multiplier but with multiplier=1.0) # Step 1: Extract survival counts l(t) from VBT table survival_counts = mortality_row.iloc[0, 1:].values # l(0), l(1), ..., l(30) num_years = len(survival_counts) - 1 if debug: print(f" Survival counts: {len(survival_counts)} durations (0-30)") print(f" First 5: {survival_counts[:5]}") # Step 2: Calculate ANNUAL mortality rates: q(t) = (l(t) - l(t+1)) / l(t) annual_mortality = np.zeros(num_years) for t in range(num_years): if survival_counts[t] > 0: annual_mortality[t] = (survival_counts[t] - survival_counts[t+1]) / survival_counts[t] else: annual_mortality[t] = 1.0 annual_mortality = np.clip(annual_mortality, 0, 1) # Step 3: Apply 1% annual mortality improvement (NO MULTIPLIER for baseline) annual_improvement_factors = 0.99 ** np.arange(num_years) final_mortality_annual = annual_mortality * annual_improvement_factors final_mortality_annual = np.clip(final_mortality_annual, 0, 1) # Step 4: Calculate ANNUAL survival probabilities annual_survival = np.zeros(num_years + 1) annual_survival[0] = 1.0 for t in range(num_years): annual_survival[t+1] = annual_survival[t] * (1 - final_mortality_annual[t]) # Step 5: Calculate LE in YEARS as sum of annual survival le_years = np.sum(annual_survival) # Step 6: Convert to months le_months = le_years * 12 if debug: print(f" LE calculation: Σ S(t) = {le_years:.2f} years = {le_months:.1f} months") return le_months def _backsolve_multiplier(self, age, gender, smoking, actual_le, baseline_le, debug=False): """Back-solve multiplier iteratively to find value that produces actual_le CORRECT LOGIC: - Higher mortality multiplier → Higher mortality rates → SHORTER life expectancy - Lower mortality multiplier → Lower mortality rates → LONGER life expectancy For example: - If baseline LE is 120 months and actual LE is 60 months (very sick) - We need a HIGHER multiplier (like 2.0x) to increase mortality and reduce LE - If baseline LE is 120 months and actual LE is 180 months (very healthy) - We need a LOWER multiplier (like 0.5x) to decrease mortality and increase LE """ # Try multipliers from 0.5 to 10.0 in steps of 0.1 # This range handles very sick individuals (need high multipliers) best_multiplier = 1.0 best_diff = float('inf') best_le = baseline_le if debug: print(f"\n DEBUG - Back-solving multiplier:") print(f" Baseline LE: {baseline_le:.1f} months") print(f" Target LE: {actual_le:.1f} months") print(f" Trying multipliers: 0.5, 1.0, 2.0, 5.0, 10.0") # Sample some key multipliers for debugging sample_multipliers = [0.5, 1.0, 2.0, 5.0, 10.0] if debug else [] for multiplier in np.arange(0.5, 10.01, 0.1): # Calculate LE with this multiplier using annual method calculated_le = self._calculate_le_with_multiplier(age, gender, smoking, multiplier) if calculated_le is None: continue # Show sample calculations if debug and multiplier in sample_multipliers: print(f" Multiplier {multiplier:.1f}x → LE = {calculated_le:.1f} months ({calculated_le/12:.1f} years)") # Find multiplier where calculated LE matches actual LE (±1 month) diff = abs(calculated_le - actual_le) if diff < best_diff: best_diff = diff best_multiplier = multiplier best_le = calculated_le # Early termination: if we're within 1 month, that's good enough if diff < 1.0: break if debug: print(f" → Best match: {best_multiplier:.2f}x (LE = {best_le:.1f} months, error = {best_diff:.1f} months)") return best_multiplier, best_le def _calculate_le_with_multiplier(self, age, gender, smoking, multiplier): """Calculate LE from VBT baseline with a given multiplier applied - ANNUAL BASIS""" # Get baseline VBT curve gender_key = 'Male' if gender in ['M', 'Male'] else 'Female' smoking_key = 'S' if smoking in ['S', 'Smoker'] else 'NS' table_key = f"{gender_key}_{smoking_key}" vbt_table = self.vbt_tables[table_key] # Get age-specific row age_int = int(round(age)) age_int = max(60, min(95, age_int)) mortality_row = vbt_table[vbt_table['Age'] == age_int] if len(mortality_row) == 0: return None # ANNUAL CALCULATION (same as calculate_adjusted_mortality PART 1) # Step 1: Extract survival counts l(t) from VBT table survival_counts = mortality_row.iloc[0, 1:].values # l(0), l(1), ..., l(30) num_years = len(survival_counts) - 1 # Step 2: Calculate ANNUAL mortality rates: q(t) = (l(t) - l(t+1)) / l(t) annual_mortality = np.zeros(num_years) for t in range(num_years): if survival_counts[t] > 0: annual_mortality[t] = (survival_counts[t] - survival_counts[t+1]) / survival_counts[t] else: annual_mortality[t] = 1.0 annual_mortality = np.clip(annual_mortality, 0, 1) # Step 3: Apply multiplier to annual mortality adjusted_mortality_annual = annual_mortality * multiplier adjusted_mortality_annual = np.clip(adjusted_mortality_annual, 0, 1) # Step 4: Apply 1% annual mortality improvement annual_improvement_factors = 0.99 ** np.arange(num_years) final_mortality_annual = adjusted_mortality_annual * annual_improvement_factors final_mortality_annual = np.clip(final_mortality_annual, 0, 1) # Step 5: Calculate ANNUAL survival probabilities annual_survival = np.zeros(num_years + 1) annual_survival[0] = 1.0 for t in range(num_years): annual_survival[t+1] = annual_survival[t] * (1 - final_mortality_annual[t]) # Step 6: Calculate LE in YEARS as sum of annual survival le_years = np.sum(annual_survival) # Step 7: Convert to months le_months = le_years * 12 return le_months def _get_condition_severity(self, condition_name): """Get severity ranking for a condition""" if pd.isna(condition_name): return 0 match = self.mapped_impairments[ self.mapped_impairments['Condition'].str.lower() == str(condition_name).lower() ] if len(match) > 0: return match.iloc[0]['Ranking (1-5)'] return 3 # Default to middle severity def _get_baseline_le(self, age, gender, smoking_status): """Calculate baseline life expectancy from VBT tables""" # Select appropriate VBT table gender_key = 'Male' if gender == 'Male' else 'Female' smoking_key = 'S' if smoking_status in ['S', 'Smoker'] else 'NS' table_key = f"{gender_key}_{smoking_key}" vbt_table = self.vbt_tables[table_key] # Round age to nearest integer for table lookup age_int = int(round(age)) age_int = max(60, min(95, age_int)) # Clamp to table range # Get mortality row mortality_row = vbt_table[vbt_table['Age'] == age_int] if len(mortality_row) == 0: return 120 # Default 10 years # Calculate life expectancy # Get survival rates across all durations survival_rates = mortality_row.iloc[0, 1:].values # Skip Age column # Calculate LE by summing survival rates (each period = 1 year) # Convert to months le_years = np.sum(survival_rates) / 1000 # Survival rates are per 1000 le_months = le_years * 12 return le_months def get_multiplier_from_quick_assessment(self, conditions_list, age, gender, smoking): """ Calculate mortality multiplier from Quick Assessment conditions. Takes a list of mapped condition names (0 to 10 conditions) and uses the SAME certificate matching logic as full assessment: - Take top 3 conditions by severity - Priority 1: Exact match (all 3 conditions in certificates) - Priority 2: Top 2 match - Priority 3: Category match - Priority 4: Fallback based on severity tiers Args: conditions_list: List of dicts with 'condition' and optional 'multiplier' keys age: User's age gender: User's gender smoking: User's smoking status Returns: tuple: (multiplier, match_method, match_count) """ print("\n" + "="*80) print("QUICK ASSESSMENT - CONDITION MAPPING") print("="*80) if not conditions_list or len(conditions_list) == 0: print("No conditions provided - using baseline multiplier 1.0") return 1.0, "No conditions (baseline)", 0 # Convert conditions to impairments with severity lookup impairments = [] cancer_multiplier = None for cond in conditions_list: condition_name = cond.get('condition') if not condition_name: continue # Check for cancer multiplier override if cond.get('multiplier'): cancer_multiplier = cond['multiplier'] print(f" Cancer multiplier override: {cancer_multiplier}x") # Look up severity from mapped_impairments match = self.mapped_impairments[ self.mapped_impairments['Condition'].str.lower() == str(condition_name).lower() ] if len(match) > 0: severity = match.iloc[0]['Ranking (1-5)'] category = match.iloc[0]['Category'] else: # Default severity based on condition type severity = 3 # Default to middle severity category = 'Unknown' # Ensure severity is an integer try: severity = int(severity) except (ValueError, TypeError): severity = 3 impairments.append({ 'category': category, 'condition': condition_name, 'severity': severity }) print(f" Mapped: {condition_name} -> Severity {severity}, Category: {category}") if not impairments: print("No valid impairments found - using baseline multiplier 1.0") return 1.0, "No valid conditions (baseline)", 0 # Sort by severity and get top 3 sorted_impairments = sorted(impairments, key=lambda x: x['severity'], reverse=True) top_impairments = sorted_impairments[:3] print(f"\nTop {len(top_impairments)} impairments by severity:") for i, imp in enumerate(top_impairments, 1): print(f" {i}. {imp['condition']} (Severity: {imp['severity']})") # Use the same certificate matching logic as full assessment multiplier, match_method, match_count = self.match_certificates_by_impairments(top_impairments) # Apply cancer multiplier override if present if cancer_multiplier: print(f"\nApplying cancer treatment multiplier: {cancer_multiplier}x") multiplier = multiplier * cancer_multiplier print(f"\n✓ Final Quick Assessment multiplier: {multiplier:.2f}x") print(f" Match method: {match_method}") print(f" Certificates matched: {match_count}") print("="*80 + "\n") return multiplier, match_method, match_count def map_questionnaire_to_impairments(self, answers): """Map user's questionnaire answers to impairments with severity""" import json impairments = [] # Load screener_complete.json with open(os.path.join(self.data_dir, 'screener_complete.json'), 'r') as f: screener_questions = json.load(f) # Process each answer for question_id, answer in answers.items(): # Find the question in screener_complete question_obj = None for q in screener_questions: if q['ID'] == question_id: question_obj = q break if not question_obj: continue # Case 1: Answer is "Yes" and question has direct impairments if answer == 'Yes' and question_obj.get('Impairments'): for imp_name in question_obj['Impairments']: # Look up severity in mapped_impairments match = self.mapped_impairments[ self.mapped_impairments['Condition'].str.lower() == str(imp_name).lower() ] if len(match) > 0: severity = match.iloc[0]['Ranking (1-5)'] category = match.iloc[0]['Category'] else: # Default severity = 3 severity = 3 category = 'Unknown' # Ensure severity is always an integer try: severity = int(severity) except (ValueError, TypeError): severity = 3 # Default if conversion fails impairments.append({ 'category': category, 'condition': imp_name, 'severity': severity, 'question': question_id }) # Case 2: Question has Followup options and answer matches an option label elif question_obj.get('Followup') and answer != 'Yes' and answer != 'No': for followup_option in question_obj['Followup']: if followup_option['label'] == answer: # Get all categories for this option categories = followup_option.get('categories', []) # Find highest severity among all categories highest_severity = 0 highest_severity_imp = None highest_category = None for cat_name in categories: # Look up severity in mapped_impairments match = self.mapped_impairments[ self.mapped_impairments['Condition'].str.lower() == str(cat_name).lower() ] if len(match) > 0: severity = match.iloc[0]['Ranking (1-5)'] category = match.iloc[0]['Category'] else: # Default severity = 3 severity = 3 category = 'Unknown' # Ensure severity is always an integer try: severity = int(severity) except (ValueError, TypeError): severity = 3 # Default if conversion fails # Track highest severity if severity > highest_severity: highest_severity = severity highest_severity_imp = cat_name highest_category = category # Add the impairment with highest severity if highest_severity_imp: impairments.append({ 'category': highest_category, 'condition': highest_severity_imp, 'severity': highest_severity, 'question': question_id }) break # Found matching followup option return impairments def get_top_impairments(self, impairments): """Get top 3 highest severity impairments""" if not impairments: return [] # Check for active cancer for imp in impairments: if 'cancer' in str(imp['condition']).lower() and imp['severity'] >= 4: return None # Stop analysis for active cancer # Sort by severity (highest first) and take top 3 sorted_imps = sorted(impairments, key=lambda x: x['severity'], reverse=True) return sorted_imps[:3] def match_certificates_by_impairments(self, top_impairments): """ PART 2: Match certificates based on impairment conditions Returns multiplier from matched certificates using priority matching """ print("\n" + "="*80) print("PART 2: CERTIFICATE MATCHING BY IMPAIRMENTS") print("="*80) if not top_impairments or len(top_impairments) == 0: print("\n⚠️ No impairments provided - using default multiplier 1.0") return 1.0, "No impairments (baseline)", 0 # Extract top impairment names and categories imp_names = [imp['condition'] for imp in top_impairments] imp_categories = [imp['category'] for imp in top_impairments] print(f"\nSearching for certificates matching:") for i, imp in enumerate(top_impairments, 1): print(f" {i}. {imp['condition']} (Severity: {imp['severity']}, Category: {imp['category']})") df = self.training_df.copy() # Helper function to normalize condition names for comparison def normalize_condition(cond): if pd.isna(cond): return "" return str(cond).strip().lower() # PRIORITY 1: Exact match (all 3 conditions) print("\n🔍 Priority 1: Searching for exact match (all 3 conditions)...") if len(imp_names) >= 3: matches = df[ (df['Condition A'].apply(normalize_condition) == normalize_condition(imp_names[0])) & (df['Condition B'].apply(normalize_condition) == normalize_condition(imp_names[1])) & (df['Condition C'].apply(normalize_condition) == normalize_condition(imp_names[2])) ] if len(matches) > 0: avg_multiplier = matches['multiplier'].mean() print(f" ✓ Found {len(matches)} exact matches!") print(f" Average multiplier: {avg_multiplier:.2f}x") print(f" Multiplier range: {matches['multiplier'].min():.2f}x - {matches['multiplier'].max():.2f}x") self._log_sample_certificates(matches) return avg_multiplier, "Exact match (3 conditions)", len(matches) print(" ✗ No exact matches found") # PRIORITY 2: Top 2 match (Condition A and B match, Condition C is any severity 1) print("\n🔍 Priority 2: Searching for top 2 match (A & B match, C is severity 1)...") if len(imp_names) >= 2: # Get all severity 1 conditions severity_1_conditions = self.mapped_impairments[ self.mapped_impairments['Ranking (1-5)'] == 1 ]['Condition'].apply(normalize_condition).unique() matches = df[ (df['Condition A'].apply(normalize_condition) == normalize_condition(imp_names[0])) & (df['Condition B'].apply(normalize_condition) == normalize_condition(imp_names[1])) & (df['Condition C'].apply(normalize_condition).isin(severity_1_conditions)) ] if len(matches) > 0: avg_multiplier = matches['multiplier'].mean() print(f" ✓ Found {len(matches)} matches!") print(f" Average multiplier: {avg_multiplier:.2f}x") print(f" Multiplier range: {matches['multiplier'].min():.2f}x - {matches['multiplier'].max():.2f}x") self._log_sample_certificates(matches) return avg_multiplier, "Top 2 match (A & B)", len(matches) print(" ✗ No top 2 matches found") # PRIORITY 3: Category match (categories match for A, B, C) print("\n🔍 Priority 3: Searching for category match...") if len(imp_categories) >= 3: # Get condition A, B, C categories df['Condition A_category'] = df['Condition A'].apply( lambda x: self._get_condition_category(x) ) df['Condition B_category'] = df['Condition B'].apply( lambda x: self._get_condition_category(x) ) df['Condition C_category'] = df['Condition C'].apply( lambda x: self._get_condition_category(x) ) matches = df[ (df['Condition A_category'] == imp_categories[0]) & (df['Condition B_category'] == imp_categories[1]) & (df['Condition C_category'] == imp_categories[2]) ] if len(matches) > 0: avg_multiplier = matches['multiplier'].mean() print(f" ✓ Found {len(matches)} category matches!") print(f" Average multiplier: {avg_multiplier:.2f}x") print(f" Multiplier range: {matches['multiplier'].min():.2f}x - {matches['multiplier'].max():.2f}x") self._log_sample_certificates(matches) return avg_multiplier, "Category match", len(matches) print(" ✗ No category matches found") # PRIORITY 4: Fallback - use severity-based calculation print("\n🔍 Priority 4: Using severity-based fallback multiplier...") print(" ⚠️ No matches found at any priority level") fallback_multiplier, tier = self._calculate_fallback_multiplier(top_impairments) return fallback_multiplier, f"Fallback ({tier})", 0 def _get_condition_category(self, condition_name): """Get category for a condition""" if pd.isna(condition_name): return "Unknown" match = self.mapped_impairments[ self.mapped_impairments['Condition'].str.lower() == str(condition_name).lower() ] if len(match) > 0: return match.iloc[0]['Category'] return "Unknown" def _calculate_fallback_multiplier(self, top_impairments): """ Calculate a smarter fallback multiplier based on severity levels when no certificate matches are found. Uses tiered logic based on the top 3 severity levels. """ print("\n 📊 Calculating severity-based fallback multiplier...") if not top_impairments: print(" No impairments - using baseline multiplier 1.0x") return 1.0, "No impairments" # Extract and sort severities (highest first) severities = sorted([imp['severity'] for imp in top_impairments], reverse=True) # Pad to 3 if fewer impairments while len(severities) < 3: severities.append(0) s1, s2, s3 = severities[0], severities[1], severities[2] print(f" Severity levels: S1={s1}, S2={s2}, S3={s3}") # Tiered fallback based on severity combination if s1 == 5 and s2 == 5: if s3 >= 5: multiplier, tier = 4.0, "S1=5, S2=5, S3>=5 (very severe)" else: multiplier, tier = 3.5, "S1=5, S2=5, S3<5 (severe)" elif s1 == 5 and s2 == 4: multiplier, tier = 3.0, "S1=5, S2=4" elif s1 == 5 and s2 == 3: multiplier, tier = 2.5, "S1=5, S2=3" elif s1 == 5 and s2 == 2: multiplier, tier = 2.25, "S1=5, S2=2" elif s1 == 5: multiplier, tier = 2.0, "S1=5 (single severe)" elif s1 == 4 and s2 == 4: multiplier, tier = 2.5, "S1=4, S2=4" elif s1 == 4 and s2 == 3: multiplier, tier = 2.0, "S1=4, S2=3" elif s1 == 4: multiplier, tier = 1.75, "S1=4 (single moderate-severe)" elif s1 == 3 and s2 == 3: multiplier, tier = 1.75, "S1=3, S2=3" elif s1 == 3: multiplier, tier = 1.5, "S1=3 (single moderate)" elif s1 == 2: multiplier, tier = 1.25, "S1=2 (mild)" else: multiplier, tier = 1.0, "S1<=1 (minimal/none)" print(f" Tier matched: {tier}") print(f" Fallback multiplier: {multiplier:.2f}x") return multiplier, tier def _log_sample_certificates(self, matches, max_samples=5): """Log sample certificates from matches""" print(f"\n Sample certificates:") sample = matches.head(max_samples) for idx, row in sample.iterrows(): print(f" - Age {row['ANB']:.0f}, {row['Gender']}, {row['Smoking']}: " f"LE={row['avgle']:.1f} months, Multiplier={row['multiplier']:.2f}x") print(f" Conditions: A={row['Condition A']}, B={row['Condition B']}, C={row['Condition C']}") def calculate_mortality_multiplier(self, age, gender, smoking, bmi, top_impairments): """Calculate mortality multiplier using trained ML model""" # Map full names to codes used in training data gender_map = {'Male': 'M', 'Female': 'F', 'M': 'M', 'F': 'F'} smoking_map = {'NS': 'N', 'S': 'S', 'N': 'N', 'Smoker': 'S', 'Non-Smoker': 'N'} gender_code = gender_map.get(gender, 'M') smoking_code = smoking_map.get(smoking, 'N') # Encode categorical variables gender_encoded = self.label_encoders['gender'].transform([gender_code])[0] smoking_encoded = self.label_encoders['smoking'].transform([smoking_code])[0] # Build feature vector features = [age, bmi, gender_encoded, smoking_encoded] # Debug logging print(f"Top impairments: {top_impairments}") # Add condition severities (0 if not present) condition_severities = [0, 0, 0] for i, imp in enumerate(top_impairments[:3]): severity = imp['severity'] # Force convert to integer - handle any type if isinstance(severity, dict): print(f"WARNING: Severity is dict for {imp['condition']}: {severity}") severity = 3 # default if dict elif isinstance(severity, str): severity = int(severity) else: severity = int(severity) condition_severities[i] = severity print(f"Condition severities: {condition_severities}") features.extend(condition_severities) # DETAILED PREDICTION LOGGING print(f"\n" + "="*60) print("MORTALITY MULTIPLIER PREDICTION") print("="*60) print(f"\nPrediction inputs:") print(f" Age: {age}") print(f" BMI: {bmi}") print(f" Gender: {gender} (encoded: {gender_encoded})") print(f" Smoking: {smoking} (encoded: {smoking_encoded})") print(f" Condition severities: {condition_severities}") print(f" Full feature vector: {features}") # Predict multiplier raw_multiplier = self.mortality_model.predict([features])[0] print(f"\nRaw ML prediction: {raw_multiplier:.3f}x") # Ensure reasonable bounds multiplier = max(0.5, min(5.0, raw_multiplier)) print(f"After clamping (0.5-5.0): {multiplier:.3f}x") if raw_multiplier != multiplier: print(f"⚠️ WARNING: Prediction was clamped from {raw_multiplier:.3f}x to {multiplier:.3f}x") return multiplier def analyze_similar_cases(self, age, conditions): """Find similar cases in certificates to validate prediction""" print(f"\n" + "="*80) print(f"SIMILAR CASES IN CERTIFICATES DATA") print(f"="*80) # Filter for similar age (+/- 5 years) similar = self.certificates_df[ (self.certificates_df['ANB'] >= age - 5) & (self.certificates_df['ANB'] <= age + 5) ] print(f"Age range {age-5:.0f} to {age+5:.0f}: {len(similar)} cases") if len(similar) > 0: print(f"Average LE for this age group: {similar['avgle'].mean():.1f} months ({similar['avgle'].mean()/12:.1f} years)") print(f"LE range: {similar['avgle'].min():.0f} - {similar['avgle'].max():.0f} months") print(f"Average age: {similar['ANB'].mean():.1f} years") # Show gender breakdown if available if 'Gender' in similar.columns: print(f"\nGender breakdown:") print(similar['Gender'].value_counts().to_string()) # Show smoking breakdown if available if 'Smoking' in similar.columns: print(f"\nSmoking breakdown:") print(similar['Smoking'].value_counts().to_string()) # Show top conditions if available if 'Condition A' in similar.columns: print(f"\nTop 5 most common Condition A:") top_conditions = similar['Condition A'].value_counts().head(5) for condition, count in top_conditions.items(): print(f" {condition}: {count} cases") # Calculate multipliers for similar cases if 'baseline_le' in self.training_df.columns: similar_with_multipliers = similar.merge( self.training_df[['ANB', 'Gender', 'Smoking', 'multiplier']], on=['ANB', 'Gender', 'Smoking'], how='left' ) if 'multiplier' in similar_with_multipliers.columns: valid_multipliers = similar_with_multipliers['multiplier'].dropna() if len(valid_multipliers) > 0: print(f"\nMultiplier statistics for similar cases:") print(f" Mean: {valid_multipliers.mean():.2f}x") print(f" Median: {valid_multipliers.median():.2f}x") print(f" Range: {valid_multipliers.min():.2f}x - {valid_multipliers.max():.2f}x") else: print("⚠️ No similar cases found in certificates data") return similar def calculate_adjusted_mortality(self, age, gender, smoking, multiplier): """ PART 3: Calculate month-by-month mortality schedule with multiplier PART 1 - LE Calculation (annual basis): 1. Load VBT survival counts l(0), l(1), ..., l(30) 2. Calculate ANNUAL mortality: q(t) = (l(t) - l(t+1)) / l(t) 3. Apply multiplier: q_adjusted(t) = q(t) × multiplier 4. Apply 1% annual improvement: q_final(t) = q_adjusted(t) × 0.99^t 5. Calculate annual survival: S(0)=1.0, S(t) = S(t-1) × (1 - q_final(t)) 6. Calculate LE in years: LE_years = Σ S(t) 7. Convert to months: LE_months = LE_years × 12 PART 2 - PV Calculations (monthly basis): 8. Convert annual q_final(t) to monthly rates: q_monthly = 1 - (1 - q_annual)^(1/12) 9. Apply cubic spline interpolation for smooth monthly progression 10. Calculate monthly survival for PV formulas """ print("\n" + "="*80) print("PART 3: CALCULATING ADJUSTED MORTALITY SCHEDULE") print("="*80) # Age validation - VBT tables only have data for ages 65+ original_age = age age_warning = None if age < 65: age_warning = f"User age {age:.0f} is below VBT minimum of 65" print(f"\n⚠️ WARNING: {age_warning}") print(f" Using age 65 as baseline - results may not be accurate for younger individuals") print(f" VBT mortality tables are designed for life settlement candidates (typically 65+)") age = 65 # Step 1: Get VBT table gender_key = 'Male' if gender in ['Male', 'M'] else 'Female' smoking_key = 'S' if smoking in ['S', 'Smoker'] else 'NS' table_key = f"{gender_key}_{smoking_key}" print(f"\nUsing VBT table: {table_key}") vbt_table = self.vbt_tables[table_key] # Get age-specific row age_int = int(round(age)) age_int = max(65, min(95, age_int)) # VBT minimum is 65, not 60 if original_age != age: print(f"Age: {original_age:.0f} → Adjusted to {age_int} (VBT minimum)") else: print(f"Age: {age} → Table age: {age_int}") mortality_row = vbt_table[vbt_table['Age'] == age_int] if len(mortality_row) == 0: print("❌ ERROR: No mortality data for this age") return None, None # PART 1: Calculate LE on ANNUAL basis print(f"\n📊 PART 1: ANNUAL LE CALCULATION") print(f"="*60) # Step 1: Extract survival counts l(t) from VBT table # VBT structure: Column A = Age, Columns B-AF = Duration 0-30 survival counts per 1,000 survival_counts = mortality_row.iloc[0, 1:].values # l(0), l(1), ..., l(30) num_years = len(survival_counts) - 1 # We need pairs for mortality calculation print(f"Survival counts (per 1,000): {len(survival_counts)} durations (0-30)") print(f"First 5: l(0)={survival_counts[0]:.2f}, l(1)={survival_counts[1]:.2f}, l(2)={survival_counts[2]:.2f}, l(3)={survival_counts[3]:.2f}, l(4)={survival_counts[4]:.2f}") # Step 2: Calculate ANNUAL mortality rates: q(t) = (l(t) - l(t+1)) / l(t) annual_mortality = np.zeros(num_years) for t in range(num_years): if survival_counts[t] > 0: annual_mortality[t] = (survival_counts[t] - survival_counts[t+1]) / survival_counts[t] else: annual_mortality[t] = 1.0 # If no survivors, 100% mortality annual_mortality = np.clip(annual_mortality, 0, 1) # Keep in valid range print(f"\nAnnual mortality rates q(t) for first 5 years:") for t in range(min(5, num_years)): print(f" Year {t}: q({t}) = ({survival_counts[t]:.2f} - {survival_counts[t+1]:.2f}) / {survival_counts[t]:.2f} = {annual_mortality[t]:.6f} ({annual_mortality[t]*100:.4f}%)") # Step 3: Apply multiplier to annual mortality adjusted_mortality_annual = annual_mortality * multiplier adjusted_mortality_annual = np.clip(adjusted_mortality_annual, 0, 1) print(f"\nAfter {multiplier:.2f}x multiplier (first 5 years):") for t in range(min(5, num_years)): print(f" Year {t}: q_adjusted({t}) = {annual_mortality[t]:.6f} × {multiplier:.2f} = {adjusted_mortality_annual[t]:.6f} ({adjusted_mortality_annual[t]*100:.4f}%)") # Step 4: Apply 1% annual mortality improvement: q_final(t) = q_adjusted(t) × 0.99^t annual_improvement_factors = 0.99 ** np.arange(num_years) final_mortality_annual = adjusted_mortality_annual * annual_improvement_factors final_mortality_annual = np.clip(final_mortality_annual, 0, 1) print(f"\nAfter 1% annual improvement (first 5 years):") for t in range(min(5, num_years)): print(f" Year {t}: q_final({t}) = {adjusted_mortality_annual[t]:.6f} × 0.99^{t} = {final_mortality_annual[t]:.6f}") # Step 5: Calculate ANNUAL survival probabilities annual_survival = np.zeros(num_years + 1) annual_survival[0] = 1.0 for t in range(num_years): annual_survival[t+1] = annual_survival[t] * (1 - final_mortality_annual[t]) print(f"\nAnnual survival probabilities (first 5 years):") for t in range(min(6, num_years + 1)): print(f" S({t}) = {annual_survival[t]:.6f} ({annual_survival[t]*100:.2f}%)") # Step 6: Calculate LE in YEARS as sum of annual survival le_years = np.sum(annual_survival) # Step 7: Convert to months le_months = le_years * 12 print(f"\n✓ Life Expectancy Calculation:") print(f" LE (years) = Σ S(t) = {le_years:.2f} years") print(f" LE (months) = {le_years:.2f} × 12 = {le_months:.1f} months") # PART 2: Convert to MONTHLY basis for PV calculations print(f"\n📊 PART 2: MONTHLY PV CALCULATION BASIS") print(f"="*60) # Step 8: Convert annual q_final(t) to monthly rates # Formula: q_monthly = 1 - (1 - q_annual)^(1/12) # This ensures that (1-q_monthly)^12 = (1-q_annual), preserving annual survival monthly_mortality_base = 1 - np.power(1 - final_mortality_annual, 1/12) print(f"\nConverting annual rates to monthly (first year sample):") print(f" Year 0 annual q = {final_mortality_annual[0]:.6f}") print(f" Monthly q = 1 - (1 - {final_mortality_annual[0]:.6f})^(1/12) = {monthly_mortality_base[0]:.6f}") print(f" Verification: (1 - {monthly_mortality_base[0]:.6f})^12 = {np.power(1 - monthly_mortality_base[0], 12):.6f}") print(f" Should equal: 1 - {final_mortality_annual[0]:.6f} = {1 - final_mortality_annual[0]:.6f}") # Step 9: Expand each annual rate to 12 monthly rates # Repeat each annual rate 12 times to create monthly schedule monthly_mortality_expanded = np.repeat(monthly_mortality_base, 12) # Step 10: Calculate MONTHLY survival probabilities for PV calculations # S(month_0) = 1.0 # S(month_t) = S(month_t-1) × (1 - q_monthly(t)) max_months = len(monthly_mortality_expanded) monthly_survival = np.zeros(max_months + 1) monthly_survival[0] = 1.0 for t in range(max_months): monthly_survival[t+1] = monthly_survival[t] * (1 - monthly_mortality_expanded[t]) # Calculate death probabilities for PV calculations # death_prob(t) = S(t-1) - S(t) = probability of dying in month t death_probs = -np.diff(monthly_survival) death_probs = np.maximum(death_probs, 0) # Ensure non-negative # Normalize to ensure probabilities sum to 1.0 if np.sum(death_probs) > 0: death_probs = death_probs / np.sum(death_probs) print(f"\nMonthly mortality schedule generated: {max_months} months") print(f"First 12 monthly survival probabilities:") for t in range(min(12, max_months + 1)): print(f" Month {t}: S({t}) = {monthly_survival[t]:.6f} ({monthly_survival[t]*100:.2f}%)") print(f"\n📊 Validation:") print(f" Death probability distribution: {len(death_probs)} monthly probabilities") print(f" Sum of death probabilities: {np.sum(death_probs):.6f} (should be ~1.0)") print(f" Final survival probability: {monthly_survival[-1]:.6f}") print(f"\n✅ CALCULATION COMPLETE") print("="*80 + "\n") return le_months, death_probs def match_premium(self, policy_info): """Match user's policy to historical premium data GENDER MATCHING RULES: - Gender is a REQUIRED match criterion - Only match Male users to Male policies, Female to Female - If no same-gender match exists, apply adjustment: * Male user matched to Female policy: multiply premiums by 1.15 * Female user matched to Male policy: multiply premiums by 0.85 PREMIUM STREAM LENGTH: - Prefer policies with at least 60 months of premium data - If best match has <60 months, try to find next best with more data """ # Extract policy metadata from premiums file carrier_row = self.premiums_df.iloc[1, :] # Row 2 product_row = self.premiums_df.iloc[2, :] # Row 3 issue_year_row = self.premiums_df.iloc[3, :] # Row 4 gender_row = self.premiums_df.iloc[7, :] # Row 8 smoking_row = self.premiums_df.iloc[10, :] # Row 11 face_value_row = self.premiums_df.iloc[6, :] # Row 7 user_gender = policy_info.get('gender', '').lower() # Normalize gender for comparison def normalize_gender(g): g_lower = str(g).lower().strip() if g_lower in ['m', 'male']: return 'male' elif g_lower in ['f', 'female']: return 'female' return g_lower user_gender_normalized = normalize_gender(user_gender) # Helper to count premium stream length for a column def get_premium_stream_length(col_idx): premiums = self.premiums_df.iloc[21:, col_idx] count = 0 for premium in premiums: if pd.notna(premium) and premium != 0: count += 1 return count # Start from column 1 (skip first column which is labels) # Separate into same-gender and different-gender matches same_gender_scores = [] diff_gender_scores = [] print(f"\n" + "="*80) print("PREMIUM MATCHING - GENDER ANALYSIS") print("="*80) print(f" User gender: {user_gender} (normalized: {user_gender_normalized})") for col_idx in range(1, len(carrier_row)): score = 0 policy_gender = normalize_gender(gender_row.iloc[col_idx]) premium_length = get_premium_stream_length(col_idx) # Gender match check (REQUIRED criterion) is_gender_match = (policy_gender == user_gender_normalized) # Exact match scoring (excluding gender - handled separately) if policy_info.get('carrier') and str(carrier_row.iloc[col_idx]).lower() == policy_info['carrier'].lower(): score += 10 if policy_info.get('product') and str(product_row.iloc[col_idx]).lower() == policy_info['product'].lower(): score += 8 if policy_info.get('smoking') and str(smoking_row.iloc[col_idx]).lower() == policy_info['smoking'].lower(): score += 5 else: # Penalize different smoking status score += 2 # Issue year proximity (if available) if policy_info.get('issue_year'): try: policy_year = pd.to_datetime(issue_year_row.iloc[col_idx]).year year_diff = abs(policy_year - int(policy_info['issue_year'])) score += max(0, 5 - year_diff) except: pass # Face value proximity if policy_info.get('face_value'): try: policy_face = float(face_value_row.iloc[col_idx]) user_face = float(policy_info['face_value']) face_ratio = min(policy_face, user_face) / max(policy_face, user_face) score += face_ratio * 5 except: pass # Bonus for having at least 60 months of premium data if premium_length >= 60: score += 3 # Bonus for sufficient data # Store in appropriate list based on gender match if is_gender_match: same_gender_scores.append((col_idx, score, premium_length, policy_gender)) else: diff_gender_scores.append((col_idx, score, premium_length, policy_gender)) print(f" Same-gender policies found: {len(same_gender_scores)}") print(f" Different-gender policies found: {len(diff_gender_scores)}") # Determine best match with gender priority gender_adjustment_applied = False gender_adjustment_factor = 1.0 if same_gender_scores: # Sort by score descending same_gender_scores.sort(key=lambda x: x[1], reverse=True) # Check if best match has at least 60 months best_same = same_gender_scores[0] if best_same[2] < 60 and len(same_gender_scores) > 1: # Look for a match with 60+ months that's still reasonably scored for candidate in same_gender_scores[1:]: if candidate[2] >= 60 and candidate[1] >= best_same[1] * 0.8: print(f" → Best same-gender match has only {best_same[2]} months") print(f" → Found better option with {candidate[2]} months (score {candidate[1]:.1f} vs {best_same[1]:.1f})") best_same = candidate break best_col = best_same[0] best_score = best_same[1] best_length = best_same[2] matched_gender = best_same[3] print(f"\n ✓ GENDER MATCH: User={user_gender_normalized}, Policy={matched_gender}") print(f" Premium stream length: {best_length} months") if best_length < 60: print(f" ⚠️ WARNING: Less than 60 months of premium data available") else: # No same-gender match - use different gender with adjustment print(f"\n ⚠️ NO SAME-GENDER MATCH FOUND") if diff_gender_scores: # Sort by score descending diff_gender_scores.sort(key=lambda x: x[1], reverse=True) # Check for 60+ months preference best_diff = diff_gender_scores[0] if best_diff[2] < 60 and len(diff_gender_scores) > 1: for candidate in diff_gender_scores[1:]: if candidate[2] >= 60 and candidate[1] >= best_diff[1] * 0.8: print(f" → Best diff-gender match has only {best_diff[2]} months") print(f" → Found better option with {candidate[2]} months") best_diff = candidate break best_col = best_diff[0] best_score = best_diff[1] best_length = best_diff[2] matched_gender = best_diff[3] # Apply gender adjustment gender_adjustment_applied = True if user_gender_normalized == 'male' and matched_gender == 'female': gender_adjustment_factor = 1.15 print(f" → Male user matched to Female policy: applying 1.15x premium adjustment") elif user_gender_normalized == 'female' and matched_gender == 'male': gender_adjustment_factor = 0.85 print(f" → Female user matched to Male policy: applying 0.85x premium adjustment") print(f" Premium stream length: {best_length} months") if best_length < 60: print(f" ⚠️ WARNING: Less than 60 months of premium data available") else: # No policies at all - this shouldn't happen print(f" ❌ ERROR: No policies found in premium data!") return [] print("="*80) # FIX 3: Log matched policy details print(f"\n" + "="*80) print("MATCHED POLICY DETAILS") print("="*80) print(f" Policy Column Index: {best_col}") print(f" Match Score: {best_score:.1f}") print(f" Carrier: {carrier_row.iloc[best_col]}") print(f" Product: {product_row.iloc[best_col]}") print(f" Face Value: ${face_value_row.iloc[best_col]:,.0f}" if pd.notna(face_value_row.iloc[best_col]) else " Face Value: N/A") print(f" Gender: {gender_row.iloc[best_col]}") print(f" Smoking: {smoking_row.iloc[best_col]}") try: issue_year = pd.to_datetime(issue_year_row.iloc[best_col]).year print(f" Issue Year: {issue_year}") except: print(f" Issue Year: {issue_year_row.iloc[best_col]}") # Show DOB and Issue Date if available try: dob_row = self.premiums_df.iloc[4, :] # Row 5 - DOB print(f" DOB: {dob_row.iloc[best_col]}") except: pass try: issue_date_row = self.premiums_df.iloc[5, :] # Row 6 - Issue Date print(f" Issue Date: {issue_date_row.iloc[best_col]}") except: pass print("="*80 + "\n") # Extract premium stream from best matching policy premium_stream = [] dates = self.premiums_df.iloc[21:, 0] # Dates starting from row 22 premiums = self.premiums_df.iloc[21:, best_col] # Premiums for matched policy for date, premium in zip(dates, premiums): if pd.notna(premium) and premium != 0: premium_stream.append({ 'date': pd.to_datetime(date), 'amount': float(premium) }) # Log premium stream summary print(f"\n" + "="*80) print("PREMIUM ADJUSTMENT SUMMARY") print("="*80) print(f" Premium stream length: {len(premium_stream)} months") # Apply gender adjustment (determined above based on gender matching logic) # Gender adjustment factor is already set: # - 1.0 if same gender match # - 1.15 if male user matched to female policy # - 0.85 if female user matched to male policy adjustment_factor = gender_adjustment_factor if gender_adjustment_applied: print(f" Gender adjustment applied: {gender_adjustment_factor:.2f}x") print(f" User gender: {user_gender_normalized}") print(f" Policy gender: {matched_gender}") else: print(f" Gender adjustment: None (same gender match)") # Check smoking mismatch and apply additional adjustment policy_smoking = str(smoking_row.iloc[best_col]).lower() user_smoking = policy_info.get('smoking', '').lower() smoking_match = policy_smoking == user_smoking if not smoking_match: # Smoker premiums are 20% more expensive if user_smoking in ['s', 'smoker']: adjustment_factor *= 1.2 print(f" Smoking adjustment: 1.20x (user is smoker, policy is non-smoker)") else: adjustment_factor *= 0.83 print(f" Smoking adjustment: 0.83x (user is non-smoker, policy is smoker)") else: print(f" Smoking adjustment: None (same smoking status)") print(f" Combined adjustment factor: {adjustment_factor:.2f}x") # Apply adjustment for item in premium_stream: item['amount'] *= adjustment_factor print("="*80) # PART 3: Age-based premium adjustment print(f"\n" + "="*80) print("PART 3: AGE-BASED PREMIUM ADJUSTMENT") print("="*80) # FIX 2: Robust date parsing with error handling age_multiplier = 1.0 try: # Get DOB and Issue Date rows from premiums file dob_row = self.premiums_df.iloc[4, :] # Row 5 - DOB issue_date_row = self.premiums_df.iloc[5, :] # Row 6 - Issue Date # Helper function to parse dates robustly def parse_date_robust(date_value, field_name): """Parse date with multiple strategies, handling state codes and bad data""" try: # Try direct pandas parsing return pd.to_datetime(date_value) except Exception as e1: # Strategy 2: Look for 4-digit year in the string import re date_str = str(date_value) year_match = re.search(r'\b(19\d{2}|20\d{2})\b', date_str) if year_match: year = int(year_match.group(1)) # Assume January 1st print(f" ⚠️ {field_name}: Found year {year} in '{date_str}', using {year}-01-01") return pd.to_datetime(f"{year}-01-01") else: # Can't parse - raise error raise ValueError(f"Could not parse date from '{date_str}' (not a valid date, may be state code or other data)") # Get matched policy's DOB and Issue Date with robust parsing try: matched_dob = parse_date_robust(dob_row.iloc[best_col], "DOB") matched_issue_date = parse_date_robust(issue_date_row.iloc[best_col], "Issue Date") except ValueError as ve: print(f" ⚠️ Date parsing error: {ve}") print(f" Skipping age adjustment") raise # Re-raise to outer exception handler # Calculate matched policy issue age matched_issue_age = (matched_issue_date - matched_dob).days / 365.25 # Calculate user's issue age if policy_info.get('dob') and policy_info.get('issue_year'): user_dob = pd.to_datetime(policy_info['dob']) user_issue_year = int(policy_info['issue_year']) # Assume January 1st for issue date user_issue_date = pd.to_datetime(f"{user_issue_year}-01-01") user_issue_age = (user_issue_date - user_dob).days / 365.25 # Calculate age difference age_difference = user_issue_age - matched_issue_age # Calculate age adjustment factor: exp(0.06 * age_difference) # Premiums increase exponentially with age age_multiplier = np.exp(0.06 * age_difference) print(f" Matched policy DOB: {matched_dob.strftime('%Y-%m-%d')}") print(f" Matched policy issue date: {matched_issue_date.strftime('%Y-%m-%d')}") print(f" Matched policy issue age: {matched_issue_age:.1f} years") print(f" User issue age: {user_issue_age:.1f} years") print(f" Age difference: {age_difference:.1f} years") print(f" Age adjustment factor: {age_multiplier:.2f}x") print(f" Example: 15 years older → e^(0.06*15) = {np.exp(0.06*15):.2f}x premium") # Apply age adjustment to premium stream for item in premium_stream: item['amount'] *= age_multiplier print(f" ✓ Applied age adjustment to {len(premium_stream)} premium payments") else: print(f" ⚠️ User DOB or Issue Year not provided - skipping age adjustment") except Exception as e: print(f" ⚠️ Could not calculate age adjustment: {e}") print(f" Using age_multiplier = 1.0 (no adjustment)") print("="*80 + "\n") return premium_stream def calculate_policy_value(self, face_value, monthly_mortality, premium_stream, csv_amount=0, current_age=None): """Calculate NPV of policy at 20% IRR""" discount_rate = 0.20 # 20% annual monthly_rate = (1 + discount_rate) ** (1/12) - 1 # PART 2: Extend premium stream to policy maturity (age 121) maturity_age = 121 # Standard policy maturity age if current_age and len(premium_stream) > 0: months_to_maturity = int((maturity_age - current_age) * 12) months_needed = len(monthly_mortality) # Match mortality schedule length print(f"\n" + "="*80) print("PART 2: EXTENDING PREMIUM STREAM TO POLICY MATURITY") print("="*80) print(f" Current age: {current_age:.1f} years") print(f" Maturity age: {maturity_age} years") print(f" Months to maturity: {months_to_maturity}") print(f" Mortality schedule length: {months_needed} months") print(f" Current premium stream length: {len(premium_stream)} payments") if len(premium_stream) < months_needed: # FIX 1: Use median of last 12 premiums for extension # (avoids using balloon payments or outliers) if len(premium_stream) >= 12: # Get last 12 premium amounts last_12_amounts = [p['amount'] for p in premium_stream[-12:]] extension_amount = np.median(last_12_amounts) print(f" Using median of last 12 premiums for extension: ${extension_amount:,.2f}/month") elif len(premium_stream) >= 120: # Use premium from month 120 (year 10) extension_amount = premium_stream[119]['amount'] print(f" Using month 120 premium for extension: ${extension_amount:,.2f}/month") else: # Fallback: use median of all available premiums all_amounts = [p['amount'] for p in premium_stream] extension_amount = np.median(all_amounts) print(f" Using median of all {len(premium_stream)} premiums: ${extension_amount:,.2f}/month") last_premium_date = premium_stream[-1]['date'] # Extend with the calculated premium amount num_extensions = months_needed - len(premium_stream) print(f" Extending by {num_extensions} months at ${extension_amount:,.2f}/month") for i in range(num_extensions): new_date = last_premium_date + timedelta(days=30 * (i + 1)) premium_stream.append({ 'date': new_date, 'amount': extension_amount }) print(f" ✓ Extended premium stream to {len(premium_stream)} payments") else: print(f" ✓ Premium stream already covers mortality schedule") print("="*80 + "\n") # Calculate PV of death benefit pv_death_benefit = 0 cumulative_survival = 1.0 for month, mortality in enumerate(monthly_mortality): # Probability of dying in this specific month prob_death_this_month = mortality * cumulative_survival # Discount back to present discount_factor = 1 / ((1 + monthly_rate) ** month) # Add to PV pv_death_benefit += face_value * prob_death_this_month * discount_factor # Update cumulative survival cumulative_survival *= (1 - mortality) # PART 4: Calculate PV of premiums with detailed logging print(f"\n" + "="*80) print("PART 4: PV CALCULATION VERIFICATION") print("="*80) print(f"Formula: PV_Premiums = Σ[Premium(t) × (1-F(t)) × (1.20)^(-t/12)]") print(f" where (1-F(t)) = probability person is still alive at month t") print(f" and 1.20^(-t/12) = discount factor at 20% annual rate") print("="*80 + "\n") pv_premiums = 0 current_date = datetime.now() cumulative_survival = 1.0 csv_remaining = csv_amount # Sample months to show detailed calculations sample_months = [0, 11, 23, 59] # Months 1, 12, 24, 60 for month in range(len(monthly_mortality)): # Find premium for this month month_date = current_date + timedelta(days=30 * month) # Get premium amount (find closest match in premium stream) premium_amount = 0 for prem in premium_stream: if prem['date'] >= month_date: premium_amount = prem['amount'] break # If CSV is available, use it first original_premium = premium_amount if csv_remaining > 0: payment = min(csv_remaining, premium_amount) csv_remaining -= payment premium_amount -= payment # Remaining premium after CSV # Only count premium if person is still alive prob_alive = cumulative_survival # Discount back to present discount_factor = 1 / ((1 + monthly_rate) ** month) # Calculate PV contribution pv_contribution = premium_amount * prob_alive * discount_factor # Add to PV pv_premiums += pv_contribution # Show detailed calculation for sample months if month in sample_months: print(f"Month {month + 1} calculation:") print(f" Premium: ${premium_amount:,.2f}") if original_premium != premium_amount: print(f" (Original: ${original_premium:,.2f}, CSV offset: ${original_premium - premium_amount:,.2f})") print(f" Prob alive (1-F(t)): {prob_alive:.6f} ({prob_alive*100:.2f}%)") print(f" Discount factor: {discount_factor:.6f}") print(f" PV contribution: ${pv_contribution:,.2f}") print() # Update survival probability if month < len(monthly_mortality): cumulative_survival *= (1 - monthly_mortality[month]) print(f"✓ Total PV of Premiums: ${pv_premiums:,.2f}") print(f"✓ Total PV of Death Benefit: ${pv_death_benefit:,.2f}") print("="*80 + "\n") # Net policy value policy_value = pv_death_benefit - pv_premiums return { 'policy_value': policy_value, 'pv_death_benefit': pv_death_benefit, 'pv_premiums': pv_premiums, 'face_value': face_value } # Initialize engine on module load print("Initializing Life Settlements Valuation Engine...") engine = LifeSettlementsEngine() print("Engine ready!")
"""
Life Settlements Valuation Engine
Calculates life expectancy, premium streams, and policy valuations
"""
import pandas as pd
import numpy as np
from scipy.interpolate import CubicSpline
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import LabelEncoder
from datetime import datetime, timedelta
import pickle
import os
import warnings
warnings.filterwarnings('ignore')
# Get the directory where this script is located
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
DATA_DIR = os.path.join(SCRIPT_DIR, 'data')
class LifeSettlementsEngine:
def __init__(self, data_dir=None):
# Use provided data_dir or default to script's data directory
self.data_dir = data_dir or DATA_DIR
# Check for cached model to speed up startup
model_cache_path = os.path.join(self.data_dir, 'trained_model.pkl')
if os.path.exists(model_cache_path):
print("="*80)
print("LOADING CACHED MODEL & DATA")
print("="*80)
print(f"Found cached model at {model_cache_path}")
print("Loading from cache (this should take ~2 seconds)...")
try:
with open(model_cache_path, 'rb') as f:
cached = pickle.load(f)
# Load model and training data
self.mortality_model = cached['model']
self.label_encoders = cached['label_encoders']
self.training_df = cached['training_df']
self.feature_names = cached['feature_names']
# Load all data files from cache
self.screener_questions = cached['screener_questions']
self.mapped_impairments = cached['mapped_impairments']
self.vbt_tables = cached['vbt_tables']
self.premiums_df = cached['premiums_df']
self.certificates_df = cached['certificates_df']
print("✓ Model and all data loaded from cache!")
print(f"✓ Training data: {len(self.training_df)} certificates")
print(f"✓ VBT tables: {len(self.vbt_tables)} tables")
print(f"✓ Premiums data: {len(self.premiums_df)} rows")
print("="*80 + "\n")
return # Skip training and data loading
except Exception as e:
print(f"⚠️ Error loading cached model: {e}")
print("Will train model from scratch...")
print("="*80 + "\n")
# Otherwise, load data and train as normal
print("No cached model found - training from scratch...")
self.load_data()
self.train_mortality_model()
def load_data(self):
"""Load all reference data files"""
print("Loading data files...")
# Load screener questions
self.screener_questions = pd.read_excel(os.path.join(self.data_dir, 'screener_questions_v2.xlsx'))
# Load mapped impairments
self.mapped_impairments = pd.read_excel(os.path.join(self.data_dir, 'mapped_impairments__1_.xlsx'))
# Load VBT mortality tables
self.vbt_tables = {
'Female_NS': pd.read_excel(os.path.join(self.data_dir, 'VBT_Female_NS.xlsx')),
'Female_S': pd.read_excel(os.path.join(self.data_dir, 'VBT_Female_S.xlsx')),
'Male_NS': pd.read_excel(os.path.join(self.data_dir, 'VBT_Male_NS.xlsx')),
'Male_S': pd.read_excel(os.path.join(self.data_dir, 'VBT_Male_S.xlsx'))
}
# Load premiums data
self.premiums_df = pd.read_excel(os.path.join(self.data_dir, 'premiums_for_model.xlsx'), header=None)
# Load certificates data for training
self.certificates_df = pd.read_csv(os.path.join(self.data_dir, 'Certificates for claude.csv'))
# Add supplemental impairment mappings for new conditions
self._add_supplemental_impairments()
print("Data loaded successfully!")
def _add_supplemental_impairments(self):
"""Add additional impairment mappings not in the Excel file"""