lucifer7210 commited on
Commit
b560b13
·
verified ·
1 Parent(s): 38ea272

Update app/services/ai_swarm.py

Browse files
Files changed (1) hide show
  1. app/services/ai_swarm.py +357 -337
app/services/ai_swarm.py CHANGED
@@ -1,338 +1,358 @@
1
- import requests
2
- import json
3
- from typing import Dict, Any, List
4
- from app.config import settings
5
- from app.models.ai_models import AIAnalysisRequest, AIAnalysisResponse, AISwarmAgent
6
- import pandas as pd
7
-
8
- # Popular mutual fund categories with scheme codes
9
- POPULAR_FUNDS = {
10
- 'Large Cap Equity': {
11
- 'HDFC Top 100 Fund': '120503',
12
- 'ICICI Pru Bluechip Fund': '120505',
13
- 'SBI Bluechip Fund': '125497',
14
- 'Axis Bluechip Fund': '120503',
15
- 'Kotak Bluechip Fund': '118989'
16
- },
17
- 'Mid Cap Equity': {
18
- 'HDFC Mid-Cap Opportunities Fund': '118551',
19
- 'ICICI Pru Mid Cap Fund': '120544',
20
- 'Kotak Emerging Equity Fund': '118999',
21
- 'SBI Magnum Mid Cap Fund': '100281',
22
- 'DSP Mid Cap Fund': '112618'
23
- },
24
- 'Small Cap Equity': {
25
- 'SBI Small Cap Fund': '122639',
26
- 'DSP Small Cap Fund': '112618',
27
- 'HDFC Small Cap Fund': '118551',
28
- 'Axis Small Cap Fund': '125487',
29
- 'Kotak Small Cap Fund': '119028'
30
- },
31
- 'ELSS (Tax Saving)': {
32
- 'Axis Long Term Equity Fund': '125494',
33
- 'HDFC Tax Saver': '100277',
34
- 'SBI Tax Saver': '125497',
35
- 'ICICI Pru ELSS Tax Saver': '120503',
36
- 'Kotak Tax Saver': '118989'
37
- },
38
- 'Debt Funds': {
39
- 'HDFC Corporate Bond Fund': '101762',
40
- 'ICICI Pru Corporate Bond Fund': '120503',
41
- 'SBI Corporate Bond Fund': '125497',
42
- 'Kotak Corporate Bond Fund': '118989',
43
- 'Axis Corporate Debt Fund': '125494'
44
- },
45
- 'Hybrid Funds': {
46
- 'HDFC Hybrid Equity Fund': '118551',
47
- 'ICICI Pru Balanced Advantage Fund': '120505',
48
- 'SBI Equity Hybrid Fund': '125497',
49
- 'Kotak Equity Hybrid Fund': '118999',
50
- 'Axis Hybrid Fund': '125494'
51
- }
52
- }
53
-
54
- # AI Agent Prompts for Mutual Funds
55
- FUND_SELECTION_PROMPT = """
56
- You are an expert Indian mutual fund selection specialist with deep knowledge of fund analysis,
57
- performance evaluation, and fund house comparisons for Indian mutual fund markets.
58
- Your responsibilities:
59
- 1. Analyze fund performance across different time periods (1Y, 3Y, 5Y)
60
- 2. Evaluate expense ratios and their impact on long-term returns
61
- 3. Assess fund manager track record and consistency
62
- 4. Compare funds within categories using quantitative metrics
63
- 5. Identify funds with consistent alpha generation
64
- 6. Evaluate fund house stability and investor service quality
65
- Focus areas for Indian mutual fund analysis:
66
- - Performance consistency across market cycles
67
- - Expense ratio optimization (direct vs regular plans)
68
- - Fund manager tenure and investment philosophy
69
- - AUM growth and scalability
70
- - Category benchmarking and peer comparison
71
- - Tax efficiency and dividend distribution policy
72
- - Goal-based fund recommendations
73
- Provide specific recommendations with rationale for Indian investors.
74
- """
75
-
76
- GOAL_PLANNING_PROMPT = """
77
- You are an expert in goal-based financial planning specialized in mapping investment
78
- goals to appropriate mutual fund strategies for Indian investors.
79
- Your responsibilities:
80
- 1. Analyze client goals for timeline, amount, and priority
81
- 2. Map goals to appropriate fund categories and asset allocation
82
- 3. Design SIP strategies aligned with goal timelines
83
- 4. Recommend optimal fund combinations for multiple goals
84
- 5. Plan step-up SIP strategies for inflation adjustment
85
- 6. Create tax-efficient investment strategies including ELSS
86
- Goal-based fund mapping expertise:
87
- - Short-term goals (1-3 years): Debt funds, liquid funds
88
- - Medium-term goals (3-7 years): Hybrid funds, large cap equity
89
- - Long-term goals (7+ years): Mid cap, small cap equity
90
- - Tax-saving goals: ELSS funds with 3-year lock-in
91
- - Retirement planning: Systematic equity exposure with debt balancing
92
- - Emergency funds: Liquid funds with instant redemption capability
93
- Provide actionable SIP recommendations with specific amounts and fund selections.
94
- """
95
-
96
- RISK_ASSESSMENT_PROMPT = """
97
- You are an expert in mutual fund risk analysis with extensive knowledge of
98
- fund-specific risks, category risks, and portfolio risk management for Indian mutual fund investments.
99
- Your responsibilities:
100
- 1. Assess fund-specific risks including manager risk, style drift
101
- 2. Analyze category concentration and diversification needs
102
- 3. Evaluate expense ratio impact on long-term wealth creation
103
- 4. Assess liquidity risks across different fund categories
104
- 5. Identify regulatory and tax-related risks
105
- 6. Recommend risk mitigation strategies
106
- Focus on Indian mutual fund risk factors:
107
- - Fund manager tenure and philosophy changes
108
- - Category concentration and overlap analysis
109
- - Expense ratio drag on returns over long periods
110
- - Exit load structures and liquidity constraints
111
- - Tax implications of different fund types
112
- - Market timing risks in equity fund investments
113
- - Credit risks in debt fund categories
114
- Provide practical risk management recommendations for Indian mutual fund investors.
115
- """
116
-
117
- FUND_ALLOCATION_PROMPT = """
118
- 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.
119
- Your Responsibilities:
120
- 1. Fund Performance Analysis:
121
- Analyze fund performance over different time periods (1Y, 3Y, 5Y) to assess consistency and growth potential.
122
- 2. Expense Ratio Evaluation:
123
- Evaluate expense ratios (direct vs regular plans) and their long-term impact on net returns for different types of investors.
124
- 3. Fund Manager Analysis:
125
- Assess the track record and investment philosophy of the fund manager. Determine consistency in management and its impact on performance.
126
- 4. Category Comparison:
127
- Compare funds within categories (e.g., equity, debt, hybrid) using quantitative metrics such as:
128
- Risk-adjusted returns
129
- Sharpe ratio
130
- Alpha generation
131
- Drawdowns and volatility
132
- 5. Alpha Generation Identification:
133
- Identify funds that consistently generate alpha (outperform the benchmark) and assess the strategies that lead to such performance.
134
- 6. Fund House Stability:
135
- Evaluate the fund house's financial stability, reputation, and investor service quality.
136
- Analyze AUM growth and scalability of the fund house to ensure long-term reliability.
137
- 7. Tax Efficiency & Dividend Distribution Policy:
138
- Evaluate the tax efficiency of each fund considering capital gains tax, dividend distribution, and holding period taxation.
139
- Provide insights into how these factors impact long-term returns for Indian investors.
140
- 8. Goal-Based Fund Recommendations:
141
- Provide goal-based fund recommendations (e.g., retirement, education, wealth creation) with tailored suggestions based on:
142
- Risk tolerance
143
- Investment horizon
144
- Tax considerations
145
-
146
- Key Areas of Focus for Indian Mutual Fund Analysis:
147
- Performance Consistency Across Market Cycles:
148
- Assess how well the fund performs in different market environments (bullish, bearish, sideways).
149
- Expense Ratio Optimization (Direct vs Regular Plans):
150
- Evaluate the trade-off between cost efficiency and accessibility, recommending the most suitable fund plans for different investor types.
151
- Fund Manager Tenure & Investment Philosophy:
152
- Assess the impact of a fund manager's tenure and their investment philosophy on the fund's consistency and long-term performance.
153
- AUM Growth & Scalability:
154
- 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.
155
- Category Benchmarking & Peer Comparison:
156
- Compare funds against category benchmarks (e.g., Nifty 50 for equity, Crisil for debt) and identify top performers within their category.
157
- Tax Efficiency & Dividend Policies:
158
- Evaluate tax efficiency considering capital gains, dividends, and fund turnover. Provide strategies to minimize tax liabilities over the investment horizon.
159
- Goal-Based Recommendations:
160
- Provide tailored investment solutions based on individual investor goals, such as:
161
- Retirement planning
162
- Wealth creation
163
- Education funding
164
- Short-term goals
165
-
166
- Recommendations for Indian Investors:
167
- 1. Equity Funds (Growth-Oriented):
168
- 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.
169
- 2. Debt Funds (Risk-Averse):
170
- 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.
171
- 3. Hybrid Funds (Balanced Approach):
172
- 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.
173
- 4. Tax Efficiency:
174
- 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.
175
- 5. Goal-Based Recommendations:
176
- 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.
177
- Provide specific recommendations with rationale for Indian investors.
178
- Make use of the following advanced portfolio techniques where applicable:
179
- 1. Modern Portfolio Theory (MPT) – Efficient Frontier
180
- 2. Risk Parity Allocation
181
- 3. Black-Litterman Model
182
- 4. Monte Carlo Simulation
183
- """
184
-
185
- class AISwarmService:
186
- """Service for creating AI swarms for mutual fund analysis"""
187
-
188
- def __init__(self):
189
- self.api_key = settings.SWARMS_API_KEY
190
- self.base_url = settings.SWARMS_BASE_URL
191
- self.headers = {
192
- "x-api-key": self.api_key,
193
- "Content-Type": "application/json"
194
- }
195
-
196
- def create_mutual_fund_swarm(self, portfolio_data: Dict[str, Any],
197
- client_profile: Dict[str, Any],
198
- goals_data: Dict[str, Any]) -> AIAnalysisResponse:
199
- """Create AI swarm for mutual fund analysis"""
200
-
201
- swarm_config = {
202
- "name": "Mutual Fund Investment Analysis Swarm",
203
- "description": "AI swarm for Indian mutual fund investment analysis and recommendations",
204
- "agents": [
205
- {
206
- "agent_name": "Fund Selection Specialist",
207
- "system_prompt": FUND_SELECTION_PROMPT,
208
- "model_name": "gpt-4o",
209
- "role": "worker",
210
- "max_loops": 1,
211
- "max_tokens": 4096,
212
- "temperature": 0.3,
213
- },
214
- {
215
- "agent_name": "Goal Planning Specialist",
216
- "system_prompt": GOAL_PLANNING_PROMPT,
217
- "model_name": "gpt-4o",
218
- "role": "worker",
219
- "max_loops": 1,
220
- "max_tokens": 4096,
221
- "temperature": 0.3,
222
- },
223
- {
224
- "agent_name": "Risk Assessment Specialist",
225
- "system_prompt": RISK_ASSESSMENT_PROMPT,
226
- "model_name": "gpt-4o",
227
- "role": "worker",
228
- "max_loops": 1,
229
- "max_tokens": 4096,
230
- "temperature": 0.3,
231
- },
232
- {
233
- "agent_name": "Fund Allocation Specialist",
234
- "system_prompt": FUND_ALLOCATION_PROMPT,
235
- "model_name": "gpt-4o",
236
- "role": "worker",
237
- "max_loops": 1,
238
- "max_tokens": 4096,
239
- "temperature": 0.3,
240
- }
241
- ],
242
- "max_loops": 2,
243
- "swarm_type": "ConcurrentWorkflow",
244
- "task": f"""
245
- Analyze the mutual fund investment requirements:
246
-
247
- Client Profile: {client_profile}
248
- Current Portfolio: {portfolio_data}
249
- Investment Goals: {goals_data}
250
-
251
- Provide comprehensive recommendations for:
252
- 1. Fund selection and optimization
253
- 2. Goal-based SIP planning
254
- 3. Risk assessment and mitigation
255
- 4. Tax-efficient strategies
256
- 5. Implementation roadmap
257
- """
258
- }
259
-
260
- try:
261
- if self.api_key:
262
- response = requests.post(
263
- f"{self.base_url}/v1/swarm/completions",
264
- headers=self.headers,
265
- json=swarm_config,
266
- timeout=120
267
- )
268
-
269
- if response.status_code == 200:
270
- result = response.json()
271
-
272
- # Parse the output to extract agent responses
273
- output_agents = []
274
- if "output" in result and isinstance(result["output"], list):
275
- for agent_output in result["output"]:
276
- if isinstance(agent_output, dict):
277
- output_agents.append(AISwarmAgent(
278
- agent_name=agent_output.get("agent_name", ""),
279
- content=agent_output.get("content", "")
280
- ))
281
-
282
- return AIAnalysisResponse(
283
- success=True,
284
- output=output_agents
285
- )
286
- else:
287
- return AIAnalysisResponse(
288
- success=False,
289
- error=f"API request failed with status code {response.status_code}"
290
- )
291
- else:
292
- return AIAnalysisResponse(
293
- success=False,
294
- error="Swarms API key not configured"
295
- )
296
- except Exception as e:
297
- return AIAnalysisResponse(
298
- success=False,
299
- error=f"Swarm analysis failed: {str(e)}"
300
- )
301
-
302
- def get_enhanced_analysis(self, request: AIAnalysisRequest) -> AIAnalysisResponse:
303
- """Get enhanced AI analysis with additional context"""
304
-
305
- # Prepare comprehensive data for AI analysis
306
- client_profile = request.client_profile
307
-
308
- portfolio_data = {
309
- 'holdings': request.portfolio_data.get('holdings', []),
310
- 'categories': request.portfolio_data.get('categories', []),
311
- 'total_value': request.portfolio_data.get('total_value', 0),
312
- 'total_invested': request.portfolio_data.get('total_invested', 0),
313
- 'total_gains': request.portfolio_data.get('total_gains', 0),
314
- 'category_allocation': request.portfolio_data.get('category_allocation', {})
315
- }
316
-
317
- goals_data = {
318
- 'goals': request.goals_data.get('goals', []),
319
- 'goal_details': request.goals_data.get('goal_details', []),
320
- 'total_required_sip': request.goals_data.get('total_required_sip', 0),
321
- 'timeline_range': request.goals_data.get('timeline_range', ""),
322
- 'priority_goals': request.goals_data.get('priority_goals', [])
323
- }
324
-
325
- # Enhanced context
326
- analysis_context = {
327
- 'market_conditions': request.market_conditions.value,
328
- 'investment_horizon': request.investment_horizon.value,
329
- 'analysis_focus': [focus.value for focus in request.analysis_focus],
330
- 'current_date': str(pd.Timestamp.now())
331
- }
332
-
333
- # Run AI analysis
334
- return self.create_mutual_fund_swarm(
335
- {**portfolio_data, **analysis_context},
336
- client_profile,
337
- goals_data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
338
  )
 
