Skip to content

AI Automation for Research and Trading and Accomplishing Tasks

Notifications You must be signed in to change notification settings

josephflu/ai_trader

Repository files navigation

AI Trader

An AI-powered algorithmic trading system with Claude integration for intelligent signal generation.

Features

  • Paper Trading: Safe experimentation with Alpaca's paper trading API
  • Claude Integration: AI-powered trading signals using Claude for news/sentiment analysis
  • Multiple Strategies: Extensible strategy framework supporting parallel strategy execution
  • Risk Management: Position limits, confidence thresholds, and comprehensive logging
  • Rich CLI: Beautiful command-line interface built with Typer and Rich
  • Performance Tracking: Detailed analytics and strategy comparison

Installation

# Clone the repository
git clone <repo-url>
cd ai_trader

# Install dependencies using uv
uv pip install -e .

Configuration

API Keys

Create config/api_keys.yaml with your credentials:

alpaca:
  endpoint: https://paper-api.alpaca.markets/v2
  api_key: YOUR_ALPACA_API_KEY
  secret_key: YOUR_ALPACA_SECRET_KEY

anthropic:
  api_key: YOUR_ANTHROPIC_API_KEY

Settings (Optional)

Create config/settings.yaml to customize behavior:

trading:
  max_position_pct: 0.10    # Max 10% portfolio per position
  min_confidence: 0.70       # Only trade on signals > 70% confidence
  paper_mode: true

strategies:
  news:
    enabled: true
    watchlist: [AAPL, TSLA, NVDA, GOOGL, MSFT]
    news_lookback_hours: 24

  claude:
    enabled: true
    model: claude-sonnet-4-20250514
    temperature: 0.3

Usage

Account & Portfolio Management

# View account status
trader account

# List open positions
trader positions

# View recent orders
trader orders

# View recent trades
trader trades

Manual Trading

# Buy shares (market order)
trader buy AAPL 10

# Sell shares (market order)
trader sell AAPL 10

# Limit orders
trader buy AAPL 10 --limit 150.00
trader sell AAPL 10 --limit 160.00

Strategy Execution

# List available strategies
trader strategies

# Run a strategy (dry run)
trader run news

# Run strategy and execute trades
trader run claude --execute

# View recent signals
trader signals

# View recent trades
trader trades

Performance Analytics

# Compare all strategies
trader performance

# View specific strategy performance
trader performance claude

# Custom time window
trader performance news --days 7

Architecture

Project Structure

ai_trader/
├── src/ai_trader/
│   ├── cli/              # CLI commands
│   ├── broker/           # Alpaca integration
│   │   ├── client.py     # Trading client wrapper
│   │   ├── executor.py   # Trade execution with risk management
│   │   └── models.py     # Data models
│   ├── strategies/       # Trading strategies
│   │   ├── base.py       # Strategy interface
│   │   ├── news.py       # News-based strategy
│   │   └── claude.py     # Claude-powered strategy
│   ├── signals/          # Signal generation
│   │   └── claude.py     # Claude API integration
│   ├── data/             # Data layer
│   │   ├── database.py   # SQLite operations
│   │   ├── models.py     # Database models
│   │   └── performance.py # Performance tracking
│   └── config.py         # Configuration management
└── config/               # Configuration files (gitignored)

Strategy System

All strategies inherit from the Strategy base class:

from ai_trader.strategies.base import Strategy, TradeSignal, SignalType

class MyStrategy(Strategy):
    def __init__(self):
        super().__init__("my_strategy")

    def analyze(self, symbol: str) -> TradeSignal:
        # Implement your logic
        return TradeSignal(
            symbol=symbol,
            signal=SignalType.BUY,
            confidence=0.8,
            reason="Strong buy signal",
            strategy_name=self.name
        )

    def get_watchlist(self) -> list[str]:
        return ["AAPL", "TSLA"]

Risk Management

The TradeExecutor enforces:

  • Confidence thresholds: Only execute signals with confidence > min_confidence
  • Position limits: Max percentage of portfolio per position
  • Account checks: Verify sufficient buying power
  • Comprehensive logging: All signals and trades logged to database

Data Storage

SQLite database tracks:

  • Trades: All executed trades with strategy attribution
  • Signals: Generated trading signals (executed and rejected)
  • Performance: Strategy performance metrics over time

Development

Adding a New Strategy

  1. Create a new file in src/ai_trader/strategies/
  2. Inherit from Strategy base class
  3. Implement analyze() and get_watchlist() methods
  4. Register in CLI (optional)

Example:

from .base import Strategy, TradeSignal, SignalType

class MyStrategy(Strategy):
    def analyze(self, symbol: str) -> TradeSignal:
        # Your logic here
        pass

    def get_watchlist(self) -> list[str]:
        return ["AAPL", "GOOGL"]

Running Tests

# Run tests (when implemented)
pytest tests/

Safety Features

  1. Paper Trading Only: System configured for paper trading by default
  2. Position Limits: Maximum 10% of portfolio per position
  3. Confidence Thresholds: Only trade on high-confidence signals
  4. Dry Run Mode: Test strategies without executing trades
  5. Comprehensive Logging: Every action logged to database

Roadmap

  • News API integration for real-time news feeds
  • Backtesting framework for historical analysis
  • Technical indicator strategies (RSI, MACD, moving averages)
  • Streamlit dashboard for visual analytics
  • Scheduling daemon for automated trading
  • Email/Slack notifications for trades
  • More sophisticated risk management

License

MIT

Disclaimer

This software is for educational and experimental purposes only. Trading involves substantial risk of loss. Always practice with paper trading before risking real capital.

About

AI Automation for Research and Trading and Accomplishing Tasks

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages