Skip to content
rushilpunuPublic

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

GPTtrade

Event-driven algorithmic trading system that turns market data into decisions and orders using behavioral signals, configurable risk controls, and pluggable policies (rules-based or LLM-driven). The system can run in a single cycle for ad‑hoc evaluation or as a scheduler loop for continuous operation.

Features

  • Behavioral signals from price/volume history
  • News & sentiment analysis with lexicon-based scoring
  • Calendar-aware trading with earnings/Fed/holiday blackouts
  • Risk gate with position sizing and exposure limits
  • Paper and live trading support (Alpaca + simulator broker)
  • Policy layer: TradingAgents engine, rules-based, or LLM-backed decisions
  • Order execution with optional limit orders and cooldowns
  • Decision + order logging to a local SQLite database

Project Structure

.
├── README.md
├── config.yaml
├── .env.example
├── pyproject.toml
├── src
│   ├── main.py
│   ├── scheduler.py
│   ├── agent
│   │   └── policy.py
│   ├── data
│   │   ├── market_data.py
│   │   ├── news_data.py          # News fetching (Alpha Vantage + RSS)
│   │   └── calendar_data.py      # Earnings/Fed/holiday calendar
│   ├── execution
│   │   ├── alpaca_broker.py
│   │   ├── broker_interface.py
│   │   └── simulator_broker.py
│   ├── features
│   │   ├── behavioral_features.py
│   │   └── sentiment.py          # Lexicon-based sentiment scoring
│   ├── observability
│   │   └── logging.py
│   ├── risk
│   │   ├── position_sizing.py
│   │   └── risk_gate.py
│   └── storage
│       ├── db.py
│       └── models.py
├── tests
│   ├── test_position_sizing.py
│   ├── test_risk_gate.py
│   ├── test_sentiment.py         # Sentiment analysis tests
│   └── test_calendar.py          # Calendar blackout tests
├── tools
│   ├── smoke.py
│   └── audit.py                  # System wiring audit
└── TradingAgents
    └── ...

Prerequisites

  • Python 3.11+
  • uv or pip

Setup

git clone <your-repo-url>
cd GPTtrade

Install dependencies:

uv sync
# or
pip install -e .

Copy environment template:

cp .env.example .env

Configuration Guide (config.yaml)

Key knobs you can tune:

  • trading_mode: paper or live (execution mode selector).
  • ENABLE_LIVE_TRADING: hard safety switch for live orders.
  • symbols: list of tickers to trade.
  • decision_interval_minutes: cadence for scheduler loop.
  • lookback_days: (optional) OHLCV history window used for features.
  • max_position_pct: max equity per position (fraction).
  • max_gross_exposure_pct: cap on total exposure (fraction).
  • max_daily_loss_pct: daily loss stop (fraction).
  • max_trades_per_day: throttle for order count.
  • cooldown_minutes: minimum wait between trades per symbol.
  • cost_buffer: slippage/fee buffer used in sizing/validation.
  • policy_type: tradingagents, rules, or llm.
  • llm.model, llm.endpoint, llm.temperature: LLM policy settings.
  • news_enabled: include news features when enabled.
  • use_limit_orders: toggle market vs limit orders.
  • limit_order_offset: percent offset from mid/last for limit orders.
  • stale_order_timeout_seconds: cancel orders past this age.
  • enable_shorts, enable_leverage: additional risk toggles.
  • logging.*: log level, outputs, rotation settings.

Environment variables in .env can override sensitive items (API keys, live-trading token, etc.).

Run

Single cycle:

python -m main --once

Scheduler loop:

python -m main

Dry run (no orders submitted):

python -m main --dry-run

Testing & Verification

Run All Tests

cd src && PYTHONPATH=. pytest ../tests -v

Test Categories

