Curious about multi-agent AI systems but unsure where to start? This tutorial will guide you through creating a basic multi-agent stock market assistant using Python and the Swarm framework. We’ll break down the process of building a system where different AI agents work together to handle various aspects of stock market queries. By the end of this tutorial, you’ll understand the fundamentals of multi-agent systems, how to set up specialized agents for different tasks, and how they can collaborate to provide useful information. This project is perfect for beginners looking to explore practical applications of AI in a financial context, without diving into complex algorithms or advanced trading strategies. Let’s get started with this hands-on introduction to multi-agent systems!
What is Swarm?
Swarm is an ergonomic, lightweight multi-agent orchestration framework designed to simplify the coordination of multiple specialized agents. It is still in an experimental stage and best suited for educational purposes or small projects rather than production-level deployment.
To get started with Swarm, you can install it using the following commands:
pip install git+https://github.com/openai/swarm.git
The framework is intended to make multi-agent orchestration lightweight and highly controllable. Swarm focuses on agent coordination and handoffs, allowing for flexibility in managing tasks effectively.
For more details, you can explore Swarm’s documentation and examples to get a better understanding of how to implement your own multi-agent systems.
What is the Swarm Multi-Agent System?
The Swarm Multi-Agent system is an advanced AI framework that uses multiple specialized agents to handle complex tasks. Unlike traditional single-agent systems, Swarm takes a more efficient approach by distributing tasks among various expert agents. This ensures that the best-suited agent handles each specific problem, enhancing the overall quality of responses.
How Swarm Powers Stock Market Assistance
Our Swarm-powered Stock Market Assistant is built around three core agents:
- General Stock Assistant: Acts as the initial point of contact for users, determining the nature of their queries and directing them to the relevant specialist.
- Stock Information Specialist: Focuses on providing up-to-date stock data, including prices, company insights, and market trends.
- Stock Calculation Specialist: Handles financial calculations such as estimating profits, losses, and other key metrics necessary for making investment decisions.
The process begins with a user’s query being handled by the General Stock Assistant, which then routes it to the appropriate specialist agent. By ensuring that the right expertise is applied to each task, Swarm delivers a more accurate and effective response to user inquiries.
Conversation with Stock Information Specialist
Welcome to the Multi-Agent Stock Market Assistant!
You: Hi How can you assist me
General Stock Assistant: I can assist you with stock market inquiries. If you need stock information or want to perform any stock-related calculations, feel free to ask! If you have a general query, I'll do my best to help with that too. What would you like to know or do today?
You: What is the stock price of NVDA
Stock Information Specialist: The current stock price of NVIDIA Corporation (NVDA) is $134.80. The company's market cap is $3,307,129,274,368.
Conversation with Stock Calculation Specialist
Welcome to the Multi-Agent Stock Market Assistant!
You: Hi How could you help me?
General Stock Assistant: I can assist you with inquiries related to the stock market. You can ask me for stock information, such as the current price or performance of specific stocks, or if you need help with calculations related to stock investments. If you have a more general query, feel free to ask!
You: Im holding stocks I want to calculate the pnl
Stock Calculation Specialist: To calculate the potential profit or loss (PNL) for your stock position, I'll need the following information:
1. **Buy Price**: The price at which you purchased the stock.
2. **Current Price**: The current market price of the stock.
3. **Shares**: The number of shares you hold.
Please provide these details, and I'll help you with the calculation!
You: I bought NVDA at 90 dollars and current price is 134 and what is the profit/loss if I hold 35 shares of NVDA
Stock Calculation Specialist: If you hold 35 shares of NVDA, you have a potential profit of $1,540.00.
List of Libraries to Install
swarm: This is the main framework we’re using for the multi-agent system.
yfinance: This is used to fetch real-time stock data.
python-dotenv: This is used to load environment variables from a .env file.
To install these libraries, you can use pip, Python’s package installer. Here’s the command to install all of them at once:
pip install git+https://github.com/openai/swarm.git yfinance python-dotenv
Here’s a basic .env file format to store the API Keys securely
# OpenAI API Key
OPENAI_API_KEY=sk-your_openai_api_key_here
The Code Behind the Magic
To give you a deeper look into how this works, here’s the core Python code that drives our Swarm Multi-Agent Stock Market Assistant:
from swarm import Swarm, Agent
import yfinance as yf
from dotenv import load_dotenv
import os
# Load environment variables from .env file
load_dotenv()
# Set the API key in the environment
os.environ["OPENAI_API_KEY"] = os.getenv('OPENAI_API_KEY')
# Function to get stock information
def get_stock_info(symbol: str):
try:
stock = yf.Ticker(symbol)
info = stock.info
return f"Company: {info['longName']}\nCurrent Price: ${info['currentPrice']:.2f}\nMarket Cap: ${info['marketCap']:,}"
except:
return f"Unable to fetch information for {symbol}. Please check the symbol and try again."
# Function to calculate potential profit/loss
def calculate_profit_loss(buy_price: float, current_price: float, shares: int):
pl = (current_price - buy_price) * shares
return f"Potential {'Profit' if pl >= 0 else 'Loss'}: ${abs(pl):.2f}"
# Function to transfer to the appropriate specialist agent
def transfer_to_specialist(query_type):
if query_type == "info":
return info_agent
elif query_type == "calculation":
return calculation_agent
else:
return general_agent
# Create the general assistant agent
general_agent = Agent(
name="General Stock Assistant",
instructions="""You are the first point of contact for stock market inquiries.
Your job is to determine whether the user is asking for stock information or wants to perform a calculation.
If they're asking for stock information, use the transfer_to_specialist("info") function.
If they're asking for a calculation, use the transfer_to_specialist("calculation") function.
If you're unsure or it's a general query, handle it yourself or use transfer_to_specialist("general").""",
functions=[transfer_to_specialist]
)
# Create the stock information agent
info_agent = Agent(
name="Stock Information Specialist",
instructions="""You are a specialist in providing stock information.
Use the get_stock_info() function to fetch information about a stock.
Always ask for the stock symbol if the user doesn't provide one.""",
functions=[get_stock_info, transfer_to_specialist]
)
# Create the calculation agent
calculation_agent = Agent(
name="Stock Calculation Specialist",
instructions="""You are a specialist in performing stock-related calculations.
Use the calculate_profit_loss() function to calculate potential profit or loss for a stock position.
Ask for the buy price, current price, and number of shares if not provided.""",
functions=[calculate_profit_loss, transfer_to_specialist]
)
# Create Swarm client
client = Swarm()
# Run the assistant
def run_stock_assistant():
print("Welcome to the Multi-Agent Stock Market Assistant!")
context_variables = {}
current_agent = general_agent
while True:
user_input = input("You: ")
if user_input.lower() in ['exit', 'quit', 'bye']:
print("Thank you for using the Multi-Agent Stock Market Assistant. Goodbye!")
break
response = client.run(
agent=current_agent,
messages=[{"role": "user", "content": user_input}],
context_variables=context_variables
)
print(f"{response.agent.name}:", response.messages[-1]["content"])
current_agent = response.agent
context_variables = response.context_variables
if __name__ == "__main__":
run_stock_assistant()
High-Level Explanation
Environment Setup: The script begins by setting up the environment, including API keys for secure access.
Utility Functions:
get_stock_info()
: Fetches real-time stock data using the yfinance library.calculate_profit_loss()
: Calculates profit or loss for a specified stock position.transfer_to_specialist()
: Directs queries to the relevant specialized agent.
Agent Definitions:
- The
general_agent
serves as the first point of contact for users. - The
info_agent
specializes in delivering stock data. - The
calculation_agent
takes care of financial calculations.
Swarm Client: A Swarm client is created to manage the interaction between agents, ensuring a seamless conversational experience for users.
Main Loop: The run_stock_assistant()
function allows users to enter queries, which are handled by the respective agent to provide accurate and specialized responses.
Benefits of Using Swarm for Stock Market Assistance
- Specialized Expertise: Each agent is designed to excel in its specific area, which ensures more accurate and detailed information.
- Efficiency: By directing queries to the right specialist immediately, users receive faster responses without unnecessary delays.
- Scalability: New specialist agents, such as those for cryptocurrency or international stock markets, can be added as needed.
- Contextual Understanding: The multi-agent system offers better comprehension of complex queries compared to a single-agent setup.
- Continuous Learning: Each agent can be updated independently, allowing for rapid improvements without needing to overhaul the entire system.
The Future of Stock Market Assistance
As we continue to enhance the Swarm Multi-Agent system, we envision even more sophisticated capabilities, such as:
- AI-Driven Predictive Analytics Advanced machine learning models will analyze vast amounts of data from diverse sources (financial reports, social media, global news) to predict market trends and individual stock performance with unprecedented accuracy.
- Personalized Robo-Advisors AI-powered assistants will offer highly customized investment advice and automated portfolio management, adapting in real-time to individual investor goals, risk tolerance, and changing market conditions.
- Collaborative Multi-Agent Decision Making Multiple specialized AI agents will work together, each focusing on different aspects such as price trends, market sentiment, and risk management. These agents will collaboratively make trading decisions based on a consensus, providing a more comprehensive and balanced approach to market analysis and trading strategies.
Conclusion
The Swarm Multi-Agent system represents a major advancement in AI-assisted stock market analysis. By combining specialized agents with intelligent query routing, it offers a highly efficient tool for navigating the complexities of stock trading. As AI technology continues to evolve, we believe tools like the Swarm Stock Market Assistant will play a crucial role in democratizing access to high-quality financial insights.