1
+ import requests
2
+ import json
3
+ from typing import Dict, Any, List
4
+ from app.config import settings
5
+ from app.models.ai_models import AIAnalysisRequest, AIAnalysisResponse, AISwarmAgent
6
+ import pandas as pd
7
+
8
+ # Popular mutual fund categories with scheme codes
9
+ POPULAR_FUNDS = {
10
+ 'Large Cap Equity': {
11
+ 'HDFC Top 100 Fund': '120503',
12
+ 'ICICI Pru Bluechip Fund': '120505',
13
+ 'SBI Bluechip Fund': '125497',
14
+ 'Axis Bluechip Fund': '120503',
15
+ 'Kotak Bluechip Fund': '118989'
16
+ },
17
+ 'Mid Cap Equity': {
18
+ 'HDFC Mid-Cap Opportunities Fund': '118551',
19
+ 'ICICI Pru Mid Cap Fund': '120544',
20
+ 'Kotak Emerging Equity Fund': '118999',
21
+ 'SBI Magnum Mid Cap Fund': '100281',
22
+ 'DSP Mid Cap Fund': '112618'
23
+ },
24
+ 'Small Cap Equity': {
25
+ 'SBI Small Cap Fund': '122639',
26
+ 'DSP Small Cap Fund': '112618',
27
+ 'HDFC Small Cap Fund': '118551',
28
+ 'Axis Small Cap Fund': '125487',
29
+ 'Kotak Small Cap Fund': '119028'
30
+ },
31
+ 'ELSS (Tax Saving)': {
32
+ 'Axis Long Term Equity Fund': '125494',
33
+ 'HDFC Tax Saver': '100277',
34
+ 'SBI Tax Saver': '125497',
35
+ 'ICICI Pru ELSS Tax Saver': '120503',
36
+ 'Kotak Tax Saver': '118989'
37
+ },
38
+ 'Debt Funds': {
39
+ 'HDFC Corporate Bond Fund': '101762',
40
+ 'ICICI Pru Corporate Bond Fund': '120503',
41
+ 'SBI Corporate Bond Fund': '125497',
42
+ 'Kotak Corporate Bond Fund': '118989',
43
+ 'Axis Corporate Debt Fund': '125494'
44
+ },
45
+ 'Hybrid Funds': {
46
+ 'HDFC Hybrid Equity Fund': '118551',
47
+ 'ICICI Pru Balanced Advantage Fund': '120505',
48
+ 'SBI Equity Hybrid Fund': '125497',
49
+ 'Kotak Equity Hybrid Fund': '118999',
50
+ 'Axis Hybrid Fund': '125494'
51
+ }
52
+ }
53
+
54
+ # AI Agent Prompts for Mutual Funds
55
+ FUND_SELECTION_PROMPT = """
56
+ You are an expert Indian mutual fund selection specialist with deep knowledge of fund analysis,
57
+ performance evaluation, and fund house comparisons for Indian mutual fund markets.
58
+ Your responsibilities:
59
+ 1. Analyze fund performance across different time periods (1Y, 3Y, 5Y)
60
+ 2. Evaluate expense ratios and their impact on long-term returns
61
+ 3. Assess fund manager track record and consistency
62
+ 4. Compare funds within categories using quantitative metrics
63
+ 5. Identify funds with consistent alpha generation
64
+ 6. Evaluate fund house stability and investor service quality
65
+ Focus areas for Indian mutual fund analysis:
66
+ - Performance consistency across market cycles
67
+ - Expense ratio optimization (direct vs regular plans)
68
+ - Fund manager tenure and investment philosophy
69
+ - AUM growth and scalability
70
+ - Category benchmarking and peer comparison
71
+ - Tax efficiency and dividend distribution policy
72
+ - Goal-based fund recommendations
73
+ Provide specific recommendations with rationale for Indian investors.
74
+ """
75
+
76
+ GOAL_PLANNING_PROMPT = """
77
+ You are an expert in goal-based financial planning specialized in mapping investment
78
+ goals to appropriate mutual fund strategies for Indian investors.
79
+ Your responsibilities:
80
+ 1. Analyze client goals for timeline, amount, and priority
81
+ 2. Map goals to appropriate fund categories and asset allocation
82
+ 3. Design SIP strategies aligned with goal timelines
83
+ 4. Recommend optimal fund combinations for multiple goals
84
+ 5. Plan step-up SIP strategies for inflation adjustment
85
+ 6. Create tax-efficient investment strategies including ELSS
86
+ Goal-based fund mapping expertise:
87
+ - Short-term goals (1-3 years): Debt funds, liquid funds
88
+ - Medium-term goals (3-7 years): Hybrid funds, large cap equity
89
+ - Long-term goals (7+ years): Mid cap, small cap equity
90
+ - Tax-saving goals: ELSS funds with 3-year lock-in
91
+ - Retirement planning: Systematic equity exposure with debt balancing
92
+ - Emergency funds: Liquid funds with instant redemption capability
93
+ Provide actionable SIP recommendations with specific amounts and fund selections.
94
+ """
95
+
96
+ RISK_ASSESSMENT_PROMPT = """
97
+ You are an expert in mutual fund risk analysis with extensive knowledge of
98
+ fund-specific risks, category risks, and portfolio risk management for Indian mutual fund investments.
99
+ Your responsibilities:
100
+ 1. Assess fund-specific risks including manager risk, style drift
101
+ 2. Analyze category concentration and diversification needs
102
+ 3. Evaluate expense ratio impact on long-term wealth creation
103
+ 4. Assess liquidity risks across different fund categories
104
+ 5. Identify regulatory and tax-related risks
105
+ 6. Recommend risk mitigation strategies
106
+ Focus on Indian mutual fund risk factors:
107
+ - Fund manager tenure and philosophy changes
108
+ - Category concentration and overlap analysis
109
+ - Expense ratio drag on returns over long periods
110
+ - Exit load structures and liquidity constraints
111
+ - Tax implications of different fund types
112
+ - Market timing risks in equity fund investments
113
+ - Credit risks in debt fund categories
114
+ Provide practical risk management recommendations for Indian mutual fund investors.
115
+ """
116
+
117
+ FUND_ALLOCATION_PROMPT = """
118
+ 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.
119
+ Your Responsibilities:
120
+ 1. Fund Performance Analysis:
121
+ Analyze fund performance over different time periods (1Y, 3Y, 5Y) to assess consistency and growth potential.
122
+ 2. Expense Ratio Evaluation:
123
+ Evaluate expense ratios (direct vs regular plans) and their long-term impact on net returns for different types of investors.
124
+ 3. Fund Manager Analysis:
125
+ Assess the track record and investment philosophy of the fund manager. Determine consistency in management and its impact on performance.
126
+ 4. Category Comparison:
127
+ Compare funds within categories (e.g., equity, debt, hybrid) using quantitative metrics such as:
128
+ Risk-adjusted returns
129
+ Sharpe ratio
130
+ Alpha generation
131
+ Drawdowns and volatility
132
+ 5. Alpha Generation Identification:
133
+ Identify funds that consistently generate alpha (outperform the benchmark) and assess the strategies that lead to such performance.
134
+ 6. Fund House Stability:
135
+ Evaluate the fund house's financial stability, reputation, and investor service quality.
136
+ Analyze AUM growth and scalability of the fund house to ensure long-term reliability.
137
+ 7. Tax Efficiency & Dividend Distribution Policy:
138
+ Evaluate the tax efficiency of each fund considering capital gains tax, dividend distribution, and holding period taxation.
139
+ Provide insights into how these factors impact long-term returns for Indian investors.
140
+ 8. Goal-Based Fund Recommendations:
141
+ Provide goal-based fund recommendations (e.g., retirement, education, wealth creation) with tailored suggestions based on:
142
+ Risk tolerance
143
+ Investment horizon
144
+ Tax considerations
145
+
146
+ Key Areas of Focus for Indian Mutual Fund Analysis:
147
+ Performance Consistency Across Market Cycles:
148
+ Assess how well the fund performs in different market environments (bullish, bearish, sideways).
149
+ Expense Ratio Optimization (Direct vs Regular Plans):
150
+ Evaluate the trade-off between cost efficiency and accessibility, recommending the most suitable fund plans for different investor types.
151
+ Fund Manager Tenure & Investment Philosophy:
152
+ Assess the impact of a fund manager's tenure and their investment philosophy on the fund's consistency and long-term performance.
153
+ AUM Growth & Scalability:
154
+ 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.
155
+ Category Benchmarking & Peer Comparison:
156
+ Compare funds against category benchmarks (e.g., Nifty 50 for equity, Crisil for debt) and identify top performers within their category.
157
+ Tax Efficiency & Dividend Policies:
158
+ Evaluate tax efficiency considering capital gains, dividends, and fund turnover. Provide strategies to minimize tax liabilities over the investment horizon.
159
+ Goal-Based Recommendations:
160
+ Provide tailored investment solutions based on individual investor goals, such as:
161
+ Retirement planning
162
+ Wealth creation
163
+ Education funding
164
+ Short-term goals
165
+
166
+ Recommendations for Indian Investors:
167
+ 1. Equity Funds (Growth-Oriented):
168
+ 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.
169
+ 2. Debt Funds (Risk-Averse):
170
+ 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.
171
+ 3. Hybrid Funds (Balanced Approach):
172
+ 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.
173
+ 4. Tax Efficiency:
174
+ 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.
175
+ 5. Goal-Based Recommendations:
176
+ 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.
177
+ Provide specific recommendations with rationale for Indian investors.
178
+ Make use of the following advanced portfolio techniques where applicable:
179
+ 1. Modern Portfolio Theory (MPT) – Efficient Frontier
180
+ 2. Risk Parity Allocation
181
+ 3. Black-Litterman Model
182
+ 4. Monte Carlo Simulation
183
+ """
184
+
185
+ class AISwarmService:
186
+ """Service for creating AI swarms for mutual fund analysis"""
187
+
188
+ def __init__(self):
189
+ self.api_key = settings.SWARMS_API_KEY
190
+ self.base_url = settings.SWARMS_BASE_URL
191
+ self.headers = {
192
+ "x-api-key": self.api_key,
193
+ "Content-Type": "application/json"
194
+ }
195
+
196
+ def create_mutual_fund_swarm(self, portfolio_data: Dict[str, Any],
197
+ client_profile: Dict[str, Any],
198
+ goals_data: Dict[str, Any]) -> AIAnalysisResponse:
199
+ """Create AI swarm for mutual fund analysis"""
200
+
201
+ swarm_config = {
202
+ "name": "Mutual Fund Investment Analysis Swarm",
203
+ "description": "AI swarm for Indian mutual fund investment analysis and recommendations",
204
+ "agents": [
205
+ {
206
+ "agent_name": "Fund Selection Specialist",
207
+ "system_prompt": FUND_SELECTION_PROMPT,
208
+ "model_name": "gpt-4o",
209
+ "role": "worker",
210
+ "max_loops": 1,
211
+ "max_tokens": 4096,
212
+ "temperature": 0.3,
213
+ },
214
+ {
215
+ "agent_name": "Goal Planning Specialist",
216
+ "system_prompt": GOAL_PLANNING_PROMPT,
217
+ "model_name": "gpt-4o",
218
+ "role": "worker",
219
+ "max_loops": 1,
220
+ "max_tokens": 4096,
221
+ "temperature": 0.3,
222
+ },
223
+ {
224
+ "agent_name": "Risk Assessment Specialist",
225
+ "system_prompt": RISK_ASSESSMENT_PROMPT,
226
+ "model_name": "gpt-4o",
227
+ "role": "worker",
228
+ "max_loops": 1,
229
+ "max_tokens": 4096,
230
+ "temperature": 0.3,
231
+ },
232
+ {
233
+ "agent_name": "Fund Allocation Specialist",
234
+ "system_prompt": FUND_ALLOCATION_PROMPT,
235
+ "model_name": "gpt-4o",
236
+ "role": "worker",
237
+ "max_loops": 1,
238
+ "max_tokens": 4096,
239
+ "temperature": 0.3,
240
+ }
241
+ ],
242
+ "max_loops": 2,
243
+ "swarm_type": "ConcurrentWorkflow",
244
+ "task": f"""
245
+ Analyze the mutual fund investment requirements:
246
+
247
+ Client Profile: {client_profile}
248
+ Current Portfolio: {portfolio_data}
249
+ Investment Goals: {goals_data}
250
+
251
+ Provide comprehensive recommendations for:
252
+ 1. Fund selection and optimization
253
+ 2. Goal-based SIP planning
254
+ 3. Risk assessment and mitigation
255
+ 4. Tax-efficient strategies
256
+ 5. Implementation roadmap
257
+ """
258
+ }
259
+
260
+ try:
261
+ if self.api_key:
262
+ response = requests.post(
263
+ f"{self.base_url}/v1/swarm/completions",
264
+ headers=self.headers,
265
+ json=swarm_config,
266
+ timeout=120
267
+ )
268
+
269
+ if response.status_code == 200:
270
+ result = response.json()
271
+
272
+ # Parse the output to extract agent responses
273
+ output_agents = []
274
+ if "output" in result and isinstance(result["output"], list):
275
+ # Define the agent names in order
276
+ agent_names = [
277
+ "Fund Selection Specialist",
278
+ "Goal Planning Specialist",
279
+ "Risk Assessment Specialist",
280
+ "Fund Allocation Specialist"
281
+ ]
282
+
283
+ for i, agent_output in enumerate(result["output"]):
284
+ if isinstance(agent_output, dict):
285
+ # Use the predefined agent name based on position
286
+ agent_name = agent_names[i] if i < len(agent_names) else f"Agent {i+1}"
287
+
288
+ # Try to get content from different possible fields
289
+ content = ""
290
+ if "content" in agent_output:
291
+ content = agent_output["content"]
292
+ elif "response" in agent_output:
293
+ content = agent_output["response"]
294
+ elif "output" in agent_output:
295
+ content = agent_output["output"]
296
+
297
+ output_agents.append(AISwarmAgent(
298
+ agent_name=agent_name,
299
+ content=content
300
+ ))
301
+
302
+ return AIAnalysisResponse(
303
+ success=True,
304
+ output=output_agents
305
+ )
306
+ else:
307
+ return AIAnalysisResponse(
308
+ success=False,
309
+ error=f"API request failed with status code {response.status_code}"
310
+ )
311
+ else:
312
+ return AIAnalysisResponse(
313
+ success=False,
314
+ error="Swarms API key not configured"
315
+ )
316
+ except Exception as e:
317
+ return AIAnalysisResponse(
318
+ success=False,
319
+ error=f"Swarm analysis failed: {str(e)}"
320
+ )
321
+
322
+ def get_enhanced_analysis(self, request: AIAnalysisRequest) -> AIAnalysisResponse:
323
+ """Get enhanced AI analysis with additional context"""
324
+
325
+ # Prepare comprehensive data for AI analysis
326
+ client_profile = request.client_profile
327
+
328
+ portfolio_data = {
329
+ 'holdings': request.portfolio_data.get('holdings', []),
330
+ 'categories': request.portfolio_data.get('categories', []),
331
+ 'total_value': request.portfolio_data.get('total_value', 0),
332
+ 'total_invested': request.portfolio_data.get('total_invested', 0),
333
+ 'total_gains': request.portfolio_data.get('total_gains', 0),
334
+ 'category_allocation': request.portfolio_data.get('category_allocation', {})
335
+ }
336
+
337
+ goals_data = {
338
+ 'goals': request.goals_data.get('goals', []),
339
+ 'goal_details': request.goals_data.get('goal_details', []),
340
+ 'total_required_sip': request.goals_data.get('total_required_sip', 0),
341
+ 'timeline_range': request.goals_data.get('timeline_range', ""),
342
+ 'priority_goals': request.goals_data.get('priority_goals', [])
343
+ }
344
+
345
+ # Enhanced context
346
+ analysis_context = {
347
+ 'market_conditions': request.market_conditions.value,
348
+ 'investment_horizon': request.investment_horizon.value,
349
+ 'analysis_focus': [focus.value for focus in request.analysis_focus],
350
+ 'current_date': str(pd.Timestamp.now())
351
+ }
352
+
353
+ # Run AI analysis
354
+ return self.create_mutual_fund_swarm(
355
+ {**portfolio_data, **analysis_context},
356
+ client_profile,
357
+ goals_data
358
  )