The `MajorityVoting` module provides a mechanism for performing majority voting among a group of agents. Majority voting is a decision rule that selects the option which has the majority of votes. This is particularly useful in systems where multiple agents provide responses to a query, and the most common response needs to be identified as the final output.
The `MajorityVoting` module provides a sophisticated multi-loop consensus building system for agents. Unlike simple majority voting, this system enables iterative consensus building where agents can refine their responses across multiple loops, with each subsequent loop considering the previous consensus. This approach leads to more robust and well-reasoned final decisions by leveraging the collective intelligence of multiple specialized agents.
- **Majority Voting**: A method to determine the most common response from a set of answers.
- **Agents**: Entities (e.g., models, algorithms) that provide responses to tasks or queries.
- **Consensus Agent**: An optional agent that analyzes the responses from all agents to determine the final consensus.
- **Conversation History**: A record of all agent interactions and responses during the voting process.
- **Output Types**: Support for different output formats (string, dictionary, list).
- **Multi-Loop Consensus Building**: An iterative process where agents can refine their responses across multiple loops, with each loop building upon the previous consensus.
- **Agents**: Specialized entities (e.g., models, algorithms) that provide expert responses to tasks or queries.
- **Consensus Agent**: An automatically created agent that analyzes and synthesizes responses from all agents to determine the final consensus.
- **Conversation History**: A comprehensive record of all agent interactions, responses, and consensus building across all loops.
- **Output Types**: Support for different output formats (string, dictionary, list) with flexible formatting options.
- **Concurrent Execution**: Agents run simultaneously for improved performance and efficiency.
## Class Definition: `MajorityVoting`
@ -41,13 +48,17 @@ class MajorityVoting:
self,
id: str = swarm_id(),
name: str = "MajorityVoting",
description: str = "A majority voting system for agents",
description: str = "A multi-loop majority voting system for agents",
The MajorityVoting system automatically creates a specialized consensus agent that analyzes and synthesizes responses from all participating agents. This consensus agent uses a sophisticated prompt that:
1. **Comprehensively evaluates** each agent's response across multiple dimensions:
- Accuracy and correctness
- Depth of analysis and insight
- Relevance to the original task
- Clarity, structure, and communication quality
- Unique perspectives or innovative ideas
2. **Performs comparative analysis** by:
- Identifying overlapping themes and points of agreement
- Highlighting divergent viewpoints or conflicting recommendations
- Assessing strengths and weaknesses of each approach
3. **Builds consensus** by:
- Identifying the most effective response(s) with clear justification
- Synthesizing the best elements from multiple responses when appropriate
- Providing ranked recommendations with detailed rationales
4. **Delivers actionable results** that are:
- Fair and balanced
- Evidence-based and rigorous
- Well-supported and clearly communicated
The consensus agent can be customized through the constructor parameters:
- `consensus_agent_prompt`: Custom system prompt for the consensus agent
- `consensus_agent_name`: Name for the consensus agent
- `consensus_agent_description`: Description for the consensus agent
- `consensus_agent_model_name`: Model to use for the consensus agent
tasks = [f"Analyze {sector} sector opportunities" for sector in sectors]
results = swarm.batch_run(tasks)
```
### Concurrent Processing
For maximum performance when processing multiple independent tasks:
```python
# Process multiple research questions concurrently
questions = [
"What are the environmental impacts of AI?",
"How will quantum computing affect cryptography?",
"What are the economic implications of space exploration?"
]
results = swarm.run_concurrently(questions)
```
## Usage Examples
### Example 1: Investment Analysis with Consensus Agent
### Example 1: Quantitative Financial Analysis with Specialized Agents
This example demonstrates using MajorityVoting for comprehensive financial analysis with three specialized quantitative agents, each focusing on different aspects of investment analysis.
```python
from swarms import Agent
from swarms.structs.majority_voting import MajorityVoting
# Technical Analysis Quant Agent System Prompt
TECHNICAL_ANALYSIS_PROMPT = """
You are a Quantitative Technical Analysis Specialist with deep expertise in market chart patterns, technical indicators, and algorithmic trading signals. Your primary focus is on price action, volume analysis, and statistical patterns in financial markets.
6. **Quantitative Methods**: Statistical analysis, backtesting, signal generation, and risk-reward calculations
## Analysis Framework:
- Always provide specific price levels, timeframes, and probability assessments
- Include risk management parameters (stop losses, take profits, position sizing)
- Explain the statistical significance and historical performance of patterns
- Consider multiple timeframes for comprehensive analysis
- Factor in market volatility and current market conditions
## Output Requirements:
- Clear buy/sell/hold recommendations with confidence levels
- Specific entry, stop-loss, and target price levels
- Risk-reward ratios and probability assessments
- Time horizon for the analysis
- Key levels to watch for confirmation or invalidation
Remember: Focus on objective, data-driven analysis based on price action and technical indicators rather than fundamental factors.
"""
# Fundamental Analysis Quant Agent System Prompt
FUNDAMENTAL_ANALYSIS_PROMPT = """
You are a Quantitative Fundamental Analysis Specialist with expertise in financial statement analysis, valuation models, and company performance metrics. Your focus is on intrinsic value, financial health, and long-term investment potential.
## Core Expertise Areas:
1. **Financial Statement Analysis**: Deep dive into income statements, balance sheets, and cash flow statements
2. **Valuation Models**: DCF analysis, P/E ratios, P/B ratios, PEG ratios, EV/EBITDA, and other valuation metrics
3. **Financial Ratios**: Liquidity, profitability, efficiency, leverage, and market ratios
5. **Industry Analysis**: Competitive positioning, market share, industry trends, and comparative analysis
6. **Economic Indicators**: Interest rates, inflation, GDP growth, and their impact on company performance
## Analysis Framework:
- Calculate and interpret key financial ratios and metrics
- Assess company's competitive moat and business model sustainability
- Evaluate management quality and corporate governance
- Consider macroeconomic factors and industry trends
- Provide fair value estimates and margin of safety calculations
## Output Requirements:
- Intrinsic value estimates with confidence intervals
- Key financial metrics and their interpretation
- Strengths, weaknesses, opportunities, and threats (SWOT) analysis
- Investment thesis with supporting evidence
- Risk factors and potential catalysts
- Long-term growth prospects and sustainability
Remember: Focus on quantitative metrics and fundamental factors that drive long-term value creation rather than short-term price movements.
"""
# Risk Management Quant Agent System Prompt
RISK_MANAGEMENT_PROMPT = """
You are a Quantitative Risk Management Specialist with expertise in portfolio optimization, risk metrics, and hedging strategies. Your focus is on risk-adjusted returns, diversification, and capital preservation.
## Core Expertise Areas:
1. **Portfolio Theory**: Modern Portfolio Theory, efficient frontier, and optimal asset allocation
2. **Risk Metrics**: VaR (Value at Risk), CVaR, Sharpe ratio, Sortino ratio, Maximum Drawdown, Beta, and correlation analysis
3. **Diversification**: Asset correlation analysis, sector allocation, geographic diversification, and alternative investments
4. **Hedging Strategies**: Options strategies, futures, swaps, and other derivative instruments
5. **Stress Testing**: Scenario analysis, Monte Carlo simulations, and tail risk assessment
6. **Regulatory Compliance**: Basel III, Solvency II, and other regulatory risk requirements
## Analysis Framework:
- Calculate comprehensive risk metrics and performance ratios
- Assess portfolio concentration and diversification benefits
- Identify potential risk factors and stress scenarios
- Recommend hedging strategies and risk mitigation techniques
- Optimize portfolio allocation for risk-adjusted returns
- Consider liquidity risk, credit risk, and operational risk factors
## Output Requirements:
- Risk-adjusted performance metrics and rankings
- Portfolio optimization recommendations
- Risk factor analysis and stress test results
- Hedging strategy recommendations with cost-benefit analysis
- Diversification analysis and concentration risk assessment
- Capital allocation recommendations based on risk tolerance
Remember: Focus on quantitative risk assessment and portfolio optimization techniques that maximize risk-adjusted returns while maintaining appropriate risk levels.
"""
# Initialize the three specialized quant agents
technical_agent = Agent(
agent_name="Technical-Analysis-Quant",
agent_description="Specialized in technical analysis, chart patterns, and trading signals",
system_prompt=TECHNICAL_ANALYSIS_PROMPT,
max_loops=1,
model_name="gpt-4o",
)
fundamental_agent = Agent(
agent_name="Fundamental-Analysis-Quant",
agent_description="Specialized in financial statement analysis and company valuation",
system_prompt=FUNDAMENTAL_ANALYSIS_PROMPT,
max_loops=1,
model_name="gpt-4o",
)
risk_agent = Agent(
agent_name="Risk-Management-Quant",
agent_description="Specialized in portfolio optimization and risk management strategies",
system_prompt=RISK_MANAGEMENT_PROMPT,
max_loops=1,
model_name="gpt-4o",
)
# Create the majority voting swarm with the three specialized quant agents
swarm = MajorityVoting(
name="Quant-Analysis-Swarm",
description="Analysis of the current market conditions and provide investment recommendations for a $40k portfolio.",