Spaces:
Sleeping
Sleeping
api
Browse files- DataSetSample.xlsx +0 -0
- app.py +158 -33
DataSetSample.xlsx
CHANGED
Binary files a/DataSetSample.xlsx and b/DataSetSample.xlsx differ
|
|
app.py
CHANGED
@@ -525,37 +525,162 @@ async def get_customer_analysis(customer_id: str):
|
|
525 |
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
526 |
detail=f"Error processing request: {str(e)}"
|
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 |
|
|
|
525 |
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
526 |
detail=f"Error processing request: {str(e)}"
|
527 |
)
|
528 |
+
@app.get("/financial-recommendations/{customer_id}")
|
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'].unique():
|
542 |
+
raise HTTPException(
|
543 |
+
status_code=status.HTTP_404_NOT_FOUND,
|
544 |
+
detail="Customer not found"
|
545 |
+
)
|
546 |
+
|
547 |
+
# Get customer profile data
|
548 |
+
customer_profile = customer_profiles[customer_profiles['Customer_Id'] == customer_id].iloc[0]
|
549 |
+
|
550 |
+
# Get purchase history
|
551 |
+
customer_purchases = purchase_history[purchase_history['Customer_Id'] == customer_id]
|
552 |
+
|
553 |
+
# Get social sentiment data
|
554 |
+
customer_sentiment = customer_Media[customer_Media['Customer_Id'] == customer_id]
|
555 |
+
|
556 |
+
# Calculate financial metrics
|
557 |
+
total_spent = customer_purchases['Amount (In Dollars)'].sum()
|
558 |
+
avg_transaction = customer_purchases['Amount (In Dollars)'].mean()
|
559 |
+
purchase_frequency = len(customer_purchases) / (
|
560 |
+
(customer_purchases['Purchase_Date'].max() - customer_purchases['Purchase_Date'].min()).days + 1
|
561 |
+
)
|
562 |
+
|
563 |
+
# Denormalize age and income
|
564 |
+
age = customer_profile['Age'] * scaler.scale_[0] + scaler.mean_[0]
|
565 |
+
income = customer_profile['Income per year (in dollars)'] * scaler.scale_[1] + scaler.mean_[1]
|
566 |
+
|
567 |
+
# Calculate spending ratio
|
568 |
+
spending_ratio = (total_spent / income) * 100 if income > 0 else 0
|
569 |
+
|
570 |
+
# Generate personalized recommendations
|
571 |
+
recommendations = {
|
572 |
+
"investment_recommendations": [],
|
573 |
+
"savings_recommendations": [],
|
574 |
+
"budget_recommendations": [],
|
575 |
+
"risk_assessment": "",
|
576 |
+
"action_items": []
|
577 |
+
}
|
578 |
+
|
579 |
+
# Investment recommendations based on age and income
|
580 |
+
if age < 30:
|
581 |
+
recommendations["investment_recommendations"].extend([
|
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"].extend([
|
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"].extend([
|
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"].extend([
|
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"].extend([
|
608 |
+
"Look for additional saving opportunities",
|
609 |
+
"Consider automated savings transfers",
|
610 |
+
"Review subscription services"
|
611 |
+
])
|
612 |
+
else:
|
613 |
+
recommendations["savings_recommendations"].extend([
|
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 |
+
category_spending = customer_purchases.groupby('Category')['Amount (In Dollars)'].sum()
|
621 |
+
top_spending_categories = category_spending.nlargest(3)
|
622 |
+
|
623 |
+
recommendations["budget_recommendations"].extend([
|
624 |
+
f"Highest spending in {cat}: ${amount:.2f}"
|
625 |
+
for cat, amount in top_spending_categories.items()
|
626 |
+
])
|
627 |
+
|
628 |
+
# Risk assessment based on sentiment and spending patterns
|
629 |
+
recent_sentiment = customer_sentiment.sort_values('Timestamp', ascending=False)['Sentiment_Score'].mean()
|
630 |
+
if recent_sentiment < -0.2:
|
631 |
+
risk_level = "Conservative"
|
632 |
+
elif recent_sentiment > 0.2:
|
633 |
+
risk_level = "Moderate"
|
634 |
+
else:
|
635 |
+
risk_level = "Balanced"
|
636 |
+
|
637 |
+
recommendations["risk_assessment"] = f"Based on your profile and behavior: {risk_level} risk tolerance"
|
638 |
+
|
639 |
+
# Generate action items
|
640 |
+
recommendations["action_items"] = [
|
641 |
+
{
|
642 |
+
"priority": "High",
|
643 |
+
"action": "Review and adjust monthly budget",
|
644 |
+
"impact": "Immediate",
|
645 |
+
"timeline": "Next 30 days"
|
646 |
+
},
|
647 |
+
{
|
648 |
+
"priority": "Medium",
|
649 |
+
"action": "Rebalance investment portfolio",
|
650 |
+
"impact": "Long-term",
|
651 |
+
"timeline": "Next 90 days"
|
652 |
+
},
|
653 |
+
{
|
654 |
+
"priority": "Low",
|
655 |
+
"action": "Schedule financial planning review",
|
656 |
+
"impact": "Strategic",
|
657 |
+
"timeline": "Next 6 months"
|
658 |
+
}
|
659 |
+
]
|
660 |
+
|
661 |
+
return {
|
662 |
+
"customer_id": customer_id,
|
663 |
+
"financial_summary": {
|
664 |
+
"total_spent": float(total_spent),
|
665 |
+
"average_transaction": float(avg_transaction),
|
666 |
+
"spending_ratio": float(spending_ratio),
|
667 |
+
"purchase_frequency": float(purchase_frequency)
|
668 |
+
},
|
669 |
+
"risk_profile": {
|
670 |
+
"age_group": "Young" if age < 30 else "Middle-aged" if age < 50 else "Senior",
|
671 |
+
"income_bracket": "Low" if income < 50000 else "Medium" if income < 100000 else "High",
|
672 |
+
"risk_tolerance": risk_level
|
673 |
+
},
|
674 |
+
"recommendations": recommendations,
|
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 |
|