DSPy ReAct와 Yahoo Finance 뉴스로 만드는 금융 분석
DSPy ReAct와 Yahoo Finance 뉴스로 만드는 금융 분석
이 튜토리얼에서는 DSPy와 LangChain의 Yahoo Finance News 도구를 함께 사용해, 실시간 시장 분석을 수행하는 금융 분석 에이전트를 만들어 볼게요. ReAct라는 방식으로 도구 호출과 추론을 오가며 뉴스를 가져오고, 감성을 분석하고, 투자 시각을 내놓는 흐름을 차근차근 따라가면 돼요.
출처: 문서
본문
무엇을 만들까요
뉴스를 가져오고, 감성을 분석하고, 투자 시각을 제시하는 금융 에이전트를 만들어요. 즉 "지금 애플에 무슨 일이 일어나고 있고, 주가에 어떤 영향을 줄까?" 같은 질문에 답할 수 있는 시스템이죠.
설정 (Setup)
pip install dspy langchain langchain-community yfinance
1단계: LangChain 도구를 DSPy로 변환하기
먼저 LangChain의 야후 파이낸스 뉴스 도구를 DSPy가 이해할 수 있는 Tool로 감싸줄게요. 이렇게 하면 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, allow_tool_async_sync_conversion=True)
# Convert LangChain Yahoo Finance tool to DSPy
yahoo_finance_tool = YahooFinanceNewsTool()
finance_news_tool = Tool.from_langchain(yahoo_finance_tool)
Tool.from_langchain()이 핵심이에요. LangChain 도구 객체를 받아 DSPy에서 바로 호출할 수 있는 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)}"
이 함수들은 주가·변동률 등을 JSON 문자열로 돌려줘요. 에이전트가 이 결과를 다시 읽고 분석에 활용할 수 있게 말이죠.
3단계: 금융 ReAct 에이전트 만들기
이제 세 도구를 한데 모아 dspy.ReAct 에이전트로 묶을게요. max_iters=6은 질문에 답할 때까지 도구를 최대 6번까지 쓸 수 있다는 뜻이에요.
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)
signature="financial_query -> analysis_response"는 이 에이전트가 금융 질문(financial_query)을 받아 분석 결과(analysis_response)를 내놓는다는 계약을 선언한 거예요.
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()
예시 출력 (Example Output)
"애플에 대한 최신 뉴스가 뭐야?" 같은 질문으로 에이전트를 실행하면 이렇게 동작해요:
- Yahoo Finance News 도구로 최신 애플 뉴스를 가져오고
- 현재 주가 데이터를 얻은 뒤
- 이 정보를 분석해 통찰을 제시해요
예시 응답:
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.
비동기 도구 다루기
LangChain 도구 중에는 성능을 위해 async 연산을 쓰는 것이 많아요. async 도구에 대한 자세한 내용은 Tools 문서를 참고하세요.
핵심 장점
- 도구 통합 (Tool Integration): LangChain 도구와 DSPy ReAct를 자연스럽게 결합해요
- 실시간 데이터 (Real-time Data): 최신 시장 데이터와 뉴스에 접근해요
- 확장성 (Extensible): 금융 분석 도구를 쉽게 더 추가할 수 있어요
- 지능적 추론 (Intelligent Reasoning): ReAct 프레임워크가 단계별 분석을 제공해요
이 튜토리얼은 DSPy의 ReAct 프레임워크가 LangChain의 금융 도구와 함께 동작해 지능적인 시장 분석 에이전트를 만드는 과정을 보여줘요.