With the rise of AI in finance, investors are increasingly leveraging AI-driven insights for better decision-making. This article explores how we can create a hierarchical multi-agent AI system using LangGraph Supervisor to analyze financial market trends, perform sentiment analysis, and provide investment recommendations. By integrating specialized agents for market data retrieval, sentiment analysis, quantitative analysis, and investment strategy formulation, we enable an intelligent, automated system that mimics the workflow of human financial analysts.
This article was published as a part of the Data Science Blogathon.
Here’s a simple example of a supervisor managing two specialized agents:
You can control how agent messages are added to the overall conversation history of the multi-agent system:
Include full message history from an agent:
Our system consists of five specialized AI agents working in a coordinated manner:
Before implementing the system, install the necessary dependencies:
!pip install langgraph-supervisor langchain-openai
Set up your OpenAI API key securely:
import os
os.environ["OPENAI_API_KEY"] = "<your_api_key>"
# 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, {})
# 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, {})
# 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, {})
# 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}"
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()
### --- 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, sentiment, and technical indicators to recommend an investment action
This multi-agent framework is a scalable AI solution for financial analysis, capable of real-time investment decision-making with minimal human intervention!
The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.
Ans. LangGraph Supervisor is a Python library that helps you create hierarchical multi-agent systems. You can define specialized agents and have a central supervisor orchestrate their interactions and tasks.
Ans. The supervisor agent uses a guiding prompt and the content of the user’s request to determine which specialized agent can fulfill the query. For example, if a query requires fetching data, the supervisor will pass it to a market data agent. If it involves sentiment analysis, it delegates to the sentiment analysis agent, and so on.
Ans. Yes. You can replace the simulated functions (like fetch_market_data) with actual API calls to services such as Yahoo Finance, Alpha Vantage, or any other financial data provider.
Ans. A multi-agent architecture allows each agent to focus on a specialized task (e.g., market data retrieval, sentiment analysis). This modular approach is easier to scale and maintain, and you can reuse or replace individual agents without overhauling the entire system.
Ans. LangGraph Supervisor can store conversation history and agent responses. You can configure it to maintain full agent conversation transcripts or just final responses. For advanced use cases, you can integrate short-term or long-term memory so that agents can refer to past interactions.