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 05

๐Ÿ’ผ Portfolio Multi-Agent LangGraph Collaboration

Visitors

Researcher (filings analysis) โ†’ Analyst (technical analysis) โ†’ Risk Manager (risk assessment) โ†’ Portfolio Manager (final decision). Each agent takes a specialist role and they collaborate in a LangGraph workflow.

โ† AI Agent series
๐Ÿ’ผ

Contents

0 / 10
  1. Why multi-agent
  2. Designing the LangGraph workflow
  3. Defining shared state
  4. Researcher agent
  5. Analyst agent
  6. Risk Manager agent
  7. Portfolio Manager
  8. Compiling & running the graph
  9. FastAPI integration
  10. Example runs
Contents 10 sections
  1. Why multi-agent
  2. Designing the LangGraph workflow
  3. Defining shared state
  4. Researcher agent
  5. Analyst agent
  6. Risk Manager agent
  7. Portfolio Manager
  8. Compiling & running the graph
  9. FastAPI integration
  10. Example runs

Why multi-agent

There are reasons portfolio management is hard to handle with a single agent.

ProblemSingle-agent limitMulti-agent solution
Context lengthContext overflows when analyzing 10 stocksIndependent context per agent
SpecializationNot good at filings analysis and technical analysis at onceRoles split per agent
ParallelismSequential processing onlyResearch several stocks in parallel
Checks & balancesHard to catch its own mistakesRisk Manager reviews
โ„น๏ธ

Design principle: use multi-agent only when it is really needed. This scenario (portfolio rebalancing) fits because it calls for a clear separation of roles: research, analysis, risk assessment, and the final decision.

Designing the LangGraph workflow

TEXT
[User request] "Rebalance my portfolio"
          โ”‚
          โ–ผ
   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
   โ”‚  Researcher  โ”‚  DART/SEC filings analysis, news collection
   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜
          โ”‚ research_report
          โ–ผ
   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
   โ”‚   Analyst   โ”‚  Technical analysis: RSI, MACD, Bollinger Bands
   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜
          โ”‚ analysis_report
          โ–ผ
   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
   โ”‚ Risk Manager โ”‚  Risk assessment, position sizing
   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
          โ”‚ risk_report
          โ–ผ
   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
   โ”‚ Portfolio Manager โ”‚  Produce the final rebalancing plan
   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
          โ”‚
          โ–ผ
   [Return final report]

Defining shared state

agents/portfolio/state.pyPYTHON
from typing import TypedDict, Annotated
from langgraph.graph import add_messages
from langchain_core.messages import BaseMessage

class PortfolioState(TypedDict):
    """State shared between the agents"""
    # User input
    user_request: str
    tickers: list[str]          # stocks to analyze

    # Output of each agent
    research_report: str        # Researcher result
    analysis_report: str        # Analyst result
    risk_report: str            # Risk Manager result
    final_plan: str             # Portfolio Manager final plan

    # Message history (passed between agents)
    messages: Annotated[list[BaseMessage], add_messages]

Researcher agent

agents/portfolio/researcher.pyPYTHON
from langchain_ollama import ChatOllama
from langchain_core.messages import HumanMessage
from rag.retriever import search_kr_disclosure, search_us_filing
from tools.us_stock import get_us_stock_price
from tools.kr_stock import get_kr_stock_price
from .state import PortfolioState

_researcher_llm = ChatOllama(model="llama3.1:8b", temperature=0)
_tools = [search_kr_disclosure, search_us_filing, get_us_stock_price, get_kr_stock_price]
_researcher_chain = _researcher_llm.bind_tools(_tools)

def researcher_node(state: PortfolioState) -> dict:
    """Fundamental research based on filings and news"""
    tickers = state["tickers"]
    ticker_list = ", ".join(tickers)

    prompt = f"""Analyze the fundamentals of the following stocks: {ticker_list}

For each stock:
1. Key points of recent filings/earnings
2. Business status and major changes
3. Investment view (positive/negative factors)

Summarize concisely, stock by stock."""

    response = _researcher_chain.invoke([HumanMessage(content=prompt)])

    # Handle Tool call results
    tool_results = []
    for tc in response.tool_calls if hasattr(response, "tool_calls") else []:
        tool_fn = {t.name: t for t in _tools}.get(tc["name"])
        if tool_fn:
            result = tool_fn.invoke(tc["args"])
            tool_results.append(f"[{tc['name']}] {result}")

    research_content = response.content
    if tool_results:
        research_content += "\n\n[Retrieved data]\n" + "\n".join(tool_results)

    return {"research_report": research_content}

Analyst agent

