Spaces:
Sleeping
Sleeping
api
Browse files
app.py
CHANGED
@@ -529,16 +529,10 @@ async def get_customer_analysis(customer_id: str):
|
|
529 |
async def get_financial_recommendations(customer_id: str):
|
530 |
"""
|
531 |
Get hyper-personalized financial recommendations for a customer
|
532 |
-
|
533 |
-
Parameters:
|
534 |
-
- customer_id: The ID of the customer
|
535 |
-
|
536 |
-
Returns:
|
537 |
-
- JSON object containing personalized financial recommendations and insights
|
538 |
"""
|
539 |
try:
|
540 |
# Validate customer
|
541 |
-
if customer_id not in customer_profiles['Customer_Id'].
|
542 |
raise HTTPException(
|
543 |
status_code=status.HTTP_404_NOT_FOUND,
|
544 |
detail="Customer not found"
|
@@ -553,21 +547,37 @@ async def get_financial_recommendations(customer_id: str):
|
|
553 |
# Get social sentiment data
|
554 |
customer_sentiment = customer_Media[customer_Media['Customer_Id'] == customer_id]
|
555 |
|
556 |
-
# Calculate financial metrics
|
557 |
-
|
558 |
-
|
559 |
-
|
560 |
-
|
561 |
-
|
562 |
-
|
563 |
-
|
564 |
-
|
565 |
-
|
566 |
-
|
567 |
-
|
568 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
569 |
|
570 |
-
# Generate
|
571 |
recommendations = {
|
572 |
"investment_recommendations": [],
|
573 |
"savings_recommendations": [],
|
@@ -576,67 +586,77 @@ async def get_financial_recommendations(customer_id: str):
|
|
576 |
"action_items": []
|
577 |
}
|
578 |
|
579 |
-
# Investment recommendations based on age
|
580 |
if age < 30:
|
581 |
-
recommendations["investment_recommendations"]
|
582 |
"Consider starting a retirement account with aggressive growth funds",
|
583 |
"Look into low-cost index funds for long-term growth",
|
584 |
"Build an emergency fund of 3-6 months expenses"
|
585 |
-
]
|
586 |
elif age < 50:
|
587 |
-
recommendations["investment_recommendations"]
|
588 |
"Diversify investment portfolio with mix of stocks and bonds",
|
589 |
"Consider real estate investment opportunities",
|
590 |
"Maximize retirement contributions"
|
591 |
-
]
|
592 |
else:
|
593 |
-
recommendations["investment_recommendations"]
|
594 |
"Focus on preservation of capital",
|
595 |
"Consider dividend-paying stocks",
|
596 |
"Review retirement withdrawal strategy"
|
597 |
-
]
|
598 |
|
599 |
# Savings recommendations based on spending ratio
|
600 |
if spending_ratio > 70:
|
601 |
-
recommendations["savings_recommendations"]
|
602 |
"Critical: Reduce monthly expenses",
|
603 |
"Implement 50/30/20 budgeting rule",
|
604 |
"Identify and cut non-essential spending"
|
605 |
-
]
|
606 |
elif spending_ratio > 50:
|
607 |
-
recommendations["savings_recommendations"]
|
608 |
"Look for additional saving opportunities",
|
609 |
"Consider automated savings transfers",
|
610 |
"Review subscription services"
|
611 |
-
]
|
612 |
else:
|
613 |
-
recommendations["savings_recommendations"]
|
614 |
"Maintain current saving habits",
|
615 |
"Consider increasing investment contributions",
|
616 |
"Look into tax-advantaged savings options"
|
617 |
-
]
|
618 |
|
619 |
# Budget recommendations based on purchase patterns
|
620 |
-
|
621 |
-
|
622 |
-
|
623 |
-
|
624 |
-
|
625 |
-
|
626 |
-
|
627 |
-
|
628 |
-
|
629 |
-
|
630 |
-
|
631 |
-
|
632 |
-
|
633 |
-
|
634 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
635 |
risk_level = "Balanced"
|
636 |
|
637 |
recommendations["risk_assessment"] = f"Based on your profile and behavior: {risk_level} risk tolerance"
|
638 |
|
639 |
-
#
|
640 |
recommendations["action_items"] = [
|
641 |
{
|
642 |
"priority": "High",
|
@@ -675,12 +695,9 @@ async def get_financial_recommendations(customer_id: str):
|
|
675 |
"analysis_timestamp": datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
676 |
}
|
677 |
|
678 |
-
except HTTPException:
|
679 |
-
raise
|
680 |
except Exception as e:
|
681 |
logger.error(f"Error processing financial recommendations for customer {customer_id}: {str(e)}")
|
682 |
raise HTTPException(
|
683 |
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
684 |
detail=f"Error processing request: {str(e)}"
|
685 |
-
)
|
686 |
-
|
|
|
529 |
async def get_financial_recommendations(customer_id: str):
|
530 |
"""
|
531 |
Get hyper-personalized financial recommendations for a customer
|
|
|
|
|
|
|
|
|
|
|
|
|
532 |
"""
|
533 |
try:
|
534 |
# Validate customer
|
535 |
+
if customer_id not in customer_profiles['Customer_Id'].values:
|
536 |
raise HTTPException(
|
537 |
status_code=status.HTTP_404_NOT_FOUND,
|
538 |
detail="Customer not found"
|
|
|
547 |
# Get social sentiment data
|
548 |
customer_sentiment = customer_Media[customer_Media['Customer_Id'] == customer_id]
|
549 |
|
550 |
+
# Calculate financial metrics with type conversion
|
551 |
+
try:
|
552 |
+
total_spent = customer_purchases['Amount (In Dollars)'].astype(float).sum()
|
553 |
+
avg_transaction = customer_purchases['Amount (In Dollars)'].astype(float).mean()
|
554 |
+
|
555 |
+
# Convert purchase dates to datetime
|
556 |
+
customer_purchases['Purchase_Date'] = pd.to_datetime(customer_purchases['Purchase_Date'])
|
557 |
+
date_range = (customer_purchases['Purchase_Date'].max() - customer_purchases['Purchase_Date'].min()).days
|
558 |
+
purchase_frequency = len(customer_purchases) / (date_range + 1) if date_range > 0 else 0
|
559 |
+
|
560 |
+
except (ValueError, TypeError) as e:
|
561 |
+
logger.error(f"Error processing numerical calculations: {str(e)}")
|
562 |
+
total_spent = 0
|
563 |
+
avg_transaction = 0
|
564 |
+
purchase_frequency = 0
|
565 |
+
|
566 |
+
try:
|
567 |
+
# Convert age and income to float
|
568 |
+
age = float(customer_profile['Age'])
|
569 |
+
income = float(customer_profile['Income per year (in dollars)'])
|
570 |
+
|
571 |
+
# Calculate spending ratio
|
572 |
+
spending_ratio = (total_spent / income) * 100 if income > 0 else 0
|
573 |
+
|
574 |
+
except (ValueError, TypeError) as e:
|
575 |
+
logger.error(f"Error processing profile data: {str(e)}")
|
576 |
+
age = 0
|
577 |
+
income = 0
|
578 |
+
spending_ratio = 0
|
579 |
|
580 |
+
# Generate recommendations based on processed data
|
581 |
recommendations = {
|
582 |
"investment_recommendations": [],
|
583 |
"savings_recommendations": [],
|
|
|
586 |
"action_items": []
|
587 |
}
|
588 |
|
589 |
+
# Investment recommendations based on age
|
590 |
if age < 30:
|
591 |
+
recommendations["investment_recommendations"] = [
|
592 |
"Consider starting a retirement account with aggressive growth funds",
|
593 |
"Look into low-cost index funds for long-term growth",
|
594 |
"Build an emergency fund of 3-6 months expenses"
|
595 |
+
]
|
596 |
elif age < 50:
|
597 |
+
recommendations["investment_recommendations"] = [
|
598 |
"Diversify investment portfolio with mix of stocks and bonds",
|
599 |
"Consider real estate investment opportunities",
|
600 |
"Maximize retirement contributions"
|
601 |
+
]
|
602 |
else:
|
603 |
+
recommendations["investment_recommendations"] = [
|
604 |
"Focus on preservation of capital",
|
605 |
"Consider dividend-paying stocks",
|
606 |
"Review retirement withdrawal strategy"
|
607 |
+
]
|
608 |
|
609 |
# Savings recommendations based on spending ratio
|
610 |
if spending_ratio > 70:
|
611 |
+
recommendations["savings_recommendations"] = [
|
612 |
"Critical: Reduce monthly expenses",
|
613 |
"Implement 50/30/20 budgeting rule",
|
614 |
"Identify and cut non-essential spending"
|
615 |
+
]
|
616 |
elif spending_ratio > 50:
|
617 |
+
recommendations["savings_recommendations"] = [
|
618 |
"Look for additional saving opportunities",
|
619 |
"Consider automated savings transfers",
|
620 |
"Review subscription services"
|
621 |
+
]
|
622 |
else:
|
623 |
+
recommendations["savings_recommendations"] = [
|
624 |
"Maintain current saving habits",
|
625 |
"Consider increasing investment contributions",
|
626 |
"Look into tax-advantaged savings options"
|
627 |
+
]
|
628 |
|
629 |
# Budget recommendations based on purchase patterns
|
630 |
+
try:
|
631 |
+
category_spending = customer_purchases.groupby('Category')['Amount (In Dollars)'].astype(float).sum()
|
632 |
+
top_spending_categories = category_spending.nlargest(3)
|
633 |
+
|
634 |
+
recommendations["budget_recommendations"] = [
|
635 |
+
f"Highest spending in {cat}: ${amount:.2f}"
|
636 |
+
for cat, amount in top_spending_categories.items()
|
637 |
+
]
|
638 |
+
except Exception as e:
|
639 |
+
logger.error(f"Error processing category spending: {str(e)}")
|
640 |
+
recommendations["budget_recommendations"] = ["Unable to process category spending"]
|
641 |
+
|
642 |
+
# Risk assessment based on sentiment
|
643 |
+
try:
|
644 |
+
recent_sentiment = customer_sentiment['Sentiment_Score'].astype(float).mean()
|
645 |
+
if pd.isna(recent_sentiment):
|
646 |
+
risk_level = "Balanced"
|
647 |
+
elif recent_sentiment < -0.2:
|
648 |
+
risk_level = "Conservative"
|
649 |
+
elif recent_sentiment > 0.2:
|
650 |
+
risk_level = "Moderate"
|
651 |
+
else:
|
652 |
+
risk_level = "Balanced"
|
653 |
+
except Exception as e:
|
654 |
+
logger.error(f"Error processing sentiment: {str(e)}")
|
655 |
risk_level = "Balanced"
|
656 |
|
657 |
recommendations["risk_assessment"] = f"Based on your profile and behavior: {risk_level} risk tolerance"
|
658 |
|
659 |
+
# Action items
|
660 |
recommendations["action_items"] = [
|
661 |
{
|
662 |
"priority": "High",
|
|
|
695 |
"analysis_timestamp": datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
696 |
}
|
697 |
|
|
|
|
|
698 |
except Exception as e:
|
699 |
logger.error(f"Error processing financial recommendations for customer {customer_id}: {str(e)}")
|
700 |
raise HTTPException(
|
701 |
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
702 |
detail=f"Error processing request: {str(e)}"
|
703 |
+
)
|
|