|
| 1 | +# Financial Analysis with DSPy ReAct and Yahoo Finance News |
| 2 | + |
| 3 | +This tutorial shows how to build a financial analysis agent using DSPy ReAct with [LangChain's Yahoo Finance News tool](https://python.langchain.com/docs/integrations/tools/yahoo_finance_news/) for real-time market analysis. |
| 4 | + |
| 5 | +## What You'll Build |
| 6 | + |
| 7 | +A financial agent that fetches news, analyzes sentiment, and provides investment insights. |
| 8 | + |
| 9 | +## Setup |
| 10 | + |
| 11 | +```bash |
| 12 | +pip install dspy langchain langchain-community yfinance |
| 13 | +``` |
| 14 | + |
| 15 | +## Step 1: Convert LangChain Tool to DSPy |
| 16 | + |
| 17 | +```python |
| 18 | +import dspy |
| 19 | +from langchain_community.tools.yahoo_finance_news import YahooFinanceNewsTool |
| 20 | +from dspy.adapters.types.tool import Tool |
| 21 | +import json |
| 22 | +import yfinance as yf |
| 23 | + |
| 24 | +# Configure DSPy |
| 25 | +lm = dspy.LM(model='openai/gpt-4o-mini') |
| 26 | +dspy.configure(lm=lm) |
| 27 | + |
| 28 | +# Convert LangChain Yahoo Finance tool to DSPy |
| 29 | +yahoo_finance_tool = YahooFinanceNewsTool() |
| 30 | +finance_news_tool = Tool.from_langchain(yahoo_finance_tool) |
| 31 | +``` |
| 32 | + |
| 33 | +## Step 2: Create Supporting Financial Tools |
| 34 | + |
| 35 | +```python |
| 36 | +def get_stock_price(ticker: str) -> str: |
| 37 | + """Get current stock price and basic info.""" |
| 38 | + try: |
| 39 | + stock = yf.Ticker(ticker) |
| 40 | + info = stock.info |
| 41 | + hist = stock.history(period="1d") |
| 42 | + |
| 43 | + if hist.empty: |
| 44 | + return f"Could not retrieve data for {ticker}" |
| 45 | + |
| 46 | + current_price = hist['Close'].iloc[-1] |
| 47 | + prev_close = info.get('previousClose', current_price) |
| 48 | + change_pct = ((current_price - prev_close) / prev_close * 100) if prev_close else 0 |
| 49 | + |
| 50 | + result = { |
| 51 | + "ticker": ticker, |
| 52 | + "price": round(current_price, 2), |
| 53 | + "change_percent": round(change_pct, 2), |
| 54 | + "company": info.get('longName', ticker) |
| 55 | + } |
| 56 | + |
| 57 | + return json.dumps(result) |
| 58 | + except Exception as e: |
| 59 | + return f"Error: {str(e)}" |
| 60 | + |
| 61 | +def compare_stocks(tickers: str) -> str: |
| 62 | + """Compare multiple stocks (comma-separated).""" |
| 63 | + try: |
| 64 | + ticker_list = [t.strip().upper() for t in tickers.split(',')] |
| 65 | + comparison = [] |
| 66 | + |
| 67 | + for ticker in ticker_list: |
| 68 | + stock = yf.Ticker(ticker) |
| 69 | + info = stock.info |
| 70 | + hist = stock.history(period="1d") |
| 71 | + |
| 72 | + if not hist.empty: |
| 73 | + current_price = hist['Close'].iloc[-1] |
| 74 | + prev_close = info.get('previousClose', current_price) |
| 75 | + change_pct = ((current_price - prev_close) / prev_close * 100) if prev_close else 0 |
| 76 | + |
| 77 | + comparison.append({ |
| 78 | + "ticker": ticker, |
| 79 | + "price": round(current_price, 2), |
| 80 | + "change_percent": round(change_pct, 2) |
| 81 | + }) |
| 82 | + |
| 83 | + return json.dumps(comparison) |
| 84 | + except Exception as e: |
| 85 | + return f"Error: {str(e)}" |
| 86 | +``` |
| 87 | + |
| 88 | +## Step 3: Build the Financial ReAct Agent |
| 89 | + |
| 90 | +```python |
| 91 | +class FinancialAnalysisAgent(dspy.Module): |
| 92 | + """ReAct agent for financial analysis using Yahoo Finance data.""" |
| 93 | + |
| 94 | + def __init__(self): |
| 95 | + super().__init__() |
| 96 | + |
| 97 | + # Combine all tools |
| 98 | + self.tools = [ |
| 99 | + finance_news_tool, # LangChain Yahoo Finance News |
| 100 | + get_stock_price, |
| 101 | + compare_stocks |
| 102 | + ] |
| 103 | + |
| 104 | + # Initialize ReAct |
| 105 | + self.react = dspy.ReAct( |
| 106 | + signature="financial_query -> analysis_response", |
| 107 | + tools=self.tools, |
| 108 | + max_iters=6 |
| 109 | + ) |
| 110 | + |
| 111 | + def forward(self, financial_query: str): |
| 112 | + return self.react(financial_query=financial_query) |
| 113 | +``` |
| 114 | + |
| 115 | +## Step 4: Run Financial Analysis |
| 116 | + |
| 117 | +```python |
| 118 | +def run_financial_demo(): |
| 119 | + """Demo of the financial analysis agent.""" |
| 120 | + |
| 121 | + # Initialize agent |
| 122 | + agent = FinancialAnalysisAgent() |
| 123 | + |
| 124 | + # Example queries |
| 125 | + queries = [ |
| 126 | + "What's the latest news about Apple (AAPL) and how might it affect the stock price?", |
| 127 | + "Compare AAPL, GOOGL, and MSFT performance", |
| 128 | + "Find recent Tesla news and analyze sentiment" |
| 129 | + ] |
| 130 | + |
| 131 | + for query in queries: |
| 132 | + print(f"Query: {query}") |
| 133 | + response = agent(financial_query=query) |
| 134 | + print(f"Analysis: {response.analysis_response}") |
| 135 | + print("-" * 50) |
| 136 | + |
| 137 | +# Run the demo |
| 138 | +if __name__ == "__main__": |
| 139 | + run_financial_demo() |
| 140 | +``` |
| 141 | + |
| 142 | +## Example Output |
| 143 | + |
| 144 | +When you run the agent with a query like "What's the latest news about Apple?", it will: |
| 145 | + |
| 146 | +1. Use the Yahoo Finance News tool to fetch recent Apple news |
| 147 | +2. Get current stock price data |
| 148 | +3. Analyze the information and provide insights |
| 149 | + |
| 150 | +**Sample Response:** |
| 151 | +``` |
| 152 | +Analysis: Given the current price of Apple (AAPL) at $196.58 and the slight increase of 0.48%, it appears that the stock is performing steadily in the market. However, the inability to access the latest news means that any significant developments that could influence investor sentiment and stock price are unknown. Investors should keep an eye on upcoming announcements or market trends that could impact Apple's performance, especially in comparison to other tech stocks like Microsoft (MSFT), which is also showing a positive trend. |
| 153 | +``` |
| 154 | + |
| 155 | +## Key Benefits |
| 156 | + |
| 157 | +- **Tool Integration**: Seamlessly combine LangChain tools with DSPy ReAct |
| 158 | +- **Real-time Data**: Access current market data and news |
| 159 | +- **Extensible**: Easy to add more financial analysis tools |
| 160 | +- **Intelligent Reasoning**: ReAct framework provides step-by-step analysis |
| 161 | + |
| 162 | +This tutorial shows how DSPy's ReAct framework works with LangChain's financial tools to create intelligent market analysis agents. |
0 commit comments