agents/portfolio/analyst.pyPYTHON
from langchain_ollama import ChatOllama
from langchain_core.messages import HumanMessage
from tools.technical import get_rsi, get_macd, get_bollinger_bands
from tools.signal import get_composite_signal
from .state import PortfolioState

_analyst_llm = ChatOllama(model="llama3.1:8b", temperature=0)
_tools = [get_composite_signal, get_rsi, get_macd, get_bollinger_bands]
_analyst_chain = _analyst_llm.bind_tools(_tools)

def analyst_node(state: PortfolioState) -> dict:
    """Technical analysis โ€” evaluates entry timing and momentum"""
    tickers = state["tickers"]
    research = state.get("research_report", "")

    prompt = f"""Run a technical analysis of the following stocks: {', '.join(tickers)}

For each stock, check the composite signal (get_composite_signal) first,
then check RSI, MACD, and Bollinger Bands as needed.

Fundamental research summary:
{research[:500]}

Summarize the technical analysis stock by stock and include a view on entry timing."""

    response = _analyst_chain.invoke([HumanMessage(content=prompt)])

    tool_results = []
    for tc in response.tool_calls if hasattr(response, "tool_calls") else []:
        tool_fn = {t.name: t for t in _tools}.get(tc["name"])
        if tool_fn:
            result = tool_fn.invoke(tc["args"])
            tool_results.append(f"[{tc['name']}] {result}")

    analysis_content = response.content
    if tool_results:
        analysis_content += "\n\n[Indicator data]\n" + "\n".join(tool_results)

    return {"analysis_report": analysis_content}

Risk Manager agent

agents/portfolio/risk_manager.pyPYTHON
from langchain_ollama import ChatOllama
from langchain_anthropic import ChatAnthropic
from langchain_core.messages import HumanMessage
from .state import PortfolioState
import os

RISK_SYSTEM = """You are an investment risk management expert.
Review the research results and the technical analysis and assess the risk.

Assessment items:
- Maximum allowed weight per stock (based on volatility)
- Sector concentration risk
- Market condition risk (rates, FX, index trend)
- Suggested stop-loss levels"""

def risk_manager_node(state: PortfolioState) -> dict:
    """Risk assessment and position sizing โ€” uses Claude (needs complex reasoning)"""
    # Risk assessment is handled by Claude (needs careful judgment)
    llm = ChatAnthropic(
        model="claude-sonnet-4-6",
        api_key=os.getenv("ANTHROPIC_API_KEY"),
        temperature=0,
        max_tokens=2048,
    )

    prompt = f"""Assess the investment risk and propose position sizing.

Stocks under analysis: {', '.join(state['tickers'])}

=== Fundamental research ===
{state.get('research_report', '')[:1000]}

=== Technical analysis ===
{state.get('analysis_report', '')[:1000]}

Write a risk report that includes:
1. Risk grade per stock (high/medium/low)
2. Recommended portfolio weights (totaling 100%)
3. Key risk factors
4. Suggested stop-loss levels"""

    response = llm.invoke([HumanMessage(content=prompt)])
    return {"risk_report": response.content}

Portfolio Manager (final decision)

agents/portfolio/portfolio_manager.pyPYTHON
from langchain_anthropic import ChatAnthropic
from langchain_core.messages import HumanMessage
from .state import PortfolioState
import os

def portfolio_manager_node(state: PortfolioState) -> dict:
    """Combine the three agent reports into the final rebalancing plan"""
    llm = ChatAnthropic(
        model="claude-sonnet-4-6",
        api_key=os.getenv("ANTHROPIC_API_KEY"),
        temperature=0,
        max_tokens=3000,
    )

    prompt = f"""User request: {state['user_request']}

Combine the three expert reports below into a concrete portfolio rebalancing plan.

=== 1. Fundamental research ===
{state.get('research_report', '')}

=== 2. Technical analysis ===
{state.get('analysis_report', '')}

=== 3. Risk assessment ===
{state.get('risk_report', '')}

Final rebalancing plan format:
## Portfolio Rebalancing Plan

### Action per stock
| Stock | Current weight | Target weight | Action | Rationale |
|------|---------|---------|------|------|

### Execution order by priority
1. ...

### Risk management
- Common stop-loss rule: ...

### Notes
- This plan is for reference only and is not investment advice"""

    response = llm.invoke([HumanMessage(content=prompt)])
    return {"final_plan": response.content}

Compiling & running the graph

agents/portfolio/graph.pyPYTHON
from langgraph.graph import StateGraph, END
from .state import PortfolioState
from .researcher import researcher_node
from .analyst import analyst_node
from .risk_manager import risk_manager_node
from .portfolio_manager import portfolio_manager_node

