11# alpaca-trader
22
3+ [ ![ CI] ( https://github.com/costajohnt/alpaca-trader/actions/workflows/ci.yml/badge.svg )] ( https://github.com/costajohnt/alpaca-trader/actions/workflows/ci.yml )
4+
35Automated equities trading system built on Alpaca's API. Combines mean-reversion technicals, AI sentiment analysis, insider trading signals, and momentum detection with conviction-based position sizing and sector exposure guards.
46
7+ An autonomous strategy agent (Claude Opus 4.6 via OpenRouter) reviews performance weekly, runs shadow experiments, and deploys validated improvements — all within hardcoded safety rails.
8+
59## Setup
610
711``` bash
8- # Install dependencies
12+ # Install dependencies (requires Python 3.14+)
913uv sync
1014
1115# Copy and fill in your API keys
@@ -19,11 +23,11 @@ Required `.env` keys:
1923
2024Optional ` .env ` keys:
2125
22- - ` FINNHUB_API_KEY ` — enables insider trading + earnings signals
26+ - ` ANTHROPIC_API_KEY ` — enables Claude Haiku sentiment analysis via Alpaca News API
27+ - ` OPENROUTER_API_KEY ` — enables autonomous strategy agent (Claude Opus 4.6)
28+ - ` FINNHUB_API_KEY ` — enables insider trading + earnings signals (cached, rate-limited)
2329- ` TELEGRAM_BOT_TOKEN ` / ` TELEGRAM_CHAT_ID ` — enables Telegram notifications
2430
25- > The Claude CLI must be installed and authenticated separately for sentiment analysis.
26-
2731## Usage
2832
2933``` bash
@@ -46,7 +50,10 @@ uv run python scripts/scan_with_sentiment.py --execute
4650uv run python scripts/screener.py --min-dip -8.0
4751
4852# Auto-trade top screener picks
49- uv run python scripts/screener_trade.py --min-dip -10.0 --max-trades 5 --execute
53+ uv run python scripts/screener_trade.py --min-dip -7.0 --max-trades 8 --execute
54+
55+ # Momentum auto-trade
56+ uv run python scripts/momentum_trade.py --min-momentum 10.0 --max-trades 5 --execute
5057
5158# Manage exits for open positions
5259uv run python scripts/position_manager.py --execute --check-sentiment
@@ -55,51 +62,103 @@ uv run python scripts/position_manager.py --execute --check-sentiment
5562uv run python scripts/dashboard.py
5663
5764# Run tests
58- uv run pytest tests/
65+ uv run python -m pytest tests/
66+
67+ # Strategy agent (dry run — no API key needed)
68+ uv run python scripts/strategy_agent.py --mode weekly --dry-run
5969```
6070
6171## Daily Pipeline
6272
63- Automated via ` scripts/daily_run.sh ` (launchd at 6:45 AM and 12:45 PM PT) :
73+ Automated via GitHub Actions ( ` .github/workflows/daily-trading.yml ` ), runs Mon-Fri at 6:45 AM and 12:45 PM PT:
6474
65- 1 . ** Position manager** — manage exits for all open positions first
66- 2 . ** Screener auto-trade** — find biggest dips market-wide, trade top 5
67- 3 . ** Watchlist scan** — 3-layer analysis on core watchlist, execute trades
68- 4 . ** Momentum screener ** — log surging stocks (research, no auto-trade)
75+ 1 . ** Position manager** — manage exits for all open positions
76+ 2 . ** Screener auto-trade** — find biggest dips market-wide, trade top picks
77+ 3 . ** Watchlist scan** — 3-layer composite analysis on core watchlist
78+ 4 . ** Momentum auto-trade ** — trend-following entries on surging stocks
69795 . ** Portfolio + performance** — summary and signal accuracy report
80+ 6 . ** Strategy agent** — lightweight event check for acute problems
81+
82+ ## Strategy Agent
83+
84+ An autonomous agent (` scripts/strategy_agent.py ` ) that self-improves the trading system using Claude Opus 4.6 via OpenRouter.
85+
86+ ** Weekly review** (Saturdays via ` .github/workflows/strategy-review.yml ` ):
87+ - Reads performance data, changelog, and experiment results
88+ - Diagnoses problems using structured reasoning (observe, compare, diagnose, validate, act)
89+ - Validates changes via walk-forward backtesting with holdout Sharpe validation
90+ - Deploys code changes or creates shadow experiments
91+ - Max 2 deploys/week, 14-day cooling period per file
92+
93+ ** Event check** (after each daily pipeline run):
94+ - Checks for acute problems (consecutive stop-losses, drawdown spikes, low win rates)
95+ - Evaluates active shadow experiments
96+ - Can pause strategies (auto-expires in 3 days) but saves bigger changes for weekly review
97+
98+ ** Safety rails** (hardcoded in ` scripts/agent_tools.py ` — agent cannot modify):
99+ - Minimum sample sizes enforced (50 trades for parameters, 30 for filters)
100+ - All tests must pass before any deploy
101+ - Position size capped at 5% of equity
102+ - Max-loss stop cannot be disabled
103+ - Automatic rollback on test failure
70104
71105## Architecture
72106
73107```
74108client.py Alpaca client factory
75109
76110strategies/
77- mean_reversion.py SMA-based mean reversion
78- sentiment.py Claude Haiku sentiment on news from Alpaca News API
79- insider.py Finnhub insider trading + earnings
111+ mean_reversion.py SMA-based mean reversion + weekly confirmation
112+ sentiment.py Claude Haiku sentiment on news ( Alpaca News API)
113+ insider.py Finnhub insider trading + earnings (cached, rate-limited)
80114 momentum.py 10d/50d momentum + volume surge
81115 config.py Watchlist + per-stock thresholds
82116 sizing.py Conviction-based position sizing
83- sector.py Sector exposure + correlation guard
117+ volatility.py ATR-based volatility for threshold normalization
118+ sector.py Sector exposure + correlation guard (126 tickers)
119+ signal_scorer.py Empirical signal scoring (bucket win rates)
120+ constants.py Tunable strategy parameters (agent-modifiable)
84121 enums.py Shared enums (Action, InsiderRecommendation)
85122
86123scripts/
87124 scan_with_sentiment.py 3-layer composite signal + sizing + sector guard
88- screener.py Market-wide screener (11K+ equities)
125+ screener.py Market-wide screener (11K+ equities, quality filters )
89126 screener_trade.py Auto-trade top screener picks
90- position_manager.py Exit manager (trailing stop, take-profit, time, sentiment)
127+ momentum_trade.py Auto-trade momentum picks
128+ position_manager.py Exit manager (trailing stop, take-profit, breakeven, cooldown)
91129 portfolio.py CLI account dashboard
92130 dashboard.py Flask web dashboard (port 8050)
93131 performance.py Signal accuracy analysis
94- trade_logger.py CSV logging (data/signals.csv, data/trades.csv )
132+ trade_logger.py CSV logging (auto-migrating headers )
95133 notify.py macOS + Telegram notifications
96134 backtest.py Single-ticker backtesting
97135 full_backtest.py Full system backtest (Sharpe, drawdown)
98- daily_run.sh Pipeline automation
99- account_status.py Quick account connection + status check
100- run_strategy.py Single-ticker mean-reversion with optional execution
101- momentum_screener.py Market-wide momentum screener (volume + 10d/50d)
136+ pipeline_backtest.py Pipeline backtest with all features
137+ param_sweep.py Parameter grid search + sensitivity analysis
138+ strategy_agent.py Autonomous strategy agent (weekly review + event check)
139+ agent_tools.py Agent tool definitions + safety-hardcoded dispatch
140+ shadow_evaluator.py Shadow experiment evaluation
141+ daily_run.sh Local pipeline automation
142+ account_status.py Quick account connection check
143+ run_strategy.py Single-ticker mean-reversion analysis
144+ momentum_screener.py Market-wide momentum screener
145+
146+ data/ Trading state (signals.csv, trades.csv, metrics.json)
147+ data/agent/ Agent state (changelog, experiments, overrides)
148+ tests/ 654 tests across 30 test files
149+ ```
150+
151+ ## Testing
102152
103- data/ Local data (gitignored)
104- tests/ Test suite
153+ ``` bash
154+ # Run all tests
155+ uv run python -m pytest tests/
156+
157+ # Run with verbose output
158+ uv run python -m pytest tests/ -v
159+
160+ # Run a specific test file
161+ uv run python -m pytest tests/test_agent_tools.py -v
105162```
163+
164+ CI runs automatically on push to ` main ` and on pull requests.
0 commit comments