Metadata-Version: 2.4
Name: pretty-good-trader
Version: 0.1.0
Summary: The LLM-native trading framework. Write a prompt. Backtest it. Ship it live.
Project-URL: Homepage, https://github.com/fullya99/PrettyGoodTrader
Project-URL: Source, https://github.com/fullya99/PrettyGoodTrader
Project-URL: Documentation, https://github.com/fullya99/PrettyGoodTrader#readme
Project-URL: Bug Tracker, https://github.com/fullya99/PrettyGoodTrader/issues
Author: PrettyGoodTrader Contributors
License: MIT
Keywords: ai,algorithmic,alpaca,backtesting,kraken,llm,trading
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Financial and Insurance Industry
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Office/Business :: Financial :: Investment
Requires-Python: >=3.11
Requires-Dist: duckdb>=0.10
Requires-Dist: httpx>=0.27
Requires-Dist: litellm<2.0,>=1.40
Requires-Dist: pandas>=2.0
Requires-Dist: plotext>=5.0
Requires-Dist: psutil>=5.9
Requires-Dist: pydantic-settings>=2.0
Requires-Dist: pydantic>=2.0
Requires-Dist: python-dotenv>=1.0
Requires-Dist: rank-bm25>=0.2.2
Requires-Dist: rich>=13.0
Requires-Dist: stockstats>=0.6.5
Requires-Dist: typer>=0.12
Requires-Dist: yfinance>=0.2.63
Provides-Extra: alpaca
Requires-Dist: alpaca-py>=0.43.0; extra == 'alpaca'
Provides-Extra: ccxt
Requires-Dist: ccxt>=4.0; extra == 'ccxt'
Provides-Extra: dev
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
Requires-Dist: pytest-cov>=5.0; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.4; extra == 'dev'
Provides-Extra: docs
Requires-Dist: mkdocs-material>=9.5; extra == 'docs'
Provides-Extra: kraken
Requires-Dist: python-kraken-sdk>=2.3.0; extra == 'kraken'
Provides-Extra: prometheus
Requires-Dist: prometheus-client>=0.20; extra == 'prometheus'
Provides-Extra: telegram
Requires-Dist: python-telegram-bot>=21.0; extra == 'telegram'
Description-Content-Type: text/markdown

# PrettyGoodTrader (pgt)

[![PyPI](https://img.shields.io/pypi/v/pretty-good-trader?color=blueviolet)](https://pypi.org/project/pretty-good-trader/)
[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![CI](https://github.com/fullya99/PrettyGoodTrader/actions/workflows/ci.yml/badge.svg)](https://github.com/fullya99/PrettyGoodTrader/actions/workflows/ci.yml)
[![Coverage](https://img.shields.io/badge/coverage-83%25-brightgreen.svg)](https://github.com/fullya99/PrettyGoodTrader)
[![Tests](https://img.shields.io/badge/tests-253%20passing-brightgreen.svg)](https://github.com/fullya99/PrettyGoodTrader)

**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.

```bash
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

```bash
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

```bash
pgt init  # writes .env with inline cost annotations
```

Minimal `.env` for paper trading on Alpaca:

```env
# 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

```bash
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

```bash
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:

```bash
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:

```bash
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

```python
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.

```bash
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:

```bash
docker compose up -d
```

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

---

## Links

- [Documentation](docs/) — quickstart, architecture, cookbook, adapter guides
- [Contributing](CONTRIBUTING.md) — adapter guide, prompt change rules, PR checklist
- [Changelog](CHANGELOG.md)
- [TODOS](TODOS.md) — deferred work, open for community contributions
- [License](LICENSE) — MIT
