With the increase in ai in finance, investors take advantage of more and more ideas driven by ai for better decision making. This article explores how we can create a multiple agent hierarchical system using the Langgraph supervisor to analyze the financial market trends, perform feelings analysis and provide investment recommendations. When integrating specialized agents for market data recovery, feelings analysis, quantitative analysis and investment strategy formulation, we allow an intelligent and automated system that mimics the workflow of human financial analysts.
Learning objectives
- Learn hierarchical structures, supervisory roles and agents coordination.
- Build specific analysis agents of the domain, feeling and quantitative analysis.
- Manage agent communication and configure hierarchical workflows.
- Integrate ai's ideas for data -based recommendations.
- Implement, optimize and climb applications promoted by ai.
- Mitigia biases, guarantees transparency and improves reliability.
- This module provides a practical approach to build intelligent systems of multiple agents driven by ai using scalable frames.
This article was published as part of the Blogathon of Data Sciences.
<h2 class="wp-block-heading" id="h-multi-agent-ai-system-langchain-supervisor”>Multiple agents ai system: Langchain supervisor
Here is a simple example of a supervisor that manages two specialized agents:

You can control how agent messages are added to the general conversation history of the multiple agents system:
Include the history of complete messages of an agent:

The architecture of multiple agents
Our system consists of five specialized agents who work in a coordinated manner:
- Market Data Agent (Market_data_expert) -Itbies prices of shares in real time, relations P/E, EPS and income growth. Responsible for real -time financial data, including shares prices, profit price relations (p/e), earnings per share (EPS) and income growth. Ensures that the system has updated market data for analysis.
- Feelings analysis agent (feeling_expert) – Analyze the news and feeling of social networks for actions. Classify feeling as positive, neutral or negative to evaluate the mood of the market towards specific actions.
- Quantitative analysisSister agent (quant_expert) – Calculate the trends in the price of shares, mobile averages and volatility metrics. It helps detect trends, possible break -up points and risk levels based on past market data.
- Investment Strategy Agent (strategy_expert) – Use all available ideas to generate a purchase/sale/retention recommendation. It determines whether an action should be marked as a purchase, sale or maintenance based on the risks and opportunities calculated.
- Supervisor agent (Market_Superervisor) -Get all agents, ensuring the delegation of tasks and decision making without problems. Coordinates the multiple interactions of agents, monitor the efficiency of the workflow and add the final recommendations for the user.
<h2 class="wp-block-heading" id="h-hands-on-multi-agent-ai-system-for-financial-market-analysis”>ai system of multiple practical agents for financial market analysis
1. Environment configuration
Before implementing the system, install the necessary units:
!pip install langgraph-supervisor langchain-openai
Configure your OpenAI API key safely:
import os
os.environ("OPENAI_API_KEY") = ""
2. Definition of specialized agent functions
Get market data
# 1. Fetching Market Data
def fetch_market_data(stock_symbol: str) -> dict:
"""Simulate fetching stock market data for a given symbol."""
market_data = {
"AAPL": {"price": 185.22, "pe_ratio": 28.3, "eps": 6.5, "revenue_growth": 8.5},
"GOOG": {"price": 142.11, "pe_ratio": 26.1, "eps": 5.8, "revenue_growth": 7.9},
"TSLA": {"price": 220.34, "pe_ratio": 40.2, "eps": 3.5, "revenue_growth": 6.2},
}
return market_data.get(stock_symbol, {})
Realization of feelings analysis
# 2. Sentiment Analysis
def analyze_sentiment(stock_symbol: str) -> dict:
"""Perform sentiment analysis on financial news for a stock."""
sentiment_scores = {
"AAPL": {"news_sentiment": "Positive", "social_sentiment": "Neutral"},
"GOOG": {"news_sentiment": "Negative", "social_sentiment": "Positive"},
"TSLA": {"news_sentiment": "Positive", "social_sentiment": "Negative"},
}
return sentiment_scores.get(stock_symbol, {})
Computer of quantitative analysis metrics
# 3. Quantitative Analysis
def compute_quant_metrics(stock_symbol: str) -> dict:
"""Compute SMA, EMA, and volatility for stock."""
quant_metrics = {
"AAPL": {"sma_50": 180.5, "ema_50": 182.1, "volatility": 1.9},
"GOOG": {"sma_50": 140.8, "ema_50": 141.3, "volatility": 2.1},
"TSLA": {"sma_50": 215.7, "ema_50": 218.2, "volatility": 3.5},
}
return quant_metrics.get(stock_symbol, {})
Generating investment recommendations
# 4. Investment Strategy Decision
def investment_strategy(stock_symbol: str, market_data: dict, sentiment: dict, quant: dict) -> str:
"""Analyze data and generate buy/sell/hold recommendation."""
if not market_data or not sentiment or not quant:
return "Not enough data for recommendation."
decision = "Hold"
if market_data("pe_ratio") < 30 and sentiment("news_sentiment") == "Positive" and quant("volatility") < 2:
decision = "Buy"
elif market_data("pe_ratio") > 35 or sentiment("news_sentiment") == "Negative":
decision = "Sell"
return f"Recommended Action for {stock_symbol}: {decision}"
3. Creation and implementation of agents
import os
from langchain_openai import ChatOpenAI
from langgraph_supervisor import create_supervisor
from langgraph.prebuilt import create_react_agent
# Initialize the Chat model
model = ChatOpenAI(model="gpt-4o")
### --- CREATE AGENTS --- ###
# Market Data Agent
market_data_expert = create_react_agent(
model=model,
tools=(fetch_market_data),
name="market_data_expert",
prompt="You are an expert in stock market data. Fetch stock data when requested."
)
# Sentiment Analysis Agent
sentiment_expert = create_react_agent(
model=model,
tools=(analyze_sentiment),
name="sentiment_expert",
prompt="You analyze financial news and social media sentiment for stock symbols."
)
# Quantitative Analysis Agent
quant_expert = create_react_agent(
model=model,
tools=(compute_quant_metrics),
name="quant_expert",
prompt="You analyze stock price trends, moving averages, and volatility metrics."
)
# Investment Strategy Agent
strategy_expert = create_react_agent(
model=model,
tools=(investment_strategy),
name="strategy_expert",
prompt="You make investment recommendations based on market, sentiment, and quant data."
)
### --- SUPERVISOR AGENT --- ###
market_supervisor = create_supervisor(
agents=(market_data_expert, sentiment_expert, quant_expert, strategy_expert),
model=model,
prompt=(
"You are a financial market supervisor managing four expert agents: market data, sentiment, "
"quantitative analysis, and investment strategy. For stock queries, use market_data_expert. "
"For news/social sentiment, use sentiment_expert. For stock price analysis, use quant_expert. "
"For final investment recommendations, use strategy_expert."
)
)
# Compile into an executable workflow
app = market_supervisor.compile()
4. Executing the system
### --- RUN THE SYSTEM --- ###
stock_query = {
"messages": (
{"role": "user", "content": "What is the investment recommendation for AAPL?"}
)
}
# Execute query
result = app.invoke(stock_query)
print(result('messages')(-1).content)

