Building a Multi-Agent AI System for Financial Market Analysis

Adarsh Balan Last Updated : 18 Feb, 2025
5 min read

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.

Learning Objectives

  • Learn hierarchical structures, supervisor roles, and agent coordination.
  • Build domain-specific, sentiment, and quantitative analysis agents.
  • Manage agent communication and configure hierarchical workflows.
  • Integrate AI insights for data-driven recommendations.
  • Implement, optimize, and scale AI-driven applications.
  • Mitigate biases, ensure transparency, and enhance reliability.
  • This module provides a hands-on approach to building intelligent, AI-driven multi-agent systems using scalable frameworks.

This article was published as a part of the Data Science Blogathon.

Multi-Agent AI System: LangChain Supervisor

Here’s a simple example of a supervisor managing two specialized agents:

supervisor
Source: Langchain Supervisor

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:

LangChain Supervisor
Source: Langchain Supervisor

The Multi-Agent Architecture

Our system consists of five specialized AI agents working in a coordinated manner:

  • Market Data Agent (market_data_expert) – Fetches real-time stock prices, P/E ratios, EPS, and revenue growth. Responsible for fetching real-time financial data, including stock prices, price-to-earnings (P/E) ratios, earnings per share (EPS), and revenue growth. Ensures that the system has up-to-date market data for analysis.
  • Sentiment Analysis Agent (sentiment_expert) – Analyzes news and social media sentiment for stocks. Categorizes sentiment as positive, neutral, or negative to assess the market mood toward specific stocks.
  • Quantitative Analysis Agent (quant_expert) – Computes stock price trends, moving averages, and volatility metrics. Helps detect trends, potential breakout points, and risk levels based on past market data.
  • Investment Strategy Agent (strategy_expert) – Uses all available insights to generate a Buy/Sell/Hold recommendation. Determines whether a stock should be marked as a Buy, Sell, or Hold based on calculated risks and opportunities.
  • Supervisor Agent (market_supervisor) – Manages all agents, ensuring smooth task delegation and decision-making. Coordinates multi-agent interactions, monitors workflow efficiency and aggregates final recommendations for the user.

Hands-on Multi-Agent AI System for Financial Market Analysis

1. Setting Up the Environment

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>"

2. Defining Specialized Agent Functions

Fetching 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, {})

Performing Sentiment 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, {})

Computing 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. Creating and Deploying 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. Running 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)
Output
Output

The AI system has analyzed market data, sentiment, and technical indicators to recommend an investment action

Future Enhancements

  • Connect to Real APIs (Yahoo Finance, Alpha Vantage) for livestock data.
  • Enhance Sentiment Analysis by integrating social media monitoring.
  • Expand Portfolio Management to include risk assessment and diversification strategies.

This multi-agent framework is a scalable AI solution for financial analysis, capable of real-time investment decision-making with minimal human intervention! 

Key Takeaways

  • A multi-agent AI system automates market trend analysis, sentiment evaluation, and investment recommendations.
  • Specialized agents handle market data, sentiment analysis, quantitative metrics, and investment strategy, managed by a supervisor agent.
  • The system is built using LangGraph Supervisor, defining agent functions, deploying them, and running investment queries.
  • The multi-agent approach enhances modularity, scalability, automation, and accuracy in financial decision-making.
  • Integration of real-time financial APIs, advanced sentiment tracking, and portfolio management for a more comprehensive AI-powered investment system.

The media shown in this article is not owned by Analytics Vidhya and is used at the Author’s discretion.

Frequently Asked Questions

Q1. What is a LangGraph Supervisor?

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.

Q2. How does the Supervisor Agent decide which agent to invoke?

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.

Q3. Can I use real-time data instead of the simulated examples?

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.

Q4. Why do we need a multi-agent approach?

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.

Q5. How does memory and conversation history work?

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.

Hi! I'm Adarsh, a Business Analytics graduate from ISB, currently deep into research and exploring new frontiers. I'm super passionate about data science, AI, and all the innovative ways they can transform industries. Whether it's building models, working on data pipelines, or diving into machine learning, I love experimenting with the latest tech. AI isn't just my interest, it's where I see the future heading, and I'm always excited to be a part of that journey!

Responses From Readers

Clear

We use cookies essential for this site to function well. Please click to help us improve its usefulness with additional cookies. Learn about our use of cookies in our Privacy Policy & Cookies Policy.

Show details