Test File Description
test_integration.py Full cycle integration with rules/LLM policies, SQLite persistence, correlation IDs
test_scheduler_autonomy.py Scheduler iteration control, graceful shutdown, dry-run mode
test_no_prompting.py Enforces no input() calls, static source scan for interactive patterns
test_offline.py Runs with network blocked, verifies LLM fallback works offline
test_risk_gate.py Risk constraint unit tests (PDT, position limits, kill switch)
test_position_sizing.py Signal-based sizing, short blocking, max position constraints

Smoke Test

Quick verification that the system runs end-to-end in simulator mode:

cd src && python ../tools/smoke.py
# Verbose mode:
cd src && python ../tools/smoke.py --verbose

Continuous Integration

GitHub Actions workflow runs on push/PR:

  • Installs dependencies
  • Runs full pytest suite
  • Runs smoke test

Test Guarantees

  • Autonomous: No human input required - tests fail if input() is called
  • Offline: Simulator tests work without network/API keys
  • Deterministic: Seeded random generators for reproducible results
  • Isolated: Temporary SQLite databases per test

Safety Warnings (Live Trading)

  • Live trading is blocked unless ENABLE_LIVE_TRADING=true and a valid LIVE_TRADING_CONFIRMATION_TOKEN is provided in .env.
  • Use paper trading by default and verify positions, limits, and order behavior before enabling live trading.
  • Review max_daily_loss_pct, exposure limits, and max_trades_per_day before going live.

Architecture

Scheduler/CLI
    │
    ▼
TradingSystem (main loop)
    │
    ├─ MarketData (Alpaca/Yahoo)
    ├─ BehavioralFeatureCalculator
    ├─ Policy (Rules or LLM)
    ├─ RiskGate + PositionSizer
    ├─ Broker (Simulator or Alpaca)
    └─ Storage (SQLite)

At each cycle, the system pulls market data, computes behavioral features, makes policy decisions, applies risk gates and sizing, then submits or simulates orders and persists decisions and executions.

LLM Provider Selection

The system supports two LLM providers for the AI-based trading policy:

OpenAI (default)

# config.yaml
llm_provider: 'openai'
llm_model: 'gpt-4o-mini'

Set OPENAI_API_KEY in your environment.

Gemini (Google)

# config.yaml  
llm_provider: 'gemini'
llm_model: 'gemini-2.0-flash'

Set GEMINI_API_KEY in your environment.

Note: If no API key is set, the system falls back to the rules-based policy.

TradingAgents Integration (Multi-Agent Decision Engine)

TradingAgents is a sophisticated multi-agent framework that can be used as the primary decision engine. When enabled, it orchestrates multiple specialized agents (market analysts, researchers, risk managers) in a debate-style architecture to reach trading decisions.

Setup

  1. TradingAgents is included in the repository at ./TradingAgents/. No additional cloning required.

  2. Install TradingAgents dependencies:

pip install -r TradingAgents/requirements.txt
  1. Configure in config.yaml:
policy_type: 'tradingagents'
llm_provider: 'openai'  # or 'google' or 'anthropic'
llm_model: 'gpt-4o-mini'
tradingagents_max_debate_rounds: 1  # optional

How It Works

  • Market Analyst: Analyzes price data and technical indicators
  • News Analyst: Processes news and sentiment
  • Fundamentals Analyst: Reviews financial statements
  • Social Media Analyst: Monitors social sentiment
  • Bull/Bear Researchers: Debate investment thesis
  • Risk Manager: Evaluates risk/reward
  • Trader: Makes final decision after debate

Fail-Fast Behavior

TradingAgents is a REQUIRED dependency when policy_type: tradingagents. The system will:

  • Verify TradingAgents is available at startup
  • Refuse to start if TradingAgents cannot be loaded
  • No silent fallback to rules-based policy

Verification

Run the inspection tool to verify your TradingAgents setup:

python tools/inspect_tradingagents.py

Troubleshooting

