Build a ReAct agent that takes natural-language questions such as "What did Samsung Electronics close at today?" or "Compare the returns of NVDA and AAPL" and calls yfinance and pykrx directly.
ReAct (Reasoning + Acting) is a pattern in which the LLM reaches an answer by repeating Thought β Action (run a tool) β Observation (inspect the result).
Question: "Which rose more today, Samsung Electronics or SK hynix?"
Thought: I need to compare today's closing change of the two stocks.
Action: get_kr_stock_price(ticker="005930") β Samsung Electronics
Observation: {"ticker": "005930", "name": "Samsung Electronics", "close": 78400, "change_pct": +1.23}
Thought: I also need the SK hynix data.
Action: get_kr_stock_price(ticker="000660") β SK hynix
Observation: {"ticker": "000660", "name": "SK hynix", "close": 204500, "change_pct": +2.87}
Thought: SK hynix rose more, at +2.87%.
Answer: Today SK hynix (+2.87%) rose more than Samsung Electronics (+1.23%).import yfinance as yf
from langchain_core.tools import tool
from typing import Optional
import pandas as pd
@tool
def get_us_stock_price(ticker: str) -> dict:
"""
Look up the current price, change, market cap, and P/E of a US stock.
ticker: US stock symbol (e.g. AAPL, MSFT, NVDA, TSLA)
"""
t = yf.Ticker(ticker.upper())
info = t.info
hist = t.history(period="2d")
if hist.empty or not info:
return {"error": f"No data found for '{ticker}'."}
prev_close = hist['Close'].iloc[-2] if len(hist) >= 2 else hist['Close'].iloc[-1]
curr_close = hist['Close'].iloc[-1]
change_pct = ((curr_close - prev_close) / prev_close) * 100
return {
"ticker": ticker.upper(),
"name": info.get("longName", ticker),
"price": round(curr_close, 2),
"currency": "USD",
"change_pct": round(change_pct, 2),
"market_cap": info.get("marketCap"),
"pe_ratio": info.get("trailingPE"),
"52w_high": info.get("fiftyTwoWeekHigh"),
"52w_low": info.get("fiftyTwoWeekLow"),
}
@tool
def get_us_index(index: str = "SP500") -> dict:
"""
Look up the major US indexes.
index: SP500 | NASDAQ | DOW | VIX
"""
symbol_map = {
"SP500": "^GSPC",
"NASDAQ": "^IXIC",
"DOW": "^DJI",
"VIX": "^VIX",
}
symbol = symbol_map.get(index.upper(), "^GSPC")
t = yf.Ticker(symbol)
hist = t.history(period="2d")
if hist.empty:
return {"error": f"Could not fetch index data: {index}"}
curr = hist['Close'].iloc[-1]
prev = hist['Close'].iloc[-2] if len(hist) >= 2 else curr
return {
"index": index.upper(),
"value": round(curr, 2),
"change_pct": round(((curr - prev) / prev) * 100, 2),
}
@tool
def compare_us_stocks(tickers: str, period: str = "1mo") -> str:
"""
Compare the returns of several US stocks.
tickers: comma-separated symbols (e.g. "AAPL,MSFT,NVDA")
period: 1d | 5d | 1mo | 3mo | 6mo | 1y
"""
symbols = [t.strip().upper() for t in tickers.split(",")]
data = yf.download(symbols, period=period, auto_adjust=True)["Close"]
if data.empty:
return "Could not fetch the data."
returns = ((data.iloc[-1] - data.iloc[0]) / data.iloc[0] * 100).round(2)
result = [f"{sym}: {ret:+.2f}%" for sym, ret in returns.items()]
return f"{period} return comparison:\n" + "\n".join(result)from pykrx import stock
from langchain_core.tools import tool
from datetime import datetime, timedelta
import pandas as pd
def _today() -> str:
return datetime.today().strftime("%Y%m%d")
def _prev_day(days: int = 1) -> str:
return (datetime.today() - timedelta(days=days)).strftime("%Y%m%d")
@tool
def get_kr_stock_price(ticker: str) -> dict:
"""
Look up the current quote of a Korean stock.
ticker: 6-digit stock code (e.g. 005930=Samsung Electronics, 000660=SK hynix, 035420=NAVER)
"""
try:
name = stock.get_market_ticker_name(ticker)
df = stock.get_market_ohlcv_by_date(_prev_day(5), _today(), ticker)
df = df.dropna()
if df.empty:
return {"error": f"No data for '{ticker}'."}
row = df.iloc[-1]
prev_close = df.iloc[-2]["μ’
κ°"] if len(df) >= 2 else row["μκ°"]
change_pct = ((row["μ’
κ°"] - prev_close) / prev_close) * 100
return {
"ticker": ticker,
"name": name,
"close": int(row["μ’
κ°"]),
"currency": "KRW",
"change_pct": round(change_pct, 2),
"volume": int(row["κ±°λλ"]),
"open": int(row["μκ°"]),
"high": int(row["κ³ κ°"]),
"low": int(row["μ κ°"]),
}
except Exception as e:
return {"error": str(e)}
@tool
def search_kr_ticker(company_name: str) -> list:
"""
Search for a Korean stock code by company name.
company_name: company name as listed on KRX, in Korean (e.g. μΌμ±μ μ, μΉ΄μΉ΄μ€, νλμ°¨)
"""
all_tickers = stock.get_market_ticker_list(market="ALL")
results = []
for t in all_tickers:
name = stock.get_market_ticker_name(t)
if company_name in name:
results.append({"ticker": t, "name": name})
if len(results) >= 5:
break
return results
@tool
def get_kr_top_stocks(market: str = "KOSPI", by: str = "κ±°λλ", limit: int = 5) -> str:
"""
Look up the top stocks in the Korean stock market.
market: KOSPI | KOSDAQ
by: κ±°λλ (volume) | κ±°λλκΈ (trading value) | μκ°μ΄μ‘ (market cap) β pykrx column names
limit: number of stocks to return (max 10)
"""
df = stock.get_market_ohlcv_by_ticker(_today(), market=market)
if df.empty:
df = stock.get_market_ohlcv_by_ticker(_prev_day(1), market=market)
top = df.nlargest(min(limit, 10), by)
lines = [f"{market} top {limit} by {by}:"]
for ticker, row in top.iterrows():
name = stock.get_market_ticker_name(ticker)
lines.append(f" {name}({ticker}): {by} {row[by]:,}")
return "\n".join(lines)import yfinance as yf
from langchain_core.tools import tool
@tool
def get_exchange_rate(pair: str = "USDKRW") -> dict:
"""
Look up an exchange rate.
pair: currency pair (e.g. USDKRW, EURKRW, JPYKRW, USDEUR)
"""
# Yahoo Finance FX symbol format: USDKRW=X
symbol = f"{pair.upper()}=X"
t = yf.Ticker(symbol)
hist = t.history(period="5d")
if hist.empty:
return {"error": f"No exchange rate data found: {pair}"}
rate = hist['Close'].iloc[-1]
prev = hist['Close'].iloc[-2] if len(hist) >= 2 else rate
return {
"pair": pair.upper(),
"rate": round(rate, 4),
"change_pct": round(((rate - prev) / prev) * 100, 4),
}from langchain_ollama import ChatOllama
from langchain.agents import create_react_agent, AgentExecutor
from langchain_core.prompts import PromptTemplate
from langchain import hub
from tools.us_stock import get_us_stock_price, get_us_index, compare_us_stocks
from tools.kr_stock import get_kr_stock_price, search_kr_ticker, get_kr_top_stocks
from tools.forex import get_exchange_rate
# Full Tool list
MARKET_TOOLS = [
get_us_stock_price,
get_us_index,
compare_us_stocks,
get_kr_stock_price,
search_kr_ticker,
get_kr_top_stocks,
get_exchange_rate,
]
SYSTEM_PROMPT = """You are an expert on the US and Korean stock markets.
Use the provided tools to answer the user's question.
Always give specific figures and state the unit clearly (USD/KRW/%).
Do not give investment advice; provide objective data only."""
def build_market_agent(model: str = "llama3.1:8b") -> AgentExecutor:
llm = ChatOllama(model=model, temperature=0)
# ReAct prompt template
prompt = PromptTemplate.from_template(
SYSTEM_PROMPT + """
Available tools:
{tools}
Tool names: {tool_names}
Question: {input}
{agent_scratchpad}"""
)
agent = create_react_agent(llm, MARKET_TOOLS, prompt)
return AgentExecutor(
agent=agent,
tools=MARKET_TOOLS,
verbose=True, # print the reasoning trace
max_iterations=5, # maximum number of Tool calls
handle_parsing_errors=True,
)
# Singleton
_agent: AgentExecutor | None = None
def get_market_agent() -> AgentExecutor:
global _agent
if _agent is None:
_agent = build_market_agent()
return _agentfrom fastapi import APIRouter, HTTPException
from pydantic import BaseModel
from agents.market_agent import get_market_agent
router = APIRouter(prefix="/market", tags=["Market data"])
class MarketQuery(BaseModel):
question: str
class MarketResponse(BaseModel):
question: str
answer: str
@router.post("/ask", response_model=MarketResponse)
async def ask_market(query: MarketQuery):
"""Query market data with a natural-language question."""
try:
agent = get_market_agent()
result = agent.invoke({"input": query.question})
return MarketResponse(question=query.question, answer=result["output"])
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))from agents.market_agent import build_market_agent
agent = build_market_agent()
questions = [
"Tell me the current price and P/E of Apple (AAPL)",
"How are the S&P 500 and NASDAQ doing today?",
"What did Samsung Electronics close at today?",
"Compare the 1-month returns of NVDA, AAPL, and MSFT",
"What is the dollar-won exchange rate?",
"What are the top 5 KOSPI stocks by volume?",
]
for q in questions:
print(f"\nQ: {q}")
result = agent.invoke({"input": q})
print(f"A: {result['output']}")# Test after starting the server
curl -X POST http://localhost:8000/market/ask \
-H "Content-Type: application/json" \
-d '{"question": "Which rose more today, Samsung Electronics or SK hynix?"}'
# Expected response:
# {
# "question": "Which rose more today, Samsung Electronics or SK hynix?",
# "answer": "Today SK hynix (+2.87%) rose more than Samsung Electronics (+1.23%)."
# }After the Korean market close: pykrx data is finalized after the daily close (3:30 PM KST). During trading hours it may return the previous close. If you need real-time trade prices, add the Korea Investment & Securities Open API.