AlpaTrade

August 20, 2026 · View on GitHub

PyPI License: MIT

Trading strategy backtester, paper trader, and research CLI powered by Alpaca Markets.

AlpaTrade CLI

Screenshots

AG-UI Chat — AI Research

AI Chat

AG-UI Chat — News

News

AG-UI Chat — Command Reference

Help

Web UI — Backtest Streaming

Backtest Streaming

Web UI — News Research

News Research

Web UI — Trade History

Trade History

Web UI — Command Reference

Command Reference

Install

uv tool install alpatrade

Quick Start

# Create .env with your API keys
cat > .env << 'EOF'
ALPACA_PAPER_API_KEY=your_key
ALPACA_PAPER_SECRET_KEY=your_secret
MARKET_DATA_PROVIDER=yfinance  # or alpaca
DATABASE_URL=<postgresql-connection-url>
EOF

# Launch the CLI
alpatrade

Architecture

graph TB
    subgraph Clients
        CLI["Rich CLI<br/><code>alpatrade.py</code><br/>prompt_toolkit"]
        AGUI["AG-UI Chat<br/><code>agui_app.py</code><br/>port 5003"]
        WEB["Web UI<br/><code>web_app.py</code><br/>port 5002"]
        API["REST API<br/><code>api_app.py</code><br/>port 5001"]
    end

    subgraph AI
        AGENT["pydantic-ai Agent<br/>XAI Grok-3-mini"]
        TOOLS["Agent Tools<br/>positions, charts,<br/>news, prices"]
    end

    subgraph Agents["Multi-Agent System"]
        ORCH["Orchestrator"]
        BT["Backtester"]
        PT["Paper Trader"]
        VAL["Validator"]
        REC["Reconciler"]
    end

    subgraph External
        ALPACA["Alpaca Paper API"]
        MARKET["Market Data<br/>Yahoo Finance / Alpaca"]
        DB[("PostgreSQL<br/><code>alpatrade</code> schema")]
    end

    CLI -->|commands| ORCH
    AGUI -->|WebSocket| AGENT
    AGUI -->|CLI commands| ORCH
    AGENT --> TOOLS
    WEB --> ORCH
    API --> ORCH

    ORCH --> BT
    ORCH --> PT
    ORCH --> VAL
    ORCH --> REC

    BT --> MARKET
    BT --> DB
    PT --> ALPACA
    PT --> DB
    VAL --> MARKET
    VAL --> DB
    REC --> ALPACA
    REC --> DB
    TOOLS --> ALPACA
    TOOLS --> MARKET
    TOOLS --> DB
sequenceDiagram
    participant U as User
    participant C as AG-UI Chat
    participant I as Command Interceptor
    participant A as AI Agent
    participant O as Orchestrator
    participant DB as PostgreSQL

    U->>C: "agent:backtest lookback:1m"
    C->>I: detect CLI command
    I->>O: process_command()
    O-->>DB: store results
    O-->>C: streaming logs + result
    C-->>U: backtest card + equity pill

    U->>C: "equity:592beaec"
    C->>I: detect equity: command
    I-->>DB: query trades
    I-->>C: __CHART_DATA__ marker
    C-->>U: Plotly equity curve

    U->>C: "show me AAPL analysis"
    C->>A: free-form → AI agent
    A->>A: call tools (price, news)
    A-->>C: streamed markdown
    C-->>U: formatted response

Features

  • Parameterized backtesting — grid search over dip threshold, take profit, hold days, and stop loss to find optimal strategy parameters ranked by Sharpe ratio
  • Paper trading — continuous background trading on Alpaca's paper API with startup order sync and PDT protection; the worker generates persisted post-close advisor reports
  • Market research — news, company profiles, financials, technicals, analyst ratings, and valuation comparisons
  • Alpha Research — local Growth, Value, and combined methodology views with user-scoped saved reports
  • Charts — stock price charts and backtest equity curves rendered with Plotly in the artifacts pane
  • Alpaca integration — live positions, account summary, and order management via Alpaca paper API
  • Multi-agent system — backtest, validate, paper trade, reconcile, and report via an orchestrated agent pipeline
  • Extended hours & intraday exits — pre/after-market trading (4AM-8PM ET) and 5-minute bar TP/SL timing
  • AI chat — AG-UI protocol chat with pydantic-ai agent (XAI Grok-3-mini) for free-form stock research
  • Interactive CLI — prompt_toolkit-powered terminal with dropdown auto-completion, streaming log output, and Plotly equity curve charts
  • Index-options paper tools — discover and submit paper orders for SPX, SPXW, VIX, VIXW, DJX, and XSP contracts; see docs/index_options.md

