构建用于金融市场分析的多代理人工智能系统

构建用于金融市场分析的多代理人工智能系统

随着人工智能在金融领域的兴起,投资者正越来越多地利用人工智能驱动的洞察力来做出更好的决策。本文探讨了如何利用 LangGraph Supervisor 创建一个分层多代理人工智能系统,以分析金融市场趋势、执行情感分析并提供投资建议。通过整合用于市场数据检索、情感分析、定量分析和投资策略制定的专业代理,我们可以创建一个模仿人类金融分析师工作流程的智能自动化系统。

学习目标

  • 学习分层结构、主管角色和代理协调。
  • 构建特定领域、情感和定量分析代理。
  • 管理代理交流并配置分层工作流程。
  • 整合人工智能洞察力,提供数据驱动的建议。
  • 实施、优化和扩展人工智能驱动的应用程序。
  • 减少偏见,确保透明度,提高可靠性。
  • 本模块提供了使用可扩展框架构建智能、人工智能驱动的多代理系统的实践方法。

多代理人工智能系统:LangGraph Supervisor

下面是一个简单的例子,说明一个主管如何管理两个专门的代理:

LangGraph Supervisor

Source: Langchain Supervisor

您可以控制将代理信息添加到多代理系统整体对话历史记录中的方式:

包括来自代理的完整信息历史记录:

LangGraph Supervisor

Source: Langchain Supervisor

多代理架构

我们的系统由五个以协调方式工作的专门人工智能代理组成:

  • 市场数据代理market_data_expert )- 获取实时股票价格、市盈率、每股收益和收入增长。负责获取实时金融数据,包括股票价格、市盈率、每股收益和收入增长。确保系统有最新的市场数据可供分析。
  • 情绪分析代理(sentiment_expert) – 分析股票的新闻和社交媒体情绪。将情绪分为正面、中性或负面,以评估市场对特定股票的情绪。
  • 定量分析代理 (quant_expert) – 计算股价趋势、移动平均线和波动指标。根据过去的市场数据,帮助检测趋势、潜在突破点和风险水平。
  • 投资策略代理(strategy_expert) – 利用所有可用的洞察力生成买入/卖出/持有建议。根据计算出的风险和机会,决定是否将股票标记为买入、卖出或持有。
  • 主管代理(market_supervisor) – 管理所有代理,确保任务授权和决策的顺利进行。协调多代理互动,监控工作流程效率,并为用户汇总最终建议。

用于金融市场分析的多代理AI系统实践

1. 设置环境

在实施系统之前,请安装必要的依赖项:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
!pip install langgraph-supervisor langchain-openai
!pip install langgraph-supervisor langchain-openai
!pip install langgraph-supervisor langchain-openai

安全设置 OpenAI API 密钥:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
import os
os.environ["OPENAI_API_KEY"] = "<your_api_key>"
import os os.environ["OPENAI_API_KEY"] = "<your_api_key>"
import os
os.environ["OPENAI_API_KEY"] = "<your_api_key>"

2. 定义专门代理功能

获取市场数据

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# 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, {})
# 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, {})
# 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, {})

进行情感分析

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# 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, {})
# 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, {})
# 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, {})

计算定量分析指标

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# 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, {})
# 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, {})
# 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, {})

生成投资建议

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
# 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}"
# 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}"
# 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. 创建和部署代理

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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()
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()
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. 运行系统

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
### --- 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)
### --- 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)
### --- 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)

运行系统输出截图

输出

人工智能系统分析了市场数据、情绪和技术指标,为投资行动提供建议。

小结

  • 连接真实 API(雅虎财经、Alpha Vantage),获取牲畜数据。
  • 通过整合社交媒体监测,加强情绪分析。
  • 扩展投资组合管理,纳入风险评估和多样化策略。

这个多代理框架是一个可扩展的人工智能金融分析解决方案,能够在最少人工干预的情况下进行实时投资决策!

  • 多代理人工智能系统可自动进行市场趋势分析、情感评估和投资建议。
  • 专业代理处理市场数据、情感分析、量化指标和投资策略,并由主管代理进行管理。
  • 该系统使用 LangGraph Supervisor 构建,定义代理功能、部署代理并运行投资查询。
  • 多代理方法增强了金融决策的模块化、可扩展性、自动化和准确性。
  • 集成实时金融 API、高级情绪跟踪和投资组合管理,打造更全面的人工智能驱动的投资系统。

评论留言