def build_portfolio_graph():
    builder = StateGraph(PortfolioState)

    # Register nodes
    builder.add_node("researcher",        researcher_node)
    builder.add_node("analyst",           analyst_node)
    builder.add_node("risk_manager",      risk_manager_node)
    builder.add_node("portfolio_manager", portfolio_manager_node)

    # Edges (sequential execution)
    builder.set_entry_point("researcher")
    builder.add_edge("researcher",        "analyst")
    builder.add_edge("analyst",           "risk_manager")
    builder.add_edge("risk_manager",      "portfolio_manager")
    builder.add_edge("portfolio_manager", END)

    return builder.compile()

# Singleton
_graph = None

def get_portfolio_graph():
    global _graph
    if _graph is None:
        _graph = build_portfolio_graph()
    return _graph
PYTHON
from agents.portfolio.graph import get_portfolio_graph

graph = get_portfolio_graph()

# Portfolio rebalancing request
result = graph.invoke({
    "user_request": "Rebalance a portfolio centered on the US AI sector and Korean semiconductors",
    "tickers": ["NVDA", "AAPL", "MSFT", "005930", "000660"],
    "messages": [],
    "research_report": "",
    "analysis_report": "",
    "risk_report": "",
    "final_plan": "",
})

print("=== Final rebalancing plan ===")
print(result["final_plan"])
๐Ÿ’ก

Run time: the full pipeline takes about 3โ€“5 minutes for 5 stocks. The Researcher and Analyst use Ollama (local) while the Risk Manager and Portfolio Manager use the Claude API, balancing quality and speed.

FastAPI integration

routers/portfolio.pyPYTHON
from fastapi import APIRouter, BackgroundTasks
from pydantic import BaseModel
from agents.portfolio.graph import get_portfolio_graph
import asyncio, uuid

router = APIRouter(prefix="/portfolio", tags=["Portfolio"])

# Store for async job status
_tasks: dict[str, str] = {}

class PortfolioRequest(BaseModel):
    request: str
    tickers: list[str]

class TaskResponse(BaseModel):
    task_id: str
    status: str

@router.post("/rebalance", response_model=TaskResponse)
async def request_rebalance(req: PortfolioRequest, bg: BackgroundTasks):
    """Portfolio rebalancing request (async โ€” takes 3โ€“5 minutes)"""
    task_id = str(uuid.uuid4())[:8]
    _tasks[task_id] = "running"

    def run():
        graph = get_portfolio_graph()
        result = graph.invoke({
            "user_request": req.request,
            "tickers": req.tickers,
            "messages": [],
            "research_report": "",
            "analysis_report": "",
            "risk_report": "",
            "final_plan": "",
        })
        _tasks[task_id] = result["final_plan"]

    bg.add_task(run)
    return TaskResponse(task_id=task_id, status="running")

@router.get("/rebalance/{task_id}")
async def get_result(task_id: str):
    """Poll the rebalancing result"""
    status = _tasks.get(task_id, "not_found")
    if status == "running":
        return {"status": "running", "plan": None}
    return {"status": "done", "plan": status}

Example runs

PYTHON
from agents.portfolio.graph import get_portfolio_graph

graph = get_portfolio_graph()

# Scenario 1: AI-sector-focused portfolio
result = graph.invoke({
    "user_request": "Rebalance an AI semiconductor-focused portfolio",
    "tickers": ["NVDA", "AMD", "005930", "000660"],
    "messages": [], "research_report": "",
    "analysis_report": "", "risk_report": "", "final_plan": "",
})
print(result["final_plan"])

# Scenario 2: mixed Korea/US portfolio
result2 = graph.invoke({
    "user_request": "A defensive portfolio strategy for a weak-dollar environment",
    "tickers": ["AAPL", "MSFT", "005930", "035420", "207940"],  # Samsung Electronics, NAVER, Samsung Biologics
    "messages": [], "research_report": "",
    "analysis_report": "", "risk_report": "", "final_plan": "",
})
print(result2["final_plan"])
BASH
# Run asynchronously through the API
curl -X POST http://localhost:8000/portfolio/rebalance \
  -H "Content-Type: application/json" \
  -d '{
    "request": "Rebalance an AI-sector-focused portfolio",
    "tickers": ["NVDA", "AAPL", "005930", "000660"]
  }'

# {"task_id": "a1b2c3d4", "status": "running"}

# Fetch the result after 3โ€“5 minutes
curl http://localhost:8000/portfolio/rebalance/a1b2c3d4