Commands

agent:backtest lookback:1m          Run parameterized backtest
agent:paper duration:7d             Paper trade in background
agent:full lookback:1m duration:1m  Full cycle (BT > Validate > PT > Validate)
agent:validate run-id:<uuid>        Validate a backtest or paper trade run
agent:reconcile window:7d           Reconcile DB vs Alpaca positions

news:TSLA                           Company news headlines
price:TSLA                          Quote and technicals
financials:AAPL                     Income and balance sheet
analysts:AAPL                       Ratings and price targets
valuation:AAPL,MSFT                 Side-by-side valuation comparison
movers                              Top market gainers and losers

alpha:growth ticker:AAPL            Growth durability and moat research
alpha:value ticker:BBY              Undervaluation and value-trap research
alpha:compare ticker:AAPL           Compact Growth and Value perspectives
alpha:runs limit:10                 Recent saved Alpha Research reports
alpha:show run-id:<uuid>            Open one saved Alpha Research report

chart:AAPL                          Stock price chart (3mo default)
chart:TSLA period:1y                Custom period chart
equity:<run_id>                     Equity curve for a backtest run

positions                           Open positions from Alpaca
account                             Account summary (value, cash, buying power)

trades                              Recent trades from DB
runs                                Recent backtest/paper runs
agent:top                           Rank strategies by Avg Annual Return
agent:top strategy:btd              Filter by slug prefix

Strategy Slugs

Each backtest variation gets a human-readable slug that encodes the strategy type, parameters, and lookback period into a compact identifier. Slugs let you compare configurations at a glance and filter results with agent:top or agent:report.

Format

{strategy}-{param1}-{param2}-...-{lookback}

Buy the Dip (btd)

TokenMeaning
btdStrategy: buy_the_dip
{n}dpDip threshold %
{n}slStop loss %
{n}tpTake profit %
{n}dHold (days)
{n}minNon-zero minimum hold (days)
{period}Lookback (e.g. 1m, 3m)

Example: btd-7dp-05sl-1tp-1d-3m = 7% dip, 0.5% stop loss, 1% take profit, 1 day hold, 3-month lookback

Momentum (mom)

TokenMeaning
momStrategy: momentum
{n}lbLookback period (days)
{n}mtMomentum threshold %
{n}dHold (days)
{n}tpTake profit %
{n}slStop loss %
{period}Lookback

Example: mom-20lb-5mt-5d-10tp-5sl-1m

VIX Fear Index (vix)

TokenMeaning
vixStrategy: vix
{n}tVIX threshold
{type}Hold type (e.g. on = overnight)

Example: vix-20t-on

Box-Wedge (bwg)

TokenMeaning
bwgStrategy: box_wedge
{n}rRisk %
{n}ctContraction threshold %

Example: bwg-2r-5ct

Environment Variables

VariableRequiredDescription
ALPACA_PAPER_API_KEYYesAlpaca paper trading API key
ALPACA_PAPER_SECRET_KEYYesAlpaca paper trading secret
MARKET_DATA_PROVIDERNoyfinance (default) or alpaca
DATABASE_URLYesPostgreSQL connection string
XAI_API_KEYNoXAI Grok for AI research commands
EODHD_API_KEYNoEOD Historical Data (intraday prices)
POSTMARK_API_KEYNoConsolidated daily-advisor email delivery
ADVISOR_ENABLEDNoWorker-owned post-close paper advisor (default true in Compose)
ADVISOR_EMAIL_ENABLEDNoSend advisor email to each user's login email (default false)
ADVISOR_CLOSE_DELAY_MINUTESNoDelay after the actual NYSE close (default 15)
PAPER_USER_ID / PAPER_ACCOUNT_IDNoBind the fixed paper service to one owned linked account for advisor attribution

Running Locally

Prerequisites

Setup

git clone https://github.com/predictivelabsai/alpatrade.git
cd alpatrade
uv sync
cp .env.example .env   # then fill in your API keys

Run the CLI

uv run python alpatrade.py

Run the AG-UI Chat (port 5003)

The AG-UI app is a chat interface built on the AG-UI protocol with FastHTML. It supports CLI commands, AI research queries, and real-time streaming via WebSocket.

uv run uvicorn agui_app:app --host 0.0.0.0 --port 5003 --reload

Open http://localhost:5003 in your browser.

Run the Web UI (port 5002)

uv run python web_app.py

Run the API Server (port 5001)

uv run uvicorn api_app:app --host 0.0.0.0 --port 5001 --reload

License

MIT