Difficulty: βββββ (Intermediate) | Duration: 20-25 Minutes | Takeaway: Master the construction of a multi-agent quantitative trading system and understand the full workflow of AI investment analysis.
Target Audience
This article is intended for developers with 1-3 years of experience. You don't need to be a quantitative trading expert; you only need:
- Basic knowledge of Python
- Interest in AI applications and quantitative trading
- A desire to learn how to use AI to simulate the investment logic of legendary investors
Core Dependencies and Environment
Before we begin, let's prepare the development environment. You will need to install the following software:
| Dependency | Version Requirement | Description |
|---|---|---|
| Python | >= 3.11 | Foundation for running the project |
| Poetry | Latest version | Python package management tool |
| API Key | At least one | OpenAI / Anthropic / Groq / DeepSeek |
TIP
Poetry is a modern package management tool for Python. You can manage dependencies and environments with a single command:
# Install Poetry
curl -sSL https://install.python-poetry.org | python3 -
Note: This project is for educational and demonstration purposes only and will not perform actual trades. It uses AI to simulate investors' decision-making processes to help you understand different investment philosophies.
Project Structure
After cloning, you will find the project structure is very clear:
ai-hedge-fund/
βββ src/
β βββ agents/ # Various investor agents (Buffett, Munger, Peter Lynch, etc.)
β βββ graph/ # LangGraph workflow definitions
β βββ llm/ # Large Language Model configurations
β βββ tools/ # Utility functions (fetching financial data, technical indicators, etc.)
β βββ data/ # Data processing
β βββ cli/ # Command-line entry points
β βββ backtesting/ # Backtesting modules
β βββ main.py # Main program entry point
β βββ backtester.py # Backtester program
βββ app/ # Web application (optional)
βββ tests/ # Testing
βββ docker/ # Docker configurations
βββ pyproject.toml # Project configuration
βββ README.md # Project documentation
Step-by-Step Tutorial
Next, we will complete the entire configuration and operation process step-by-step.
Step 1: Install Poetry
If you haven't installed Poetry yet, install it first:
# Linux / macOS
curl -sSL https://install.python-poetry.org | python3 -
# Windows (PowerShell)
(Invoke-WebRequest -Uri https://install.python-poetry.org -UseBasicParsing).Content | python -
# Verify installation
poetry --version
TIP
If you are on macOS, you can also install it via Homebrew: brew install poetry
Step 2: Clone Project and Install Dependencies
Pull the project locally and install the dependencies:
# Clone the repository
git clone https://github.com/virattt/ai-hedge-fund.git
cd ai-hedge-fund
# Install dependencies (Poetry will automatically create a virtual environment)
poetry install
This step may take a few minutes as Poetry installs all required packages, including:
- langchain / langgraph: LLM Agent framework
- pandas / numpy: Data processing
- fastapi: Web services
- matplotlib: Plotting
Step 3: Configure API Keys
The project requires calling large models to make investment decisions. You need to configure at least one LLM API Key:
# Copy the example configuration file
cp .env.example .env
Then edit the .env file and add your API Key:
# Choose one API Key you have
OPENAI_API_KEY=your-openai-api-key
# OR
ANTHROPIC_API_KEY=your-anthropic-api-key
# OR
GROQ_API_KEY=your-groq-api-key
# OR
DEEPSEEK_API_KEY=your-deepseek-api-key
# Financial Data (Optional, AAPL/GOOGL/MSFT/NVDA/TSLA are free)
FINANCIAL_DATASETS_API_KEY=your-financial-datasets-api-key
WARNING
The financial data API Key is optional. If you only analyze AAPL, GOOGL, MSFT, NVDA, and TSLA, you can leave it blank. Other stocks require an API Key.
Step 4: Run CLI Version (Command Line Interface)
Now we run the basic command-line version:
poetry run python src/main.py --ticker AAPL,MSFT,NVDA
After running, you will see the system start analyzing these three stocks. The output will look something like this:
π¦ AI Hedge Fund Analysis
==========================
Ticker: AAPL, MSFT, NVDA
Date: 2026-03-07
π€ Warren Buffett Agent:
Looking at Apple through the lens of a wonderful business at fair price...
[Analysis content...]
π€ Charlie Munger Agent:
[Analysis content...]
π Portfolio Manager:
Synthesizing opinions from all Agents, final recommendation: BUY AAPL, HOLD MSFT, SELL NVDA
TIP
The first run will be slower because it needs to initialize the LangGraph workflow and connect to the LLM. Subsequent runs will be much faster.
Step 5: Understanding the Output
The system calls 18 legendary investor Agents to analyze each stock:
- Warren Buffett: Looking for a "Wonderful Business at Fair Price"
- Charlie Munger: Buys only excellent companies
- Michael Burry: Looks for deep value opportunities
- Cathie Wood: Looks for innovation and disruptive opportunities
- Peter Lynch: Searches for "ten-baggers"
- Phil Fisher: Deep research specialist
- ...and 12 others
Additionally, there are 4 specialized analysis Agents:
- Valuation Agent: Calculates intrinsic value
- Sentiment Agent: Analyzes market sentiment
- Fundamentals Agent: Analyzes fundamental data
- Technicals Agent: Analyzes technical indicators
Finally, the Risk Manager and Portfolio Manager provide the ultimate decision.
Step 6: Run Backtesting
If you want to see how this strategy performed in the past, you can run a backtest:
poetry run python src/backtester.py --ticker AAPL,MSFT,NVDA
Add a date range to analyze a specific period:
poetry run python src/backtester.py --ticker AAPL,MSFT,NVDA --start-date 2024-01-01 --end-date 2024-12-31
Backtest results will show the performance of each stock and the overall portfolio return.
Step 7: Launch Web UI (Optional)
If you prefer a graphical interface, you can start the Web application:
cd app
poetry install
poetry run fastapi run src/main.py
Then open your browser and visit http://localhost:8000.
The Web UI provides a friendlier interface where you can:
- Search for and select stocks
- View detailed analysis reports
- Adjust parameters and rerun
- View historical analysis records
Step 8: Use Local Models with Ollama (Advanced)
If you don't have a cloud API Key or want to save money, you can use your own local model:
# Start Ollama first
ollama serve
# Then run AI Hedge Fund
poetry run python src/main.py --ticker AAPL,MSFT,NVDA --ollama
TIP
It is recommended to run models like qwen2.5 or llama3.1 with Ollama; they perform well and are free.
Troubleshooting
Problem 1: Poetry Installation Failed
Symptom: Running poetry --version results in a command not found error.
Solution:
- Check Python version:
python3 --version(requires 3.11+) - Confirm if the installation script executed successfully
- Manually add to PATH:
export PATH="$HOME/.local/bin:$PATH" - Or use Homebrew:
brew install poetry
Problem 2: API Key Configuration Error
Symptom: The program prompts authentication failure or Invalid API Key.
Solution:
- Check if the
.envfile is in the project root directory - Confirm the API Key is spelled correctly with no extra spaces
- Confirm if the API Key has remaining credits
- Check the specific error message in the program output
Problem 3: Dependency Installation Stuck
Symptom: Running poetry install shows no response for a long time.
Solution:
- Add a local mirror source (e.g., for users in China):
poetry config mirror.https://pypi.org https://pypi.tuna.tsinghua.edu.cn - Or install key dependencies first via pip:
pip install langchain langgraph pandas
Problem 4: Model Call Timeout
Symptom: The program hangs for a long time and then reports a timeout error.
Solution:
- Check your network connection
- Switch to a faster model (like Groq)
- Increase timeout duration (requires code modification)
- Use a local Ollama model
Problem 5: Web UI Failed to Start
Symptom: Running FastAPI prompts that the port is occupied or dependencies are missing.
Solution:
- Check if the port is occupied:
lsof -i :8000 - Install Web dependencies:
cd app && poetry install - View specific errors:
poetry run fastapi dev src/main.py
Problem 6: Data Acquisition Failed
Symptom: The program prompts that stock data cannot be retrieved.
Solution:
- Confirm you are using free stocks only (AAPL/GOOGL/MSFT/NVDA/TSLA)
- Apply for a Financial Datasets API Key
- Check if your network can access financialdatasets.com
Core Mechanism Analysis
You might wonder how this system actually works. The core lies in the multi-agent collaboration framework built with LangGraph.
Agent Architecture
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β Portfolio Manager β
β (Final Decision & Order Generation) β
βββββββββββββββββββββββββββββββ¬ββββββββββββββββββββββββββββββββββββ
β
βββββββββββββββββββββββΌββββββββββββββββββββββ
β β β
βΌ βΌ βΌ
βββββββββββββββββ βββββββββββββββββ βββββββββββββββββ
β Valuation β β Sentiment β β Fundamentals β
β Agent β β Agent β β Agent β
β (Valuation) β β (Sentiment) β β (Fundamentals)β
βββββββββββββββββ βββββββββββββββββ βββββββββββββββββ
β β β
βββββββββββββββββββββββΌββββββββββββββββββββββ
β
βββββββββββββββββββββββ΄ββββββββββββββββββββββ
β β
βΌ βΌ
βββββββββββββββββββββ βββββββββββββββββββββ
β Risk Manager β β 18 Investor β
β (Risk Management) β β Agents β
β β β (Buffett/Munger) β
βββββββββββββββββββββ βββββββββββββββββββββ
Decision Process
- Input: User specifies the stock ticker to analyze (e.g., AAPL)
- Data Collection: Fetch financial data, technical indicators, and news sentiment
- Parallel Analysis: 18 investor Agents analyze simultaneously, each giving their viewpoint
- Expert Analysis: 4 analysis Agents provide valuation, sentiment, fundamental, and technical opinions
- Risk Assessment: Risk Manager calculates risk metrics and sets position limits
- Final Decision: Portfolio Manager synthesizes all opinions to generate a Buy/Sell/Hold recommendation
WARNING
This system is for educational demonstration only and will not execute actual trades. Its decisions are for reference only and should never be taken as real investment advice!
Advanced Directions
Once you have mastered the basic usage, you can explore these advanced features:
1. Add New Investor Agents
In the src/agents/ directory, follow the existing templates to add new investor Agents. You could create a "Silicon Valley Investor" or any other persona to let the AI learn their investment style.
2. Customize Analysis Strategies
Modify the workflow definitions under src/graph/ to adjust the weights and decision logic of various Agents. For example, if you value fundamentals more, increase that Agent's weight.
3. Connect to Real Trading APIs
WARNING
This is an advanced feature that requires a full understanding of trading API risks.
The project has reserved trading interfaces. You can modify src/tools/ to interface with brokerage APIs for true automated trading. Please proceed with extreme caution!
4. Docker Deployment
The project provides a Dockerfile for deployment:
docker build -t ai-hedge-fund .
docker run -it --env-file .env ai-hedge-fund python src/main.py --ticker AAPL