AI Hedge Fund

repository·main·Indexed 13 days ago

https://github.com/virattt/ai-hedge-fund

A proof-of-concept tool for educational and research purposes to explore AI-driven trading. It allows users to build, backtest, and simulate fund mandates using LLM-powered alpha models and financial datasets via a CLI tool (aihf) and an interactive TUI.

Tokens
7.2K
Snippets
23
Records
38
Agent score
98%

What's inside AI Hedge Fund

  1. How the trading cycle works

    main

    The system operates via a single pipeline called run_cycle. This pipeline is identical across all modes (Backtest, Paper, Live), ensuring that research and production code do not diverge. A single cycle follows this sequence:

    1. Point-in-time data: Fetches only data that was publicly available at the specific timestamp (prevents lookahead bias).
    2. Analysts emit Signals: Analysts (LLM or Quant) provide a conviction score [-1, +1] and a thesis.
    3. Portfolio construction: Blends the various analyst views into target weights.
    4. Risk model: Applies hard caps and vetoes to ensure positions stay within defined limits.
    5. Execution: Translates target weights vs. current broker reality into specific orders.
    6. Ledger: Persists the decision, the written thesis, the fills, and the updated Net Asset Value (NAV).
  2. Understand the Fund Engine Pipeline

    main

    The core of the project is the run_cycle pipeline. A single cycle follows this sequence of operations:

    1. Data: Fetching market and fundamental data via the DataClient protocol.
    2. Analysts: Running AlphaModel implementations to generate signals.
    3. Portfolio: Constructing target weights based on model views (often conviction-weighted).
    4. Risk: Applying hard caps (fund-level and pod-level limits).
    5. Execution: Sending orders through a pluggable Broker protocol.
    6. Ledger: Writing a CycleRecord receipt containing positions, cash, NAV, and every decision/thesis.
  3. Core design principles and constraints

    main

    When building or extending the system, adhere to these core principles:

    • Point-in-time honesty: Never use data that was not public at the time of the simulation (no lookahead bias).
    • The backtest is the live system: Use the same pipeline for both research and production.
    • LLM isolation: LLMs are used for reasoning and narration (forming views/theses) only. They never touch the trade directly. Deterministic code handles position sizing, order placement, and risk enforcement.
    • Gated self-improvement: Any new strategy or model must pass a validation gate (e.g., overfitting checks like CPCV/PBO) before being promoted to the live fund.
    • Paper before real: Live trading is disabled by default and requires explicit opt-in.
  4. Understand the AI Hedge Fund architecture

    main

    The project is designed as a hierarchical, pluggable system that mimics a real hedge fund structure. It consists of three nested layers that can be customized or extended:

    1. FUND: The top level, consisting of an Allocator (CIO) that distributes capital across multiple Strategies.
    2. STRATEGY: A 'pod' that bundles a set of Analysts with a specific Portfolio Policy and a dedicated capital slice.
    3. ANALYST: The base unit that produces a Signal. Analysts come in two types:
      • LLM Investor Agents: Stylized approximations of famous investors (e.g., Warren Buffett) that provide a conviction in [-1, +1] and a written thesis.
      • Quant Models: Pure mathematical models (e.g., momentum, regime detection) that output the same conviction and thesis format.

    This modularity allows you to mix and match different models at every layer of the stack.

  5. Configure API keys for AI Hedge Fund

    main

    The application requires two types of API keys to function:

    1. Financial Datasets API key: Required for accessing prices, fundamentals, and earnings data.
    2. LLM API key: Required for the LLM-powered alpha models. Supported providers include Anthropic, OpenAI, DeepSeek, Google, xAI, and Kimi.

    Configuration Methods:

    • Automatic: The app will prompt you for keys the first time they are needed and save them to ~/.hedge-fund/.env.
    • Environment Variables: Any keys exported in your current shell session will take precedence over the keys saved in the .env file.
  6. Run Non-interactive Fund Cycles and Backtests

    main

    You can execute specific fund operations using a mandate file (the configuration defining strategies, staff, risk, capital, and cadence) and specifying tickers via the --tickers flag.

    Run a single fund cycle: This prints the full cycle record to stdout as JSON and a human-readable summary to stderr.

    aihf <path_to_mandate_file> --tickers <TICKER_LIST>

    Backtest a mandate over history: This runs the mandate over historical data according to its defined rebalance cadence.

    aihf <path_to_mandate_file> --tickers <TICKER_LIST> --backtest

    Note: Mandate files do not contain tickers; tickers must be provided at runtime via the --tickers flag.

    aihf ~/.hedge-fund/mandates/example.yaml --tickers AAPL,MSFT
    
    # To backtest:
    aihf ~/.hedge-fund/mandates/example.yaml --tickers AAPL,MSFT --backtest
  7. Set up a development environment

    main

    To contribute to the project or run it in a development context, use poetry to manage dependencies and run the application or tests.

    # Clone and enter the repository
    git clone https://github.com/virattt/ai-hedge-fund.git
    cd ai-hedge-fund
    
    # Install dependencies
    poetry install
    
    # Run the application
    poetry run aihf
    
    # Run tests
    poetry run pytest hedge_fund
    git clone https://github.com/virattt/ai-hedge-fund.git
    cd ai-hedge-fund
    poetry install
    poetry run aihf
    poetry run pytest hedge_fund
  8. Implement an Alpha Model (Analyst)

    main

    The primary way to contribute to the AI Hedge Fund is by implementing the AlphaModel interface. An analyst is a component that plugs directly into the engine to provide market signals.

    To implement a new model:

    1. Implement the AlphaModel interface.
    2. Ensure the predict(...) method returns a Signal object.
    3. Add a corresponding test to verify the model's behavior.

    There are two main types of models you can implement:

    • Quantitative models: Pure mathematical or data-driven models (e.g., Momentum, Mean Reversion, Value/Quality factors).
    • LLM investor agents: Agents that reason over fundamentals using a specific investor persona (e.g., Warren Buffett, Charlie Munger) to emit a conviction and a thesis.
    # Conceptual implementation pattern
    class MyNewModel(AlphaModel):
        def predict(self, ...) -> Signal:
            # logic to return a Signal
            pass
  9. Use the Interactive Terminal App

    main

    Running the aihf command without any arguments launches the interactive terminal application. In this mode, you can:

    • Build a new fund by selecting stocks, strategies, and rebalance cadence.
    • Backtest a previously saved fund and view its equity curve against a benchmark.

    Funds you create are saved as mandate files in ~/.hedge-fund/mandates/.

    aihf
  10. Switch between Backtest, Paper, and Live modes

    main

    The system uses a single engine (run_cycle) but changes behavior based on the clock and the broker used. You can choose from three modes:

    ModeClockBrokerContext
    BACKTESTHistoricalSimulatedTesting strategies on past data with fake money.
    PAPERLivePaperTesting on real-time data with fake money.
    LIVELiveRealTrading real money in real-time (opt-in only).

    Note: Because the code path is identical, what you validate in a backtest is exactly what will execute in live trading.

  11. Install the AI Hedge Fund CLI

    main

    You can install the aihf tool using pipx, uv, or pip. Once installed, the aihf command is available globally in your terminal.

    To install via pipx:

    pipx install aihf

    Alternatively, use uv or pip:

    uv tool install aihf
    # or
    pip install aihf
  12. Extend the project with new Data Sources

    main

    The data layer uses a pluggable DataClient protocol. While core market, fundamental, and earnings data are provided (e.g., via Financial Datasets), you can extend the engine by adding connectors for alternative data sources.

    Examples of alternative data to implement include:

    • Satellite imagery
    • Web & social-media search
    • App-download trends
    • Shipping data