Skip to content

使用DSPy ReAct和雅虎财经新闻进行财务分析

本教程展示如何使用DSPy ReAct和LangChain的雅虎财经新闻工具构建一个金融分析智能体,用于实时市场分析。

你将构建什么

一个金融智能体,用于获取新闻、分析情绪并提供投资洞察。

设置

pip install dspy langchain langchain-community yfinance

步骤一:将LangChain工具转换为DSPy

import dspy
from langchain_community.tools.yahoo_finance_news import YahooFinanceNewsTool
from dspy.adapters.types.tool import Tool
import json
import yfinance as yf

# Configure DSPy
lm = dspy.LM(model='openai/gpt-4o-mini')
dspy.configure(lm=lm)

# Convert LangChain Yahoo Finance tool to DSPy
yahoo_finance_tool = YahooFinanceNewsTool()
finance_news_tool = Tool.from_langchain(yahoo_finance_tool)

步骤2:创建支持性金融工具

def get_stock_price(ticker: str) -> str:
    """Get current stock price and basic info."""
    try:
        stock = yf.Ticker(ticker)
        info = stock.info
        hist = stock.history(period="1d")

        if hist.empty:
            return f"Could not retrieve data for {ticker}"

        current_price = hist['Close'].iloc[-1]
        prev_close = info.get('previousClose', current_price)
        change_pct = ((current_price - prev_close) / prev_close * 100) if prev_close else 0

        result = {
            "ticker": ticker,
            "price": round(current_price, 2),
            "change_percent": round(change_pct, 2),
            "company": info.get('longName', ticker)
        }

        return json.dumps(result)
    except Exception as e:
        return f"Error: {str(e)}"

def compare_stocks(tickers: str) -> str:
    """Compare multiple stocks (comma-separated)."""
    try:
        ticker_list = [t.strip().upper() for t in tickers.split(',')]
        comparison = []

        for ticker in ticker_list:
            stock = yf.Ticker(ticker)
            info = stock.info
            hist = stock.history(period="1d")

            if not hist.empty:
                current_price = hist['Close'].iloc[-1]
                prev_close = info.get('previousClose', current_price)
                change_pct = ((current_price - prev_close) / prev_close * 100) if prev_close else 0

                comparison.append({
                    "ticker": ticker,
                    "price": round(current_price, 2),
                    "change_percent": round(change_pct, 2)
                })

        return json.dumps(comparison)
    except Exception as e:
        return f"Error: {str(e)}"

步骤3:构建金融ReAct智能体

class FinancialAnalysisAgent(dspy.Module):
    """ReAct agent for financial analysis using Yahoo Finance data."""

    def __init__(self):
        super().__init__()

        # Combine all tools
        self.tools = [
            finance_news_tool,  # LangChain Yahoo Finance News
            get_stock_price,
            compare_stocks
        ]

        # Initialize ReAct
        self.react = dspy.ReAct(
            signature="financial_query -> analysis_response",
            tools=self.tools,
            max_iters=6
        )

    def forward(self, financial_query: str):
        return self.react(financial_query=financial_query)

步骤4:运行财务分析

def run_financial_demo():
    """Demo of the financial analysis agent."""

    # Initialize agent
    agent = FinancialAnalysisAgent()

    # Example queries
    queries = [
        "What's the latest news about Apple (AAPL) and how might it affect the stock price?",
        "Compare AAPL, GOOGL, and MSFT performance",
        "Find recent Tesla news and analyze sentiment"
    ]

    for query in queries:
        print(f"Query: {query}")
        response = agent(financial_query=query)
        print(f"Analysis: {response.analysis_response}")
        print("-" * 50)

# Run the demo
if __name__ == "__main__":
    run_financial_demo()

示例输出

当你使用类似"苹果公司的最新消息是什么?"的查询运行智能体时,它将:

  1. 使用Yahoo Finance News工具获取近期苹果公司新闻
  2. 获取当前股票价格数据
  3. 分析信息并提供洞察

示例回复:

分析: 鉴于苹果公司(AAPL)当前股价为196.58美元且微涨0.48%,该股票似乎在市场上表现稳定。然而,由于无法获取最新消息,任何可能影响投资者情绪和股价的重大发展都尚不明确。投资者应密切关注可能影响苹果公司表现的即将发布的公告或市场趋势,特别是与微软(MSFT)等其他同样呈现积极趋势的科技股进行比较。

主要优势

  • 工具集成: 无缝结合LangChain工具与DSPy ReAct
  • 实时数据: 获取当前市场数据和新闻
  • 可扩展性: 轻松添加更多金融分析工具
  • 智能推理: ReAct框架提供逐步分析

本教程展示dspy的ReAct框架如何与LangChain的金融工具配合,创建智能市场分析智能体。