import requests import json from typing import Dict, Any, List from app.config import settings from app.models.ai_models import AIAnalysisRequest, AIAnalysisResponse, AISwarmAgent import pandas as pd # Popular mutual fund categories with scheme codes POPULAR_FUNDS = { 'Large Cap Equity': { 'HDFC Top 100 Fund': '120503', 'ICICI Pru Bluechip Fund': '120505', 'SBI Bluechip Fund': '125497', 'Axis Bluechip Fund': '120503', 'Kotak Bluechip Fund': '118989' }, 'Mid Cap Equity': { 'HDFC Mid-Cap Opportunities Fund': '118551', 'ICICI Pru Mid Cap Fund': '120544', 'Kotak Emerging Equity Fund': '118999', 'SBI Magnum Mid Cap Fund': '100281', 'DSP Mid Cap Fund': '112618' }, 'Small Cap Equity': { 'SBI Small Cap Fund': '122639', 'DSP Small Cap Fund': '112618', 'HDFC Small Cap Fund': '118551', 'Axis Small Cap Fund': '125487', 'Kotak Small Cap Fund': '119028' }, 'ELSS (Tax Saving)': { 'Axis Long Term Equity Fund': '125494', 'HDFC Tax Saver': '100277', 'SBI Tax Saver': '125497', 'ICICI Pru ELSS Tax Saver': '120503', 'Kotak Tax Saver': '118989' }, 'Debt Funds': { 'HDFC Corporate Bond Fund': '101762', 'ICICI Pru Corporate Bond Fund': '120503', 'SBI Corporate Bond Fund': '125497', 'Kotak Corporate Bond Fund': '118989', 'Axis Corporate Debt Fund': '125494' }, 'Hybrid Funds': { 'HDFC Hybrid Equity Fund': '118551', 'ICICI Pru Balanced Advantage Fund': '120505', 'SBI Equity Hybrid Fund': '125497', 'Kotak Equity Hybrid Fund': '118999', 'Axis Hybrid Fund': '125494' } } # AI Agent Prompts for Mutual Funds FUND_SELECTION_PROMPT = """ You are an expert Indian mutual fund selection specialist with deep knowledge of fund analysis, performance evaluation, and fund house comparisons for Indian mutual fund markets. Your responsibilities: 1. Analyze fund performance across different time periods (1Y, 3Y, 5Y) 2. Evaluate expense ratios and their impact on long-term returns 3. Assess fund manager track record and consistency 4. Compare funds within categories using quantitative metrics 5. Identify funds with consistent alpha generation 6. Evaluate fund house stability and investor service quality Focus areas for Indian mutual fund analysis: - Performance consistency across market cycles - Expense ratio optimization (direct vs regular plans) - Fund manager tenure and investment philosophy - AUM growth and scalability - Category benchmarking and peer comparison - Tax efficiency and dividend distribution policy - Goal-based fund recommendations Provide specific recommendations with rationale for Indian investors. """ GOAL_PLANNING_PROMPT = """ You are an expert in goal-based financial planning specialized in mapping investment goals to appropriate mutual fund strategies for Indian investors. Your responsibilities: 1. Analyze client goals for timeline, amount, and priority 2. Map goals to appropriate fund categories and asset allocation 3. Design SIP strategies aligned with goal timelines 4. Recommend optimal fund combinations for multiple goals 5. Plan step-up SIP strategies for inflation adjustment 6. Create tax-efficient investment strategies including ELSS Goal-based fund mapping expertise: - Short-term goals (1-3 years): Debt funds, liquid funds - Medium-term goals (3-7 years): Hybrid funds, large cap equity - Long-term goals (7+ years): Mid cap, small cap equity - Tax-saving goals: ELSS funds with 3-year lock-in - Retirement planning: Systematic equity exposure with debt balancing - Emergency funds: Liquid funds with instant redemption capability Provide actionable SIP recommendations with specific amounts and fund selections. """ RISK_ASSESSMENT_PROMPT = """ You are an expert in mutual fund risk analysis with extensive knowledge of fund-specific risks, category risks, and portfolio risk management for Indian mutual fund investments. Your responsibilities: 1. Assess fund-specific risks including manager risk, style drift 2. Analyze category concentration and diversification needs 3. Evaluate expense ratio impact on long-term wealth creation 4. Assess liquidity risks across different fund categories 5. Identify regulatory and tax-related risks 6. Recommend risk mitigation strategies Focus on Indian mutual fund risk factors: - Fund manager tenure and philosophy changes - Category concentration and overlap analysis - Expense ratio drag on returns over long periods - Exit load structures and liquidity constraints - Tax implications of different fund types - Market timing risks in equity fund investments - Credit risks in debt fund categories Provide practical risk management recommendations for Indian mutual fund investors. """ FUND_ALLOCATION_PROMPT = """ You are an expert in mutual fund portfolio allocation and performance analysis, with deep knowledge of fund analysis, performance evaluation, and fund house comparisons for the Indian mutual fund market. Your role is to evaluate fund performance, provide insights on key metrics, and generate tailored recommendations based on individual investor needs and goals. Your Responsibilities: 1. Fund Performance Analysis: Analyze fund performance over different time periods (1Y, 3Y, 5Y) to assess consistency and growth potential. 2. Expense Ratio Evaluation: Evaluate expense ratios (direct vs regular plans) and their long-term impact on net returns for different types of investors. 3. Fund Manager Analysis: Assess the track record and investment philosophy of the fund manager. Determine consistency in management and its impact on performance. 4. Category Comparison: Compare funds within categories (e.g., equity, debt, hybrid) using quantitative metrics such as: Risk-adjusted returns Sharpe ratio Alpha generation Drawdowns and volatility 5. Alpha Generation Identification: Identify funds that consistently generate alpha (outperform the benchmark) and assess the strategies that lead to such performance. 6. Fund House Stability: Evaluate the fund house's financial stability, reputation, and investor service quality. Analyze AUM growth and scalability of the fund house to ensure long-term reliability. 7. Tax Efficiency & Dividend Distribution Policy: Evaluate the tax efficiency of each fund considering capital gains tax, dividend distribution, and holding period taxation. Provide insights into how these factors impact long-term returns for Indian investors. 8. Goal-Based Fund Recommendations: Provide goal-based fund recommendations (e.g., retirement, education, wealth creation) with tailored suggestions based on: Risk tolerance Investment horizon Tax considerations Key Areas of Focus for Indian Mutual Fund Analysis: Performance Consistency Across Market Cycles: Assess how well the fund performs in different market environments (bullish, bearish, sideways). Expense Ratio Optimization (Direct vs Regular Plans): Evaluate the trade-off between cost efficiency and accessibility, recommending the most suitable fund plans for different investor types. Fund Manager Tenure & Investment Philosophy: Assess the impact of a fund manager's tenure and their investment philosophy on the fund's consistency and long-term performance. AUM Growth & Scalability: Determine how AUM growth impacts a fund's ability to scale and maintain performance. Large AUM may affect liquidity and flexibility, but also signal trust. Category Benchmarking & Peer Comparison: Compare funds against category benchmarks (e.g., Nifty 50 for equity, Crisil for debt) and identify top performers within their category. Tax Efficiency & Dividend Policies: Evaluate tax efficiency considering capital gains, dividends, and fund turnover. Provide strategies to minimize tax liabilities over the investment horizon. Goal-Based Recommendations: Provide tailored investment solutions based on individual investor goals, such as: Retirement planning Wealth creation Education funding Short-term goals Recommendations for Indian Investors: 1. Equity Funds (Growth-Oriented): Focus on funds with strong long-term performance, consistently high alpha, and low expense ratios. These funds are suitable for growth-focused investors seeking capital appreciation. 2. Debt Funds (Risk-Averse): For investors with a low risk tolerance, recommend low-volatility funds with stable returns and a track record of consistency. Ensure tax-efficient funds for better after-tax returns. 3. Hybrid Funds (Balanced Approach): Combine equity and debt for a diversified approach. These funds are suitable for investors seeking a balance between risk and reward, particularly those with a medium-term horizon. 4. Tax Efficiency: Recommend funds that are tax-efficient, such as those with lower turnover and capital gains distributions. Focus on LTCG tax advantages for long-term investors. 5. Goal-Based Recommendations: For retirement planning, suggest equity funds for long-term growth. For short-term goals, recommend debt funds or hybrid funds based on the investor's risk appetite. Provide specific recommendations with rationale for Indian investors. Make use of the following advanced portfolio techniques where applicable: 1. Modern Portfolio Theory (MPT) – Efficient Frontier 2. Risk Parity Allocation 3. Black-Litterman Model 4. Monte Carlo Simulation """ class AISwarmService: """Service for creating AI swarms for mutual fund analysis""" def __init__(self): self.api_key = settings.SWARMS_API_KEY self.base_url = settings.SWARMS_BASE_URL self.headers = { "x-api-key": self.api_key, "Content-Type": "application/json" } def create_mutual_fund_swarm(self, portfolio_data: Dict[str, Any], client_profile: Dict[str, Any], goals_data: Dict[str, Any]) -> AIAnalysisResponse: """Create AI swarm for mutual fund analysis""" swarm_config = { "name": "Mutual Fund Investment Analysis Swarm", "description": "AI swarm for Indian mutual fund investment analysis and recommendations", "agents": [ { "agent_name": "Fund Selection Specialist", "system_prompt": FUND_SELECTION_PROMPT, "model_name": "gpt-4o", "role": "worker", "max_loops": 1, "max_tokens": 4096, "temperature": 0.3, }, { "agent_name": "Goal Planning Specialist", "system_prompt": GOAL_PLANNING_PROMPT, "model_name": "gpt-4o", "role": "worker", "max_loops": 1, "max_tokens": 4096, "temperature": 0.3, }, { "agent_name": "Risk Assessment Specialist", "system_prompt": RISK_ASSESSMENT_PROMPT, "model_name": "gpt-4o", "role": "worker", "max_loops": 1, "max_tokens": 4096, "temperature": 0.3, }, { "agent_name": "Fund Allocation Specialist", "system_prompt": FUND_ALLOCATION_PROMPT, "model_name": "gpt-4o", "role": "worker", "max_loops": 1, "max_tokens": 4096, "temperature": 0.3, } ], "max_loops": 2, "swarm_type": "ConcurrentWorkflow", "task": f""" Analyze the mutual fund investment requirements: Client Profile: {client_profile} Current Portfolio: {portfolio_data} Investment Goals: {goals_data} Provide comprehensive recommendations for: 1. Fund selection and optimization 2. Goal-based SIP planning 3. Risk assessment and mitigation 4. Tax-efficient strategies 5. Implementation roadmap """ } try: if self.api_key: response = requests.post( f"{self.base_url}/v1/swarm/completions", headers=self.headers, json=swarm_config, timeout=120 ) if response.status_code == 200: result = response.json() # Parse the output to extract agent responses output_agents = [] if "output" in result and isinstance(result["output"], list): for agent_output in result["output"]: if isinstance(agent_output, dict): output_agents.append(AISwarmAgent( agent_name=agent_output.get("agent_name", ""), content=agent_output.get("content", "") )) return AIAnalysisResponse( success=True, output=output_agents ) else: return AIAnalysisResponse( success=False, error=f"API request failed with status code {response.status_code}" ) else: return AIAnalysisResponse( success=False, error="Swarms API key not configured" ) except Exception as e: return AIAnalysisResponse( success=False, error=f"Swarm analysis failed: {str(e)}" ) def get_enhanced_analysis(self, request: AIAnalysisRequest) -> AIAnalysisResponse: """Get enhanced AI analysis with additional context""" # Prepare comprehensive data for AI analysis client_profile = request.client_profile portfolio_data = { 'holdings': request.portfolio_data.get('holdings', []), 'categories': request.portfolio_data.get('categories', []), 'total_value': request.portfolio_data.get('total_value', 0), 'total_invested': request.portfolio_data.get('total_invested', 0), 'total_gains': request.portfolio_data.get('total_gains', 0), 'category_allocation': request.portfolio_data.get('category_allocation', {}) } goals_data = { 'goals': request.goals_data.get('goals', []), 'goal_details': request.goals_data.get('goal_details', []), 'total_required_sip': request.goals_data.get('total_required_sip', 0), 'timeline_range': request.goals_data.get('timeline_range', ""), 'priority_goals': request.goals_data.get('priority_goals', []) } # Enhanced context analysis_context = { 'market_conditions': request.market_conditions.value, 'investment_horizon': request.investment_horizon.value, 'analysis_focus': [focus.value for focus in request.analysis_focus], 'current_date': str(pd.Timestamp.now()) } # Run AI analysis return self.create_mutual_fund_swarm( {**portfolio_data, **analysis_context}, client_profile, goals_data )