Skip to content

Commit 611655f

Browse files
costajohntclaude
andcommitted
Address 7 high-priority codebase issues
1. Structured logging: Replace 929 print() calls with stdlib logging via strategies/log.py factory. Two-tier: full conversion for operational modules, WARNING/ERROR only for display scripts. 2. Pipeline failure alerting: Telegram notifications on daily pipeline failures (daily_run.sh + GHA), agent deploy/rollback events. 3. CI data branch: Move trading data (signals.csv, trades.csv, agent/) to dedicated trading-data branch. Main stays clean for code changes. 4. agent_tools.py split: 1,702 → 3 files (164 + 686 + 959 lines). Safety constants + dispatch in agent_tools.py (no-touch file), reads in agent_reads.py, writes in agent_writes.py. 5. dashboard.py split: 2,071 → 3 files (208 + 357 + 1,516 lines). Routes in dashboard.py, data layer in dashboard_data.py, HTML/CSS/JS template extracted to templates/dashboard.html. 6. Coverage threshold: 54% minimum with branch coverage enforced in CI. 7. Drift monitor: New scripts/drift_monitor.py compares backtest predictions to live performance, alerts on significant deviation. Integrated into weekly strategy-review workflow. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
1 parent ba8c2ba commit 611655f

54 files changed

Lines changed: 4311 additions & 6017 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

.github/workflows/ci.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ jobs:
3838
run: uv sync
3939

4040
- name: Run tests with coverage
41-
run: uv run python -m pytest tests/ -v --tb=short --cov=strategies --cov=scripts --cov-report=term-missing --cov-report=html
41+
run: uv run python -m pytest tests/ -v --tb=short --cov=strategies --cov=scripts --cov-report=term-missing --cov-report=html --cov-fail-under=54
4242

4343
- name: Upload coverage report
4444
if: always()

.github/workflows/daily-trading.yml

Lines changed: 37 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,11 @@ jobs:
4343
- name: Ensure data directory exists
4444
run: mkdir -p data
4545

46+
- name: Restore state from trading-data branch
47+
run: |
48+
git fetch origin trading-data 2>/dev/null || true
49+
git checkout origin/trading-data -- data/ 2>/dev/null || echo "No prior trading data"
50+
4651
- name: 1. Position Manager (manage exits)
4752
id: position_manager
4853
run: uv run python scripts/position_manager.py --execute --check-sentiment
@@ -77,12 +82,40 @@ jobs:
7782
run: uv run python scripts/strategy_agent.py --mode event-check
7883
continue-on-error: true
7984

80-
- name: Commit updated state files
85+
- name: Commit state to trading-data branch
8186
if: always()
8287
run: |
8388
git config user.name "github-actions[bot]"
8489
git config user.email "github-actions[bot]@users.noreply.github.com"
90+
91+
# Save data directory
92+
cp -r data/ /tmp/trading-data-snapshot/
93+
94+
# Switch to trading-data branch (create if needed)
95+
git fetch origin trading-data 2>/dev/null || true
96+
git checkout trading-data 2>/dev/null || git checkout --orphan trading-data
97+
98+
# Clean and restore data
99+
rm -rf data/
100+
cp -r /tmp/trading-data-snapshot/ data/
101+
85102
git add data/
86-
git diff --cached --quiet || git commit -m "chore: update trading state"
87-
git pull --rebase || true
88-
git push
103+
git diff --cached --quiet || git commit -m "chore: update trading state [$(date -u +%Y-%m-%dT%H:%M:%SZ)]"
104+
git push origin trading-data
105+
106+
# Return to original branch for any subsequent steps
107+
git checkout ${{ github.ref_name }} 2>/dev/null || true
108+
109+
- name: Alert on pipeline failures
110+
if: failure()
111+
env:
112+
TELEGRAM_BOT_TOKEN: ${{ secrets.TELEGRAM_BOT_TOKEN }}
113+
TELEGRAM_CHAT_ID: ${{ secrets.TELEGRAM_CHAT_ID }}
114+
GH_REPO: ${{ github.repository }}
115+
GH_RUN_ID: ${{ github.run_id }}
116+
run: |
117+
if [ -n "$TELEGRAM_BOT_TOKEN" ] && [ -n "$TELEGRAM_CHAT_ID" ]; then
118+
curl -s -X POST "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage" \
119+
-d chat_id="$TELEGRAM_CHAT_ID" \
120+
-d text="GHA Pipeline Alert: daily-trading job failed. Check: https://github.com/${GH_REPO}/actions/runs/${GH_RUN_ID}"
121+
fi

