Skip to main content

PrettyGoodTrader (pgt)

PyPI Python 3.11+ License: MIT CI Coverage Tests

The LLM-native trading framework. Write a prompt. Backtest it. Ship it live.

One codebase. Paper mode → backtest → live — no rewrite, no compromise.


What is PGT?

PGT is a production-grade Python framework that puts an LLM at the center of every trading decision. You define your strategy in plain language. The AI monitors markets, researches signals, debates its own positions, then routes orders through a risk engine before touching a broker.

It is not a signal library. It is not a wrapper around an exchange API. It is an autonomous trading brain you configure with prompts and deploy in minutes.

pip install pretty-good-trader
pgt init       # generates .env template
pgt doctor     # validates all connections
pgt run --dry-run
╭──────────────────────────────────────────────╮
│  🟢  PAPER MODE ACTIVE — no real orders      │
╰──────────────────────────────────────────────╯

[10:31:02] Monitor   AAPL  urgency=0.84  → RESEARCH triggered
[10:31:09] Research  found 3 bullish catalysts, 1 risk factor
[10:31:22] Decision  BUY 8 shares @ ~$188.40  confidence=0.91
[10:31:22] Risk      APPROVED  position=3.8% portfolio  drawdown=1.2%
[10:31:22] Paper     Order placed: AAPL BUY 8 @ market  ✓

Why PGT?

Framework LLM-native Backtest/live parity Live trading Plugin system Cost
PGT ✅ Any LiteLLM model ✅ Identical code path ✅ Multi-broker ✅ Built-in ~$5/day
Freqtrade ❌ OHLCV rules ✅ ✅ ✅ Low
TradingAgents ✅ Multi-agent ❌ Research only ❌ ❌ Varies
NautilusTrader ❌ Code strategies ✅ Rust-grade parity ✅ ✅ Low
ai-hedge-fund ✅ Agent personas ❌ No live ❌ ❌ Varies
Jesse ❌ Code strategies ✅ ✅ ❌ Low

Architecture

┌──────────────────────────────────────────────────────────────┐
│                        SCHEDULER                             │
│              (market-hours aware, async)                     │
└──────────────────────┬───────────────────────────────────────┘
                       │
          ┌────────────▼─────────────┐
          │  MONITOR  — Tier 1       │  cheap fast model (grok-3-mini-fast)
          │  "is there a signal?"    │  runs every cycle
          └────────────┬─────────────┘
                       │  urgency ≥ threshold
          ┌────────────▼─────────────┐
          │  RESEARCH — Tier 2       │  web search + BM25 reflection memory
          │  "what does the data     │  SearXNG + Firecrawl (self-hosted)
          │   actually say?"         │
          └────────────┬─────────────┘
                       │
          ┌────────────▼─────────────┐
          │  DEBATER  — optional     │  adversarial bull vs. bear debate
          │  "challenge the thesis"  │  fires on high-urgency signals
          └────────────┬─────────────┘
                       │
          ┌────────────▼─────────────┐
          │  DECISION — Tier 3       │  reasoning model (grok-4)
          │  "BUY / SELL / HOLD?"    │  structured JSON output
          └────────────┬─────────────┘
                       │
          ┌────────────▼─────────────┐
          │  RISK ENGINE — 7 checks  │  position limits · daily drawdown
          │                          │  duplicate orders · max notional
          └────────────┬─────────────┘
                       │  APPROVED
          ┌────────────▼─────────────────────────────┐
          │           BROKER ADAPTER                  │
          │  Alpaca · Kraken · CCXT (100+ exchanges)  │
          └───────────────────────────────────────────┘

Quickstart

1. Install

pip install pretty-good-trader          # core
pip install pretty-good-trader[alpaca]  # + Alpaca US equities
pip install pretty-good-trader[kraken]  # + Kraken crypto
pip install pretty-good-trader[ccxt]    # + 100+ exchanges

2. Configure

pgt init  # writes .env with inline cost annotations

Minimal .env for paper trading on Alpaca:

# LLM — any LiteLLM-compatible provider
XAI_API_KEY=your_xai_key
MONITOR_MODEL=xai/grok-3-mini-fast
RESEARCH_MODEL=xai/grok-3-fast
DECISION_MODEL=xai/grok-4

# Broker
ALPACA_API_KEY=your_alpaca_key
ALPACA_SECRET_KEY=your_alpaca_secret
ALPACA_BASE_URL=https://paper-api.alpaca.markets

# Safety
PAPER=true  # set to false only when ready for live

3. Verify

pgt doctor
✓  XAI_API_KEY        valid
✓  Alpaca connection   paper endpoint reachable
✓  SearXNG            http://localhost:8080 OK
✓  SQLite logger       data/pgt.db writable
✓  Risk engine         7/7 checks loaded
All systems go.

4. Run

pgt run --dry-run    # safe — no orders, full AI pipeline
pgt run              # paper mode (PAPER=true)
pgt run --confirm-live  # live mode gate (10s countdown)

Backtest

Same prompt, same pipeline, simulated data:

pgt backtest run --start 2024-01-01 --end 2024-12-31 --plot
  PGT Backtest — 2024  (grok-4 · Alpaca US equities)
  ════════════════════════════════════════════════════
  Sharpe ratio   1.84      Win rate    61.3%
  Total return  +31.2%     Max DD      -8.4%
  Avg trade      +0.9%     Trades         87

  Equity curve
  120 ┤                                          ╭──╮
  115 ┤                              ╭──╮       ╭╯  ╰─
  110 ┤                   ╭──╮      ╭╯  ╰──╮   ╭╯
  105 ┤         ╭──╮     ╭╯  ╰─────╯       ╰───╯
  100 ┤─────────╯  ╰─────╯
       Jan      Mar       Jun        Sep        Dec