Issue Solution
TradingAgentsNotFoundError Ensure TradingAgents folder exists in project root
Import errors Run pip install -r TradingAgents/requirements.txt
LLM errors Verify OPENAI_API_KEY or GEMINI_API_KEY is set

Web Monitoring Dashboard

A local FastAPI server provides read-only monitoring endpoints.

Enabling the Web Server

# config.yaml
enable_web: true
web_host: '127.0.0.1'
web_port: 8000

Available Endpoints

  • GET /health - Health check
  • GET /status - Current system status
  • GET /decisions - Recent trading decisions
  • GET /orders - Recent orders
  • GET /positions - Current positions
  • GET /logs/recent - Recent log entries

Testing the API

curl http://127.0.0.1:8000/health
curl http://127.0.0.1:8000/status

Discord Notifications

Get real-time alerts via Discord webhook.

Setup

  1. Create a Discord webhook in your server
  2. Configure in config.yaml or environment:
enable_discord: true
discord_webhook_url: 'https://discord.com/api/webhooks/...'

Or set DISCORD_WEBHOOK_URL env var.

Notification Events

  • Trade signals submitted
  • Orders filled
  • Risk gate blocks
  • Kill switch triggered
  • Large price moves (configurable threshold)

Configuration Options

notify_on_trade: true
notify_on_risk_blocks: true
notify_on_large_move: true
large_move_threshold_pct: 3.0
notify_on_kill_switch: true

News & Sentiment Analysis

The system integrates news headlines into trading decisions using a deterministic lexicon-based sentiment scorer.

How It Works

  1. News Fetching: Headlines are fetched via Alpha Vantage API (if key provided) or RSS feeds (fallback)
  2. Sentiment Scoring: Each headline is scored using a financial lexicon (~60 positive, ~60 negative terms)
  3. Feature Generation: Sentiment features are computed and passed to the policy
  4. Decision Integration: The RulesPolicy amplifies/dampens signals based on sentiment alignment

Sentiment Features

Feature Description
sentiment_score -1.0 to 1.0 aggregate sentiment from headlines
news_volume Normalized count of recent headlines (0-1)
major_news_flag 1.0 if high volume or strong sentiment
news_weight Position sizing multiplier (0.5-1.5)

Configuration

# config.yaml
news_enabled: true
alpha_vantage_api_key: 'your-key'  # Optional, uses RSS if not set

Or set ALPHA_VANTAGE_API_KEY in your .env file.

Policy Behavior

  • Aligned sentiment: If trend and sentiment agree, signal strength is amplified by up to 50%
  • Conflicting sentiment: If trend and sentiment disagree, signal is dampened by 50%
  • Major news: Confidence is adjusted when major news is present

Calendar-Based Trading Controls

The system tracks earnings dates, Fed meetings, and market holidays to avoid trading during high-uncertainty periods.

Blackout Events

Event Type Behavior
Earnings Configurable window (default: 2 days before, 1 day after)
Fed Meeting Days Full trading day of FOMC announcements
Market Holidays US market holidays (system won't trade)

Blackout Behavior

During blackouts, the risk gate enforces "reduce-only" mode by default:

  • New positions are blocked
  • Reducing/closing existing positions is allowed
  • Set blackout_reduce_only: false in config to block all trades

Configuration

# config.yaml
earnings_blackout_days_before: 2
earnings_blackout_days_after: 1
blackout_reduce_only: true

# Manual earnings dates (optional)
earnings_dates:
  AAPL: ['2025-01-30', '2025-04-24']
  MSFT: ['2025-01-28', '2025-04-22']

Built-in Calendar Data

  • Fed Meetings: 2024-2026 FOMC announcement dates pre-loaded
  • Holidays: US market holidays 2024-2026 pre-loaded

System Audit Tool

Verify that all components are properly wired:

uv run python tools/audit.py

This checks:

  • All modules import correctly
  • Sentiment features are computed
  • Calendar flags are generated
  • Risk gate handles blackouts
  • Main.py has all components wired

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages