AI Hedge Fund

Multi-Agent AI-Powered Trading System

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

5
Modules
19
AI Agents
235
Source Files
Python + TS
Languages

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

DecisionChoice MadeAlternativesWhy This Approach
Agent architectureOne function per investor personaClass hierarchy, plugin systemFunctions are simpler, self-contained, easy to add/remove
OrchestrationLangGraph StateGraphRaw asyncio, Celery, custom DAGBuilt-in parallel execution, state merging, message history
State sharingTypedDict with merge operatorsClass-based state, event busLightweight, handles parallel agent writes via dict merge
Data sourceFinancial Datasets API (single source)Multiple APIs, yfinance, Alpha VantageClean single-source design, easy to mock for testing
LLM abstractionFactory function get_model()Per-agent config, direct API callsOne place to switch providers (OpenAI/Groq/Anthropic)
Web interfaceReact Flow visual editorForm-based UI, CLI-onlyVisual workflow builder is intuitive for non-developers
StreamingServer-Sent Events (SSE)WebSocket, pollingOne-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

Core Trading Engine

agents

19 AI Investor Persona 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.

22 files~7k LOC19 agents

backtesting

Historical Backtesting Engine

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.

11 files~3.5k LOC

Infrastructure

core

Graph, Data & LLM Infrastructure

The foundational plumbing: LangGraph workflow orchestration, shared state management, LLM provider abstraction, financial data API tools, and caching. Every agent depends on this layer.

20 files~2.7k LOC

v2

Next-Gen Quantitative Pipeline

Work-in-progress quantitative pipeline that adds traditional finance methods: numerical signals, portfolio optimization (mean-variance, Black-Litterman), and optimal execution modeling.

20 files~870 LOC

Web Application

webapp

Full-Stack Web Application

Visual workflow builder for composing agent pipelines via drag-and-drop. FastAPI backend with SSE streaming, React Flow frontend with real-time execution status, and SQLite persistence.

142 files~18.3k LOC
LevelWhat You'll FindWhen to Use
0 — Project Hub (this page)Project philosophy, design decisions, module map, data flowsGetting started, understanding the big picture
1 — Module OverviewDesign rationale, algorithm spotlight, narrated walkthrough, failure analysisUnderstanding a module's purpose and design choices
2 — Sub-Module Deep DiveAnnotated code walkthroughs, design rationale, edge cases, implementation detailsImplementing, debugging, or extending code
Focus PagesAlgorithm traces, alternatives comparison, complexity analysis, failure recoveryDeep 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 calls run_hedge_fund() directly, while the WebApp builds a StateGraph from 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)