Computes RSI, MACD, Bollinger Bands, and moving averages and generates buy/sell signals. The LLM calls Tools that compute the indicators directly, then interprets the results into an analysis report investors can easily follow.
Compute the key indicators with the pandas-ta library and wrap each one as a LangChain Tool.
import yfinance as yf
import pandas as pd
import pandas_ta as ta
from langchain_core.tools import tool
from pykrx import stock
from datetime import datetime, timedelta
def _get_ohlcv_us(ticker: str, period: str = "6mo") -> pd.DataFrame:
df = yf.Ticker(ticker.upper()).history(period=period)
df.index = pd.to_datetime(df.index).tz_localize(None)
return df[["Open", "High", "Low", "Close", "Volume"]].dropna()
def _get_ohlcv_kr(ticker: str, days: int = 180) -> pd.DataFrame:
end = datetime.today().strftime("%Y%m%d")
start = (datetime.today() - timedelta(days=days)).strftime("%Y%m%d")
df = stock.get_market_ohlcv_by_date(start, end, ticker)
df.columns = ["Open", "High", "Low", "Close", "Volume"]
return df.dropna()
@tool
def get_moving_average(ticker: str, market: str = "US", windows: str = "5,20,60") -> str:
"""
Compute moving averages and whether a golden cross/death cross occurred.
ticker: stock code (US: AAPL, Korea: 005930)
market: US | KR
windows: moving-average periods (comma-separated, e.g. "5,20,60,120")
"""
df = _get_ohlcv_us(ticker) if market == "US" else _get_ohlcv_kr(ticker)
periods = [int(w.strip()) for w in windows.split(",")]
lines = [f"[{ticker} moving-average analysis]"]
curr_price = df["Close"].iloc[-1]
lines.append(f"Price: {curr_price:,.2f}")
ma_values = {}
for p in periods:
if len(df) >= p:
ma = df["Close"].rolling(p).mean().iloc[-1]
ma_values[p] = ma
position = "above" if curr_price > ma else "below"
lines.append(f"MA{p}: {ma:,.2f} (price is {position})")
# Golden cross check (short MA crossing above the long MA)
sorted_periods = sorted(ma_values.keys())
if len(sorted_periods) >= 2:
short, long_ = sorted_periods[0], sorted_periods[-1]
short_ma_prev = df["Close"].rolling(short).mean().iloc[-2]
long_ma_prev = df["Close"].rolling(long_).mean().iloc[-2]
short_ma_now = ma_values[short]
long_ma_now = ma_values[long_]
if short_ma_now > long_ma_now and short_ma_prev <= long_ma_prev:
lines.append(f"๐ข Golden cross (MA{short} > MA{long_})")
elif short_ma_now < long_ma_now and short_ma_prev >= long_ma_prev:
lines.append(f"๐ด Death cross (MA{short} < MA{long_})")
else:
trend = "bullish MA alignment" if short_ma_now > long_ma_now else "bearish MA alignment"
lines.append(f"Current trend: {trend}")
return "\n".join(lines)@tool
def get_rsi(ticker: str, market: str = "US", period: int = 14) -> str:
"""
Compute RSI (Relative Strength Index) to judge overbought/oversold conditions.
ticker: stock code
market: US | KR
period: RSI period (default 14 days)
"""
df = _get_ohlcv_us(ticker) if market == "US" else _get_ohlcv_kr(ticker)
rsi_series = ta.rsi(df["Close"], length=period)
if rsi_series is None or rsi_series.dropna().empty:
return "Could not compute RSI (not enough data)."
rsi_now = rsi_series.iloc[-1]
rsi_prev = rsi_series.iloc[-2]
if rsi_now >= 70:
signal = "๐ด Overbought (consider selling)"
elif rsi_now <= 30:
signal = "๐ข Oversold (consider buying)"
elif rsi_now > rsi_prev:
signal = "โ RSI rising (momentum strengthening)"
else:
signal = "โ RSI falling (momentum weakening)"
return (
f"[{ticker} RSI({period})]\n"
f"Current RSI: {rsi_now:.1f}\n"
f"Previous RSI: {rsi_prev:.1f}\n"
f"Verdict: {signal}"
)@tool
def get_macd(ticker: str, market: str = "US") -> str:
"""
Compute MACD (Moving Average Convergence Divergence) to provide trend-reversal signals.
ticker: stock code
market: US | KR
"""
df = _get_ohlcv_us(ticker) if market == "US" else _get_ohlcv_kr(ticker)
macd_df = ta.macd(df["Close"], fast=12, slow=26, signal=9)
if macd_df is None or macd_df.dropna().empty:
return "Could not compute MACD."
macd = macd_df["MACD_12_26_9"].iloc[-1]
signal = macd_df["MACDs_12_26_9"].iloc[-1]
hist = macd_df["MACDh_12_26_9"].iloc[-1]
hist_prev = macd_df["MACDh_12_26_9"].iloc[-2]
if hist > 0 and hist_prev <= 0:
cross = "๐ข MACD golden cross (bullish reversal signal)"
elif hist < 0 and hist_prev >= 0:
cross = "๐ด MACD death cross (bearish reversal signal)"
elif hist > 0:
cross = "๐ MACD histogram positive (uptrend)"
else:
cross = "๐ MACD histogram negative (downtrend)"
return (
f"[{ticker} MACD(12,26,9)]\n"
f"MACD: {macd:.4f}\n"
f"Signal: {signal:.4f}\n"
f"Histogram: {hist:.4f}\n"
f"Verdict: {cross}"
)@tool
def get_bollinger_bands(ticker: str, market: str = "US", period: int = 20) -> str:
"""
Compute Bollinger Bands to analyze volatility and price position.
ticker: stock code
market: US | KR
period: moving-average period (default 20 days)
"""
df = _get_ohlcv_us(ticker) if market == "US" else _get_ohlcv_kr(ticker)
bb = ta.bbands(df["Close"], length=period, std=2)
if bb is None or bb.dropna().empty:
return "Could not compute Bollinger Bands."
upper = bb[f"BBU_{period}_2.0"].iloc[-1]
middle = bb[f"BBM_{period}_2.0"].iloc[-1]
lower = bb[f"BBL_{period}_2.0"].iloc[-1]
curr = df["Close"].iloc[-1]
width = (upper - lower) / middle * 100 # band width %
pct_b = (curr - lower) / (upper - lower) * 100 # position within the band
if curr >= upper:
position = "๐ด Touching/breaking the upper band (overbought warning)"
elif curr <= lower:
position = "๐ข Touching/breaking the lower band (oversold, rebound expected)"
elif pct_b >= 70:
position = "โ Near the upper band (bullish)"
elif pct_b <= 30:
position = "โ Near the lower band (bearish)"
else:
position = "โ Middle of the band (searching for direction)"
return (
f"[{ticker} Bollinger Bands({period})]\n"
f"Upper: {upper:,.2f}\n"
f"Middle (MA{period}): {middle:,.2f}\n"
f"Lower: {lower:,.2f}\n"
f"Price: {curr:,.2f} (position in band: {pct_b:.1f}%)\n"
f"Band width: {width:.1f}%\n"
f"Verdict: {position}"
)from langchain_core.tools import tool
from tools.technical import (
_get_ohlcv_us, _get_ohlcv_kr,
get_rsi, get_macd, get_bollinger_bands, get_moving_average,
)
import pandas_ta as ta
@tool
def get_composite_signal(ticker: str, market: str = "US") -> str:
"""
Generate a buy/sell signal combining RSI, MACD, Bollinger Bands, and moving averages.
ticker: stock code
market: US | KR
"""
df = _get_ohlcv_us(ticker) if market == "US" else _get_ohlcv_kr(ticker)
scores = []
# RSI
rsi = ta.rsi(df["Close"], length=14).iloc[-1]
if rsi <= 30: scores.append(("RSI", +2, f"oversold({rsi:.1f})"))
elif rsi <= 45: scores.append(("RSI", +1, f"lower neutral({rsi:.1f})"))
elif rsi >= 70: scores.append(("RSI", -2, f"overbought({rsi:.1f})"))
elif rsi >= 55: scores.append(("RSI", -1, f"upper neutral({rsi:.1f})"))
else: scores.append(("RSI", 0, f"neutral({rsi:.1f})"))
# MACD
macd_df = ta.macd(df["Close"])
if macd_df is not None and not macd_df.dropna().empty:
hist = macd_df.iloc[-1, 2]
prev = macd_df.iloc[-2, 2]
if hist > 0 and prev <= 0: scores.append(("MACD", +2, "golden cross"))
elif hist > 0: scores.append(("MACD", +1, "positive"))
elif hist < 0 and prev >= 0: scores.append(("MACD", -2, "death cross"))
else: scores.append(("MACD", -1, "negative"))
# Bollinger Bands
bb = ta.bbands(df["Close"])
if bb is not None and not bb.dropna().empty:
curr = df["Close"].iloc[-1]
upper = bb.iloc[-1, 0]
lower = bb.iloc[-1, 2]
pct_b = (curr - lower) / (upper - lower) * 100
if pct_b <= 20: scores.append(("BB", +2, f"near lower({pct_b:.0f}%)"))
elif pct_b >= 80: scores.append(("BB", -2, f"near upper({pct_b:.0f}%)"))
else: scores.append(("BB", 0, f"middle({pct_b:.0f}%)"))
# Moving-average alignment
ma20 = df["Close"].rolling(20).mean().iloc[-1]
ma60 = df["Close"].rolling(60).mean().iloc[-1]
curr_p = df["Close"].iloc[-1]
if curr_p > ma20 > ma60: scores.append(("MA", +1, "bullish alignment"))
elif curr_p < ma20 < ma60: scores.append(("MA", -1, "bearish alignment"))
else: scores.append(("MA", 0, "mixed"))
total = sum(s for _, s, _ in scores)
detail = " | ".join(f"{name}:{label}" for name, _, label in scores)
if total >= 4: judgment = "๐ข Strong buy"
elif total >= 2: judgment = "๐ก Weak buy"
elif total <= -4: judgment = "๐ด Strong sell"
elif total <= -2: judgment = "๐ Weak sell"
else: judgment = "โช Neutral"
return (
f"[{ticker} composite signal]\n"
f"Score: {total:+d}/8\n"
f"Verdict: {judgment}\n"
f"Basis: {detail}"
)from langchain_core.tools import tool
import yfinance as yf
import pandas as pd
import pandas_ta as ta
@tool
def run_rsi_backtest(ticker: str, period: str = "1y",
rsi_buy: float = 30, rsi_sell: float = 70) -> str:
"""
Backtest a simple RSI-based buy/sell strategy.
ticker: US stock symbol (e.g. AAPL)
period: backtest period (1y | 2y | 5y)
rsi_buy: RSI buy threshold (default 30, oversold)
rsi_sell: RSI sell threshold (default 70, overbought)
"""
df = yf.Ticker(ticker.upper()).history(period=period)
df["RSI"] = ta.rsi(df["Close"], length=14)
df = df.dropna()
position = False
buy_price = 0.0
trades = []
for i, row in df.iterrows():
if not position and row["RSI"] <= rsi_buy:
position = True
buy_price = row["Close"]
elif position and row["RSI"] >= rsi_sell:
ret = (row["Close"] - buy_price) / buy_price * 100
trades.append(ret)
position = False
if not trades:
return f"{ticker} {period} backtest: no trades (RSI {rsi_buy}/{rsi_sell} condition never met)"
total_ret = sum(trades)
win_rate = sum(1 for t in trades if t > 0) / len(trades) * 100
bh_ret = (df["Close"].iloc[-1] - df["Close"].iloc[0]) / df["Close"].iloc[0] * 100
return (
f"[{ticker} RSI({rsi_buy}/{rsi_sell}) backtest โ {period}]\n"
f"Total trades: {len(trades)}\n"
f"Win rate: {win_rate:.1f}%\n"
f"Strategy cumulative return: {total_ret:+.1f}%\n"
f"Buy & Hold return: {bh_ret:+.1f}%\n"
f"Excess return: {total_ret - bh_ret:+.1f}%"
)Backtesting limits: this is a simple simulation that ignores slippage, fees, and market impact. Building a real trading strategy needs much more rigorous validation.
from langchain_ollama import ChatOllama
from langchain.agents import create_react_agent, AgentExecutor
from langchain_core.prompts import PromptTemplate
from tools.technical import get_moving_average, get_rsi, get_macd, get_bollinger_bands
from tools.signal import get_composite_signal
from tools.backtest import run_rsi_backtest
from tools.us_stock import get_us_stock_price
from tools.kr_stock import get_kr_stock_price
TECHNICAL_TOOLS = [
get_composite_signal,
get_moving_average,
get_rsi,
get_macd,
get_bollinger_bands,
run_rsi_backtest,
get_us_stock_price,
get_kr_stock_price,
]
SYSTEM = """You are a stock technical analysis expert.
You interpret technical indicators such as RSI, MACD, Bollinger Bands, and moving averages and give investors a clear analysis.
Analysis principles:
- Check the composite signal first, then refine with individual indicators
- Give the indicator values specifically
- State the limits of technical analysis
- Provide analysis only, not investment advice"""
def build_technical_agent() -> AgentExecutor:
llm = ChatOllama(model="llama3.1:8b", temperature=0)
prompt = PromptTemplate.from_template(
SYSTEM + "\n\nAvailable tools:\n{tools}\n\nTool names: {tool_names}\n\nQuestion: {input}\n{agent_scratchpad}"
)
agent = create_react_agent(llm, TECHNICAL_TOOLS, prompt)
return AgentExecutor(agent=agent, tools=TECHNICAL_TOOLS, verbose=True,
max_iterations=6, handle_parsing_errors=True)from agents.technical_agent import build_technical_agent
agent = build_technical_agent()
questions = [
"Analyze the current RSI and MACD of AAPL",
"What is the composite technical signal for Samsung Electronics (005930)?",
"Tell me where NVDA sits in its Bollinger Bands and whether its moving averages are bullishly aligned",
"Backtest the RSI 30/70 strategy on AAPL over 1 year",
"Has SK hynix (000660) had a golden cross?",
]
for q in questions:
print(f"\nQ: {q}")
result = agent.invoke({"input": q})
print(f"A: {result['output']}")