Compare models in parallel:

pgt backtest run --compare --models xai/grok-4,claude/claude-opus-4-6,openai/gpt-4o
  ┌──────────────────┬────────┬──────────┬───────────┬────────┐
  │ Model            │ Sharpe │ Return   │ Win rate  │ Trades │
  ├──────────────────┼────────┼──────────┼───────────┼────────┤
  │ grok-4           │   1.84 │  +31.2%  │   61.3%   │     87 │
  │ claude-opus-4-6  │   1.61 │  +26.8%  │   58.7%   │     94 │
  │ gpt-4o           │   1.43 │  +22.1%  │   55.2%   │    102 │
  └──────────────────┴────────┴──────────┴───────────┴────────┘

Supported Brokers & Exchanges

Connector Asset classes Status
Alpaca US equities, ETFs Stable
Kraken Crypto spot · xStocks (tokenized equities) Stable
Binance Spot · Perpetuals Stable (via CCXT)
Bybit Spot · Perpetuals · Inverse Stable (via CCXT)
OKX Spot · Futures · Options Stable (via CCXT)
Hyperliquid Perpetuals Stable (via CCXT)
Gate.io Spot · Futures Stable (via CCXT)
+ 100 others — Via CCXT
PaperEngine Any of the above Stable

Plugin Ecosystem

from pgt import TradingEngine
from pgt.plugins import TelegramPlugin, PrometheusPlugin

engine = TradingEngine(
    plugins=[
        TelegramPlugin(token="...", chat_id="..."),
        PrometheusPlugin(port=9090),
    ]
)
Plugin What it does
TelegramPlugin Trade alerts, signals, daily P&L summaries — with chat_id whitelist
DiscordPlugin Same via Discord webhook
PrometheusPlugin /metrics on port 9090 — importable Grafana dashboard included
Custom Subclass PGTPlugin ABC — 5 hooks, no-op defaults

Cost-Optimized AI Pipeline

PGT runs a 3-tier model strategy proven in production:

Tier Model Runs on Typical cost
Monitor grok-3-mini-fast Every cycle ~$0.002
Research grok-3-fast On signal only ~$0.04
Decision grok-4 (reasoning) On signal only ~$0.15

At 48 cycles/day (every 30 min, market hours), base cost is < $5/day. Models are swappable per tier via env vars — use Claude, GPT-4o, or local Ollama with no code changes.


Memory & Learning

PGT learns from every trade without retraining:

  • ReflectionMemory — stores trade outcomes as text, retrieves relevant lessons via BM25Plus at research time. Zero API cost, fully offline.
  • SessionMemory — cooldown tracking and recent order deduplication, persisted across restarts via SQLite.
  • AnnotationMemory — human-in-the-loop: annotate past cycles via pgt replay --annotate, injected into future research context.
pgt reflections --search "tech earnings miss"
# → retrieves past trade notes matching the query, highlighted

CLI Reference

pgt init                      Generate .env template
pgt doctor [--fix]            Health check (auto-repair optional)
pgt run [--dry-run]           Run AI pipeline
pgt run --confirm-live        Live trading gate (10s countdown)
pgt status [--watch]          Portfolio dashboard, auto-refreshing
pgt cost [--forecast]         API spend + 30-day projection
pgt backtest run              Run backtest
pgt backtest run --compare    Multi-model parallel comparison
pgt reflections --search      BM25 search through trade memory
pgt replay <cycle_id>         Inspect past cycle in Rich panel
pgt replay <cycle_id> --annotate  Add human annotation
pgt cycles [--cycle-id <id>]  Browse cycle log
pgt logs                      Tail SQLite log
pgt docker up/down            Manage self-hosted service stack

Self-Hosted Stack

Full infrastructure via Docker Compose:

docker compose up -d

Includes: SearXNG (private web search) · Firecrawl (page scraping) · PGT engine · Prometheus · Grafana (pre-configured dashboard) · Redis (rate limit cache)


Links

Metadata

Release files for pretty-good-trader 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pretty-good-trader 0.1.0
File Size Uploaded Provenance Actions
pretty_good_trader-0.1.0.tar.gz 109.9 kB Without provenance Details for pretty_good_trader-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pretty-good-trader 0.1.0
File Interpreter ABI Platform Actions
pretty_good_trader-0.1.0-py3-none-any.whl Python 3 none any Details for pretty_good_trader-0.1.0-py3-none-any.whl

Total release size: 175.6 kB

Release files / pretty_good_trader-0.1.0.tar.gz

Download URL pretty_good_trader-0.1.0.tar.gz
Size 109.9 kB
Tags Source
SHA-256 checksum
How to use checksums
ef8f533cbccf47a2f745df5cc2cc756dedc6d01fc910f975ab39576a24a643c2
BLAKE2b-256 checksum
How to use checksums
ef9ddd53e1521b54918d7f951335de59411faf8102e95609efbfd714d942d00a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.12

Release files / pretty_good_trader-0.1.0-py3-none-any.whl

Download URL pretty_good_trader-0.1.0-py3-none-any.whl
Size 65.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
7a79ac3d094f48358cd4cb995e16c4013d251c6f220c3c34e9c549eab813caec
BLAKE2b-256 checksum
How to use checksums
8d34630fe6e8b072b608c598ace8c409fdc7b0f3a9f352f96c4ecf5be2b4a543
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/6.2.0 CPython/3.13.12

Security for pretty-good-trader 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page