.github/workflows/strategy-review.yml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,10 @@ jobs:
4242
run: uv run python scripts/strategy_agent.py --mode weekly
4343
continue-on-error: true
4444

45+
- name: Run drift monitor
46+
run: uv run python scripts/drift_monitor.py --alert
47+
continue-on-error: true
48+
4549
- name: Commit agent state and code changes
4650
if: always()
4751
run: |

.gitignore

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@ data/trading_state.db
1212
data/metrics.json
1313
data/audit/
1414

15+
# Trading state — lives on trading-data branch
16+
data/signals.csv
17+
data/trades.csv
18+
data/agent/
19+
1520
# Test / coverage artifacts
1621
.coverage
1722
htmlcov/

CLAUDE.md

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ Automated equities trading system using Alpaca's API.
2929
- `risk_guard.py` — Portfolio-level kill switch (daily loss + drawdown from HWM)
3030
- `state_db.py` — SQLite persistence for all trading state (HWMs, cooldowns, partial profits, equity)
3131
- `weekly_trend.py` — Weekly SMA trend filter (blocks severe downtrends only)
32+
- `log.py` — Structured logging factory (`get_logger` with `alpaca.` namespace prefix)
3233

3334
### Scripts (`scripts/`)
3435

@@ -38,7 +39,7 @@ Automated equities trading system using Alpaca's API.
3839
- `position_manager.py` — Exit manager: max-loss stop, dynamic trailing stop, partial profit, breakeven stop, cooldown tracking, null-price alerting
3940
- `momentum_trade.py` — Auto-trades momentum picks with momentum-adapted position sizing
4041
- `portfolio.py` — Account dashboard (CLI) + equity curve snapshot recording
41-
- `dashboard.py` — Live web dashboard (Flask, port 8050)
42+
- `dashboard.py` — Live web dashboard routes (Flask, port 8050)
4243
- `performance.py` — Signal accuracy analysis + strategy attribution + slippage analysis
4344
- `trade_logger.py` — CSV logging to `data/signals.csv` and `data/trades.csv` (with strategy_source column)
4445
- `notify.py` — macOS + Telegram notifications
@@ -51,7 +52,11 @@ Automated equities trading system using Alpaca's API.
5152
- `run_strategy.py` — Run single-ticker mean-reversion analysis with optional execution
5253
- `momentum_screener.py` — Market-wide momentum screener (volume + 10d/50d momentum)
5354
- `strategy_agent.py` — Autonomous strategy improvement agent (OpenRouter via OpenAI SDK, Opus 4.6, weekly + event-triggered)
54-
- `agent_tools.py` — 16 agent tools with safety constraints (no-touch files, change budget, cooling periods, atomic writes)
55+
- `agent_tools.py` — Agent safety constants, tool dispatch, and TOOL_DEFINITIONS (no-touch file)
56+
- `agent_reads.py` — Agent read/compute tools (side-effect-free observations)
57+
- `agent_writes.py` — Agent write/deploy tools (state-mutating operations)
58+
- `dashboard_data.py` — Dashboard data loading and performance computation
59+
- `drift_monitor.py` — Backtest-to-live drift detection with alerting
5560
- `shadow_evaluator.py` — Shadow experiment evaluator (retrospective A/B testing against real trades)
5661
- `daily_metrics.py` — Daily performance metrics snapshot
5762
- `walkforward.py` — Walk-forward backtesting validation
@@ -98,6 +103,11 @@ Automated equities trading system using Alpaca's API.
98103
- Shadow experiments: retrospective A/B testing of parameter changes against real trade data (max 2 active, 14-day duration)
99104
- All scripts use `uv run python scripts/<name>.py`
100105
- Run tests with: `uv run pytest tests/`
106+
- Structured logging: use `from strategies.log import get_logger; logger = get_logger(__name__)` — never bare `print()` for warnings/errors
107+
- Coverage threshold: 54% minimum with branch coverage enforced in CI (strategies/ at 78%, scripts/ lower due to CLI entry points)
108+
- Trading data (signals.csv, trades.csv, agent/) committed to `trading-data` branch, not `main`
109+
- Pipeline failure alerting: Telegram notifications on daily pipeline failures, agent deploys, and rollbacks
110+
- Drift monitoring: weekly comparison of backtest predictions vs live performance (>15pp win rate, >0.5 Sharpe, >2x drawdown triggers alert)
101111

102112
## Dependencies
103113

data/agent/.gitkeep

Whitespace-only changes.

data/agent/changelog.json

Lines changed: 0 additions & 16 deletions
This file was deleted.

data/agent/experiments/.gitkeep

Whitespace-only changes.

0 commit comments

Comments
 (0)