構建用於金融市場分析的多代理人工智慧系統

構建用於金融市場分析的多代理人工智慧系統

隨著人工智慧在金融領域的興起,投資者正越來越多地利用人工智慧驅動的洞察力來做出更好的決策。本文探討了如何利用 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、高階情緒跟蹤和投資組合管理,打造更全面的人工智慧驅動的投資系統。

評論留言