from swarms import Agent, MixtureOfAgents
import os
# Configure your LLM
api_key = os.getenv("OPENAI_API_KEY")
# Define specialized financial analyst agents
fundamental_analyst = Agent(
agent_name="Fundamental-Analyst",
system_prompt="""
You are a fundamental analysis expert.
Your role is to:
- Analyze financial statements (P&L, balance sheet, cash flow)
- Calculate key financial ratios (P/E, ROE, debt-to-equity, etc.)
- Assess company financial health and profitability
- Evaluate management quality and corporate governance
- Determine intrinsic value using DCF and comparable analysis
Provide thorough fundamental analysis with specific metrics.
""",
model_name="gpt-4o",
max_loops=1,
dynamic_temperature_enabled=True,
)
technical_analyst = Agent(
agent_name="Technical-Analyst",
system_prompt="""
You are a technical analysis specialist.
Your role is to:
- Analyze price trends, support/resistance levels
- Identify chart patterns and technical indicators
- Assess momentum using RSI, MACD, moving averages
- Evaluate volume patterns and market sentiment
- Provide entry/exit points based on technical signals
Focus on price action and market dynamics.
""",
model_name="gpt-4o",
max_loops=1,
dynamic_temperature_enabled=True,
)
risk_analyst = Agent(
agent_name="Risk-Analyst",
system_prompt="""
You are a risk management expert.
Your role is to:
- Assess market risk, credit risk, and operational risk
- Calculate Value at Risk (VaR) and stress test scenarios
- Analyze volatility and beta
- Evaluate concentration risk and correlations
- Recommend risk mitigation strategies
Identify and quantify all material risks.
""",
model_name="gpt-4o",
max_loops=1,
dynamic_temperature_enabled=True,
)
macro_analyst = Agent(
agent_name="Macro-Analyst",
system_prompt="""
You are a macroeconomic analysis expert.
Your role is to:
- Analyze economic indicators (GDP, inflation, employment)
- Assess monetary and fiscal policy impacts
- Evaluate sector and industry trends
- Identify macroeconomic risks and opportunities
- Provide economic context for investment decisions
Connect macro trends to investment implications.
""",
model_name="gpt-4o",
max_loops=1,
dynamic_temperature_enabled=True,
)
quant_analyst = Agent(
agent_name="Quantitative-Analyst",
system_prompt="""
You are a quantitative analyst specializing in statistical models.
Your role is to:
- Build statistical and mathematical models
- Perform regression analysis and factor modeling
- Calculate Sharpe ratio, alpha, and other performance metrics
- Analyze historical patterns and correlations
- Backtest investment strategies
Provide data-driven quantitative insights.
""",
model_name="gpt-4o",
max_loops=1,
dynamic_temperature_enabled=True,
)
sentiment_analyst = Agent(
agent_name="Sentiment-Analyst",
system_prompt="""
You are a market sentiment and behavioral finance expert.
Your role is to:
- Analyze news sentiment and social media trends
- Assess investor sentiment and positioning
- Identify behavioral biases in market pricing
- Monitor insider trading and institutional flows
- Evaluate market psychology and crowd behavior
Gauge market sentiment and contrarian opportunities.
""",
model_name="gpt-4o",
max_loops=1,
dynamic_temperature_enabled=True,
)
aggregator_agent = Agent(
agent_name="Chief-Investment-Officer",
system_prompt="""
You are the Chief Investment Officer who synthesizes all analyst inputs.
Your role is to:
- Integrate insights from all analytical perspectives
- Identify consensus views and disagreements
- Weigh different analytical approaches appropriately
- Assess confidence level based on analyst agreement
- Provide clear investment recommendations with rationale
- Assign conviction levels (High/Medium/Low)
Make final investment decisions based on collective intelligence.
""",
model_name="gpt-4o",
max_loops=1,
dynamic_temperature_enabled=True,
)
# Create the Mixture of Agents financial analysis system
financial_analysis_system = MixtureOfAgents(
name="Financial-Analysis-System",
agents=[
fundamental_analyst,
technical_analyst,
risk_analyst,
macro_analyst,
quant_analyst,
sentiment_analyst,
],
aggregator_agent=aggregator_agent,
aggregator_system_prompt="""
Synthesize all analyst perspectives into a comprehensive investment recommendation.
Structure your output as:
1. Executive Summary
2. Analyst Consensus & Disagreements
3. Investment Thesis
4. Risk Assessment
5. Recommendation (Buy/Hold/Sell with conviction level)
6. Price Targets and Timeline
7. Key Risks and Mitigants
""",
layers=2, # Two rounds of analysis for deeper insights
)
# Execute financial analysis
if __name__ == "__main__":
analysis_request = """
Provide comprehensive investment analysis for:
Company: Tesla Inc. (TSLA)
Analysis scope:
- Current valuation and financial health
- Technical price trends and momentum
- Risk factors (market, business, regulatory)
- Macroeconomic tailwinds/headwinds for EV sector
- Quantitative performance metrics vs peers
- Market sentiment and investor positioning
Context:
- Investment horizon: 12-18 months
- Portfolio context: Growth-oriented equity portfolio
- Risk tolerance: Moderate-aggressive
Provide actionable buy/hold/sell recommendation with price targets.
"""
# Run the financial analysis
print("Running multi-agent financial analysis...")
investment_report = financial_analysis_system.run(analysis_request)
# Save the investment report
with open("tesla_investment_analysis.md", "w") as f:
f.write(investment_report)
print("Investment analysis complete! Report saved to tesla_investment_analysis.md")