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.
There are reasons portfolio management is hard to handle with a single agent.
| Problem | Single-agent limit | Multi-agent solution |
|---|---|---|
| Context length | Context overflows when analyzing 10 stocks | Independent context per agent |
| Specialization | Not good at filings analysis and technical analysis at once | Roles split per agent |
| Parallelism | Sequential processing only | Research several stocks in parallel |
| Checks & balances | Hard to catch its own mistakes | Risk 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.
[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]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]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}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}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}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}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 _graphfrom 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.
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}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"])# 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