AI Hedge Fund
An educational proof-of-concept that uses AI agents embodying famous investor personas to analyze stocks, generate trading signals, and make Portfolio Tracking & Performance Metrics" href="backtesting_doc/portfolio/index.html">portfolio decisions. Built on LangGraph for orchestration with a full-stack web interface.
LangGraph Multi-Agent 19 Investor Personas Full-Stack Web App
Project Philosophy
When you first look at this codebase, the most striking design choice is the persona-based agent architecture. Rather than building a single monolithic trading algorithm, the authors created 19 independent AI agents, each embodying a famous investor's philosophy — from Warren Buffett's value investing to Cathie Wood's innovation-focused growth strategy. This isn't just a cosmetic choice: it reflects a genuine insight about investment decision-making. Different market conditions favor different philosophies, and by running all perspectives in parallel, the system creates a built-in ensemble effect.
The architecture follows a fan-out/fan-in pattern: all analyst agents run independently in parallel (using LangGraph's StateGraph), then their signals converge through a risk manager and portfolio manager. This mirrors how real hedge funds operate — analysts research independently, then an investment committee synthesizes their views.
The project prioritizes education and extensibility over production performance. Adding a new agent means copying a Python file and registering it — no framework changes needed. The system deliberately avoids premature optimization: no connection pooling, no caching layers, no retry logic. This keeps the code readable and the learning curve gentle.
The progressive enhancement pattern (CLI → Web App → v2 Pipeline) shows an organic evolution: each layer wraps the previous without replacing it, letting users engage at their preferred complexity level.
Design Decisions
| Decision | Choice Made | Alternatives | Why This Approach |
|---|---|---|---|
| Agent architecture | One function per investor persona | Class hierarchy, plugin system | Functions are simpler, self-contained, easy to add/remove |
| Orchestration | LangGraph StateGraph | Raw asyncio, Celery, custom DAG | Built-in parallel execution, state merging, message history |
| State sharing | TypedDict with merge operators | Class-based state, event bus | Lightweight, handles parallel agent writes via dict merge |
| Data source | Financial Datasets API (single source) | Multiple APIs, yfinance, Alpha Vantage | Clean single-source design, easy to mock for testing |
| LLM abstraction | Factory function get_model() | Per-agent config, direct API calls | One place to switch providers (OpenAI/Groq/Anthropic) |
| Web interface | React Flow visual editor | Form-based UI, CLI-only | Visual workflow builder is intuitive for non-developers |
| Streaming | Server-Sent Events (SSE) | WebSocket, polling | One-way streaming is sufficient and simpler than WebSocket |
System Architecture
flowchart TD
subgraph CLI["Command Line Interface"]
main_py["main.py"]
cli_input["cli/input.py"]
main_py --> cli_input
end
subgraph Agents["AI Agent Pipeline"]
start_node["start_node"]
investor_agents["19 Investor Agents\n(fan-out parallel)"]
risk_manager["risk_manager"]
portfolio_manager["portfolio_manager"]
start_node --> investor_agents
investor_agents --> risk_manager
risk_manager --> portfolio_manager
end
subgraph Core["Core Infrastructure"]
graph_state["graph/state"]
llm_models["llm/models"]
tools_api["tools/api"]
data_cache["data/cache"]
end
subgraph Backend["FastAPI Backend"]
routes["routes"]
services["services"]
database["database"]
routes --> services
services --> database
end
subgraph Frontend["React Frontend"]
react_flow["ReactFlow Editor"]
hooks["hooks"]
fe_services["services"]
react_flow --> hooks
hooks --> fe_services
end
subgraph V2["v2 Pipeline"]
signals["signals"]
portfolio_opt["portfolio optimizer"]
v2_risk["risk"]
v2_exec["execution"]
signals --> portfolio_opt
portfolio_opt --> v2_risk
v2_risk --> v2_exec
end
CLI --> Agents
Agents --> Core
Backend --> Agents
Frontend --> Backend
V2 --> Core
Modules
agents
The heart of the system: 19 independent AI agents, each embodying a famous investor's philosophy. From Warren Buffett's value investing to Nassim Taleb's tail-risk analysis, these agents analyze stocks in parallel and produce trading signals.
backtesting
Day-by-day historical simulation that runs the full agent pipeline against past market data. Tracks portfolio positions, calculates performance metrics (Sharpe, drawdown), and generates detailed reports.
Infrastructure
core
The foundational plumbing: LangGraph workflow orchestration, shared state management, LLM provider abstraction, financial data API tools, and caching. Every agent depends on this layer.
v2
Work-in-progress quantitative pipeline that adds traditional finance methods: numerical signals, portfolio optimization (mean-variance, Black-Litterman), and optimal execution modeling.
Web Application
Navigation Guide
| Level | What You'll Find | When to Use |
|---|---|---|
| 0 — Project Hub (this page) | Project philosophy, design decisions, module map, data flows | Getting started, understanding the big picture |
| 1 — Module Overview | Design rationale, algorithm spotlight, narrated walkthrough, failure analysis | Understanding a module's purpose and design choices |
| 2 — Sub-Module Deep Dive | Annotated code walkthroughs, design rationale, edge cases, implementation details | Implementing, debugging, or extending code |
| Focus Pages | Algorithm traces, alternatives comparison, complexity analysis, failure recovery | Deep understanding of a specific mechanism |
Key Data Flows
How data moves through the system's two major execution paths. The trading pipeline runs the same agent graph whether invoked from CLI or the web app.
Trading Decision Pipeline
sequenceDiagram
participant User
participant CLI
participant StateGraph
participant Agents
participant RiskMgr as Risk Manager
participant PortfolioMgr as Portfolio Manager
User->>CLI: ticker + date range
CLI->>StateGraph: create workflow
StateGraph->>Agents: fan-out to all analysts (parallel)
Note over Agents: Each agent calls Financial API + LLM
Agents->>RiskMgr: aggregate signals
RiskMgr->>PortfolioMgr: risk-adjusted signals
PortfolioMgr->>User: trading decisions (JSON)
Web App Execution (SSE)
sequenceDiagram
participant Browser
participant FastAPI
participant GraphService
participant Agents
participant ReactFlow
Browser->>FastAPI: POST /hedge-fund/run
FastAPI->>GraphService: build LangGraph from React Flow
GraphService->>Agents: execute pipeline
Note over Agents: SSE events streamed back
Agents-->>FastAPI: progress events
FastAPI-->>Browser: SSE stream (Start/Progress/Complete)
Browser->>ReactFlow: update node statuses
How CLI & WebApp Share the Core Engine
Both the command-line interface and the web application are thin entry points that compose the same underlying agent pipeline and core infrastructure. Neither owns the trading logic — they simply configure and invoke it.
flowchart LR
subgraph EntryPoints["Entry Points"]
cli["CLI (main.py)"]
webapp["WebApp (FastAPI + React)"]
end
subgraph SharedCore["Shared Core"]
pipeline["Agent Pipeline\n(19 analysts + managers)"]
infra["Core Infrastructure\n(graph, LLM, data, tools)"]
pipeline --> infra
end
cli --> pipeline
webapp --> pipeline
Key insight: The CLI and WebApp are interchangeable front-ends. The CLI callsrun_hedge_fund()directly, while the WebApp builds aStateGraphfrom the React Flow canvas and streams results via SSE. Both ultimately delegate to the same agent functions and core infrastructure, which means any new agent added to the pipeline is immediately available in both interfaces.
Directory Map
Project source tree
ai-hedge-fund/
├── src/ ← Core trading engine
│ ├── agents/ ← 19 AI investor agents + 2 managers
│ ├── backtesting/ ← Historical simulation engine
│ ├── graph/ ← LangGraph state + workflow
│ ├── data/ ← Data models + cache
│ ├── llm/ ← LLM provider abstraction
│ ├── tools/ ← Financial data API
│ ├── utils/ ← Display, progress, visualization
│ ├── cli/ ← CLI argument parsing
│ └── main.py ← Entry point
├── app/ ← Full-stack web application
│ ├── backend/ ← FastAPI backend (routes, services, DB)
│ └── frontend/ ← React + TypeScript frontend
├── v2/ ← Next-gen quantitative pipeline
├── tests/ ← Test suite
├── pyproject.toml ← Python dependencies (Poetry)
└── .env.example ← API key configuration
Build & Tech Stack
Languages
Python 3.11+, TypeScript 5.x
Frameworks
LangGraph, FastAPI, React 18, React Flow
LLM Providers
OpenAI, Groq, Anthropic (configurable via get_model())
Data & Storage
Financial Datasets API, SQLite (persistence)