The ai system has analyzed market data, feeling and technical indicators to recommend an investment action
Future improvements
- Connect to API Reales (Yahoo Finance, Alpha Vantage) for cattle data.
- Improve feelings analysis by integrating social networks monitoring.
- Expand portfolio management to include risk and diversification evaluation strategies.
This framework of multiple agents is a scalable solution for financial analysis, capable of making real -time investment decisions with minimal human intervention!
Key control
- An ai system of multiple agents automates the analysis of market trends, the evaluation of feelings and investment recommendations.
- Specialized agents handle market data, feelings analysis, quantitative metrics and investment strategy, managed by a supervisor agent.
- The system is built using the Langgraph supervisor, the definition of agents functions, implementing them and executing investment consultations.
- The approach to multiple agents improves modularity, scalability, automation and precision in financial decision making.
- Integration of real -time financial API, monitoring of advanced feelings and portfolio management for a more comprehensive ai investment system.
The means shown in this article are not owned by Analytics Vidhya and are used at the author's discretion.
Frequent questions
ANS. Langgraph supervisor is a Python Library that helps you create hierarchical systems of multiple agents. You can define specialized agents and make a central supervisor organize its interactions and tasks.
ANS. The supervisor agent uses a guide message and the content of the user's application to determine which specialized agent can meet the consultation. For example, if a query requires obtaining data, the supervisor will pass it to a market data agent. If you imply feelings analysis, delegate the feelings analysis agent, etc.
ANS. Yes. You can replace simulated functions (such as FETCH_MARKET_Data) with real API calls to services such as Yahoo Finance, Alpha Vantage or any other financial data provider.
ANS. An architecture of multiple agents allows each agent to focus on a specialized task (for example, market data recovery, feelings analysis). This modular approach is easier to climb and maintain, and can reuse or replace individual agents without reviewing the entire system.
ANS. <a target="_blank" href="https://github.com/langchain-ai/langgraph-supervisor”>Langgraph Supervisor You can store the conversation history and agents' responses. You can configure it to keep transcripts of complete agent conversation or simply final answers. For advanced use cases, you can integrate short or long term memory for agents to refer to past interactions.
(Tagstotranslate) Blogathon