Skip to main content
AIDevOps
  • Learn
  • Learning Paths
  • Practice
  • Open Source
  • Books
  • Engineering

    AI DevOpsThe full map of building and operating AI servicesLLMOpsLLM deployment ยท evaluation ยท observabilityHands-on ProjectsBuild AI Agent projects

    Knowledge

    DocsTechnical documentationBlogEngineering articlesPloggerDevelopment log feed

    Validate

    Certification3-level skills certification ยท coming soon
AI Models
LlamaTutorial|MistralTutorial|GemmaTutorial|DeepSeekTutorial|QwenTutorial
๐Ÿง  AI Agent Development
Finance AI AgentLLM API ServerStock Investing AgentAIOps AI AgentEducation AI AgentCoding AI Agent
๐Ÿค– AI Applied Development
Applied AI Intro & RoadmapHugging FaceLangChainLlamaIndexLLMOps|LangGraphMCPMulti-AgentAgent Evaluation
๐Ÿง  AI Core
AI Intro & RoadmapML FundamentalsLLM Fundamentals|Python AIC++|PyTorchTensorFlowJAX
๐ŸŒฑ Spring Cloud
Spring Intro & RoadmapSpring Cloud GatewaySpring BootJava|Spring AISpring SecuritySpring BatchSpring JPA
๐Ÿณ DevOps
DevOps Intro & RoadmapLinuxDockerCI/CD|Kubernetes BasicsK8s AdvancedPrometheusGrafana
๐Ÿงฑ Infrastructure
Infrastructure Intro & RoadmapNginxRedis
โ˜๏ธ Cloud
Cloud Intro & RoadmapAWSGCPAzureNCPCloudflare
๐ŸŽจ Frontend
Frontend Intro & RoadmapJavaScriptTypeScript|ReactNext.js|VueNuxt|Electron
๐Ÿ“ฑ Mobile
Mobile Intro & RoadmapKotlinAndroidFlutter
โš™๏ธ Backend
Backend Intro & RoadmapPython BasicsFastAPIDjangoFlask|CGoGinNode.js
๐Ÿ’พ Database
DB Intro & RoadmapCore SQLOracleMySQLPostgreSQL|MongoDBVector DB
๐Ÿงช Testing
k6JMeternGrinder
AIDevOps

Engineering AI. From Code to Production.
An engineering learning platform for building and operating AI and AI Agents

Learn

  • All Guides
  • Learning Paths
  • AI Tutorial
  • Practice
  • Books

Resources

  • AI DevOps
  • LLMOps
  • Hands-on Projects
  • Docs
  • Blog
  • Plogger
  • Open Source
  • Certification (coming soon)

Start Here

  • AI Core Roadmap
  • AI Applied Development Roadmap
  • Spring Cloud Roadmap
  • DevOps Roadmap
  • Infrastructure Roadmap

ย 

  • Cloud Roadmap
  • Frontend Roadmap
  • Mobile Roadmap
  • Backend Roadmap
  • Database Roadmap
ยฉ 2026 AIDevOps. All rights reserved.
Terms of ServicePrivacy PolicySitemaptestforge.kr
Finance AI Agent 04

๐Ÿ“Š Technical Analysis Agent Tool Use Pattern

Visitors

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.

โ† AI Agent series
๐Ÿ“Š

Contents

0 / 9
  1. Implementing indicator Tools
  2. Moving averages & golden cross
  3. RSI
  4. MACD
  5. Bollinger Bands
  6. Combined buy/sell signal
  7. Simple backtesting
  8. Building the Tool Use Agent
  9. Example runs
Contents 9 sections
  1. Implementing indicator Tools
  2. Moving averages & golden cross
  3. RSI
  4. MACD
  5. Bollinger Bands
  6. Combined buy/sell signal
  7. Simple backtesting
  8. Building the Tool Use Agent
  9. Example runs

Implementing indicator Tools

Compute the key indicators with the pandas-ta library and wrap each one as a LangChain Tool.

Moving averages & golden cross

tools/technical.pyPYTHON
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)

RSI

PYTHON
@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}"
    )

MACD

PYTHON
@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}"
    )

Bollinger Bands

PYTHON
@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}"
    )

Combined buy/sell signal

tools/signal.pyPYTHON
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}"
    )

Simple backtesting

tools/backtest.pyPYTHON
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.

Building the Tool Use Agent

agents/technical_agent.pyPYTHON
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)

Example runs

PYTHON
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']}")