{"id":48277051,"url":"https://github.com/scottdhughes/pxi-command","last_synced_at":"2026-04-04T22:37:17.169Z","repository":{"id":330747630,"uuid":"1123794036","full_name":"scottdhughes/pxi-command","owner":"scottdhughes","description":"Quantitative market tools: PXI macro strength index (28 indicators → 0-100 score) + weekly sector rotation signals from Reddit analysis. Live at pxicommand.com","archived":false,"fork":false,"pushed_at":"2026-03-06T06:40:56.000Z","size":3936,"stargazers_count":0,"open_issues_count":1,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-03-06T10:57:53.738Z","etag":null,"topics":["cloudflare-workers","finance","macro","market-analysis","market-data","open-source","quantitative-finance","react","reddit","sentiment-analysis","typescript"],"latest_commit_sha":null,"homepage":"https://pxicommand.com","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/scottdhughes.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":"AGENTS.md","dco":null,"cla":null}},"created_at":"2025-12-27T16:28:53.000Z","updated_at":"2026-02-22T01:53:22.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/scottdhughes/pxi-command","commit_stats":null,"previous_names":["scottdhughes/pxi-command"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/scottdhughes/pxi-command","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scottdhughes%2Fpxi-command","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scottdhughes%2Fpxi-command/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scottdhughes%2Fpxi-command/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scottdhughes%2Fpxi-command/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/scottdhughes","download_url":"https://codeload.github.com/scottdhughes/pxi-command/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/scottdhughes%2Fpxi-command/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":31417136,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-04T20:09:54.854Z","status":"ssl_error","status_checked_at":"2026-04-04T20:09:44.350Z","response_time":60,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cloudflare-workers","finance","macro","market-analysis","market-data","open-source","quantitative-finance","react","reddit","sentiment-analysis","typescript"],"created_at":"2026-04-04T22:37:16.537Z","updated_at":"2026-04-04T22:37:17.146Z","avatar_url":"https://github.com/scottdhughes.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# PXI /COMMAND\n\n[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)\n[![Cloudflare Workers](https://img.shields.io/badge/Cloudflare-Workers-F38020?logo=cloudflare\u0026logoColor=white)](https://workers.cloudflare.com/)\n[![TypeScript](https://img.shields.io/badge/TypeScript-5.0-3178C6?logo=typescript\u0026logoColor=white)](https://www.typescriptlang.org/)\n[![React](https://img.shields.io/badge/React-19-61DAFB?logo=react\u0026logoColor=black)](https://react.dev/)\n\nA suite of quantitative market tools:\n- **PXI Index** - Real-time macro market strength (28 indicators → single 0-100 score)\n- **Sector Signals** - Weekly sector rotation signals from Reddit discussion analysis\n\n**Live:** [pxicommand.com](https://pxicommand.com) · [/signals](https://pxicommand.com/signals)\n\n## What is PXI?\n\nPXI (Positioning Index) synthesizes signals from liquidity, credit spreads, volatility, market breadth, macro economic data, global risk appetite, and crypto markets into one score:\n\n| Score | Status | Meaning |\n|-------|--------|---------|\n| 80+ | MAX PAMP | Extremely bullish conditions |\n| 65-79 | PAMPING | Bullish conditions |\n| 45-64 | NEUTRAL | Mixed signals |\n| 30-44 | SOFT | Bearish conditions |\n| \u003c30 | DUMPING | Extremely bearish conditions |\n\n## Features\n\n### Core Index\n- **28 indicators** across 7 categories normalized to 0-100 scale\n- **Real-time updates** via GitHub Actions cron (4x daily)\n- **Historical backtest** with 1000+ observations since Dec 2022\n\n### ML \u0026 Predictions (v1.2)\n- **Ensemble Predictions** - Weighted combination of XGBoost (60%) and LSTM (40%) with confidence scoring\n- **XGBoost Model** - Gradient boosted trees using 36 engineered features (momentum, dispersion, extremes)\n- **LSTM Model** - Recurrent neural network using 20-day sequences of 12 features for temporal patterns\n- **Similar Period Detection** - Find historically similar market regimes using vector embeddings\n- **Prediction Tracking** - Log predictions and evaluate against actual outcomes\n- **Historical Outlook** - Forward returns and win rates by PXI bucket with adaptive thresholds\n- **Signal Layer** - Risk allocation signals based on PXI, momentum, and volatility\n\n### Backtesting\n- **PXI-Signal Strategy** - Dynamic risk allocation (Sharpe ~2.0)\n- **Comparison** - vs 200DMA and buy-and-hold baselines\n- **Walk-forward validation** - Out-of-sample testing\n\n### MCP Server (AI Agent Integration)\n- **Model Context Protocol** - Enables Claude and other LLM agents to query PXI\n- **7 Tools** - get_pxi, get_predictions, get_similar_periods, get_signal, get_regime, get_market_context, get_history\n- **Agent-Optimized** - Structured responses with suggested actions and risk assessments\n\n### Sector Rotation Signals (`/signals`)\n- **Weekly Analysis** - Runs every Monday (or Tuesday if Monday is a US market holiday)\n- **Reddit Sentiment** - Analyzes 750+ posts from investing subreddits\n- **20 Sector Themes** - Nuclear, Automation, Defense, Copper, Financials, and more\n- **Classification System** - Signal type (Rotation/Momentum/Divergence/Reversion), confidence, timing\n- **Evidence-Based** - Links to source discussions for each theme\n\n## Categories \u0026 Weights\n\n| Category | Weight | Key Indicators |\n|----------|--------|----------------|\n| Credit | 20% | HY spreads, IG spreads, yield curve |\n| Liquidity | 15% | Fed balance sheet, TGA, reverse repo, net liquidity |\n| Volatility | 15% | VIX, VIX term structure |\n| Breadth | 15% | RSP/SPY ratio, advance-decline |\n| Positioning | 15% | Put/call ratio, fear \u0026 greed |\n| Macro | 10% | 10Y yield, dollar index, oil |\n| Global | 10% | Copper/gold ratio, BTC, stablecoin flows |\n\n## Architecture\n\n```\n                              PXI INDEX                                    SIGNALS\n                    ┌─────────────────────────┐                 ┌─────────────────────────┐\n                    │                         │                 │                         │\n┌─────────────────┐ │  ┌──────────────────┐   │  ┌───────────┐  │  ┌──────────────────┐   │\n│   Data Sources  │───▶│  GitHub Actions  │   │  │  Reddit   │────▶│  Cloudflare Cron │   │\n│  FRED, Yahoo,   │ │  │   (Daily Cron)   │   │  │   API     │  │  │   (Weekly)       │   │\n│  DeFiLlama...   │ │  └────────┬─────────┘   │  └───────────┘  │  └────────┬─────────┘   │\n└─────────────────┘ │           │             │                 │           │             │\n                    │           ▼             │                 │           ▼             │\n                    │  ┌──────────────────┐   │                 │  ┌──────────────────┐   │\n                    │  │  Cloudflare D1   │   │                 │  │  Cloudflare D1   │   │\n                    │  │   (SQLite)       │   │                 │  │  + R2 Storage    │   │\n                    │  └────────┬─────────┘   │                 │  └────────┬─────────┘   │\n                    │           │             │                 │           │             │\n                    └───────────┼─────────────┘                 └───────────┼─────────────┘\n                                │                                           │\n                                ▼                                           ▼\n                    ┌──────────────────────────────────────────────────────────────────┐\n                    │                     React Frontend (CF Pages)                     │\n                    │                        pxicommand.com                             │\n                    └──────────────────────────────────────────────────────────────────┘\n```\n\n## Project Structure\n\n```\npxi-command/\n├── frontend/        # React app (pxicommand.com)\n├── worker/          # Main PXI API worker\n├── signals/         # Sector rotation signals worker (/signals)\n├── ml/              # ML model training (XGBoost, LSTM)\n├── mcp-server/      # MCP server for AI agents\n├── src/             # Shared data collection scripts\n└── ai/              # AI analysis prompts\n```\n\n## Tech Stack\n\n- **Backend:** TypeScript, Node.js\n- **Database:** Cloudflare D1 (SQLite at edge)\n- **Storage:** Cloudflare R2 (report storage for signals)\n- **Vector Store:** Cloudflare Vectorize (768-dim embeddings)\n- **ML Models:** XGBoost + LSTM (trained locally, inference at edge via KV)\n- **AI:** Cloudflare Workers AI (BGE embeddings, Llama analysis)\n- **API:** Cloudflare Workers\n- **Frontend:** React 19, Vite, Tailwind CSS\n- **Hosting:** Cloudflare Pages\n- **Scheduler:** GitHub Actions (PXI daily) + Cloudflare Cron (Signals weekly)\n- **Agent Integration:** MCP Server (Model Context Protocol)\n\n## API Endpoints\n\n### Core Data\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/api/pxi` | GET | Current PXI score, categories, sparkline, regime, and freshness operator payload (`topOffenders`, refresh ETA) |\n| `/api/history` | GET | Historical PXI scores |\n| `/api/regime` | GET | Current market regime detection |\n| `/api/signal` | GET | PXI-Signal layer with risk allocation |\n| `/api/plan` | GET | Canonical decision object for homepage (policy state, uncertainty, consistency, trader playbook) |\n| `/api/market/consistency` | GET | Latest decision consistency score/state/violations |\n| `/api/ops/freshness-slo` | GET | Rolling 7d/30d freshness SLO attainment and recent critical stale incidents |\n| `/api/ops/utility-funnel` | GET | Rolling utility funnel metrics (session -\u003e decision views -\u003e no-action unlock coverage + CTA intent rate) |\n| `/api/ops/decision-impact` | GET | Decision-impact ops view (7d/30d market outcome proxy, theme summary, utility attribution, governance mode with observe + enforce readiness) |\n| `/api/ops/decision-grade` | GET | Rolling governance scorecard (freshness, consistency, calibration, edge evidence, opportunity hygiene, utility) |\n| `/api/ops/go-live-readiness` | GET | Explicit go-live readiness snapshot (blockers + decision-impact enforce readiness context) |\n\n### Product Layer (Phase 1)\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/api/brief` | GET | Daily market brief coherent with `/api/plan` policy state (includes contract version + consistency) |\n| `/api/opportunities` | GET | Ranked opportunities for `7d` or `30d` horizon with calibration + expectancy + unavailable reasons |\n| `/api/decision-impact` | GET | Outcome attribution using matured opportunity ledger rows (market uses SPY forward proxy; theme uses proxy blend with SPY fallback, 30/90d windows) |\n| `/api/diagnostics/calibration` | GET | Calibration diagnostics (Brier/ECE/log loss + quality band) for conviction and edge-quality snapshots |\n| `/api/diagnostics/edge` | GET | Forward-chaining edge evidence (model vs lagged baseline uplift, CI, leakage sentinel, promotion gate) |\n| `/api/alerts/feed` | GET | In-app alert timeline (`regime_change`, `threshold_cross`, `opportunity_spike`, `freshness_warning`) |\n| `/api/alerts/subscribe/start` | POST | Start email digest subscription with verification token |\n| `/api/alerts/subscribe/verify` | POST | Verify subscription token and activate email digest |\n| `/api/alerts/unsubscribe` | POST | Unsubscribe via token |\n| `/api/metrics/utility-event` | POST | Record lightweight product utility telemetry events (session, decision view, no-action unlock, `cta_action_click`) |\n\n### ML \u0026 Predictions\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/api/similar` | GET | Find similar historical periods (vector search with weighted scoring) |\n| `/api/predict` | GET | Historical outlook by PXI bucket with adaptive thresholds |\n| `/api/ml/predict` | GET | XGBoost model predictions for 7d/30d PXI changes |\n| `/api/ml/lstm` | GET | LSTM neural network predictions using 20-day sequences |\n| `/api/ml/ensemble` | GET | Weighted ensemble (60% XGBoost + 40% LSTM) with confidence |\n| `/api/accuracy` | GET | Prediction accuracy metrics |\n| `/api/analyze` | GET | AI-generated market analysis |\n\n### Backtesting\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/api/backtest` | GET | PXI bucket forward returns analysis |\n| `/api/backtest/signal` | GET | Signal strategy vs baselines |\n\n### Admin (requires auth)\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/api/write` | POST | Write indicator data |\n| `/api/recalculate` | POST | Recalculate PXI for date |\n| `/api/migrate` | POST | Create missing database tables |\n| `/api/evaluate` | POST | Evaluate past predictions |\n| `/api/retrain` | POST | Retrain adaptive bucket thresholds |\n| `/api/export/training-data` | GET | Export data for ML model training |\n| `/api/market/refresh-products` | POST | Generate/store latest brief, opportunities, and market alerts |\n| `/api/market/send-digest` | POST | Send daily digest to active subscribers |\n\n### Signals (`/signals/*`)\n| Endpoint | Method | Description |\n|----------|--------|-------------|\n| `/signals/latest` | GET | Latest weekly report (HTML) |\n| `/signals/run/{id}` | GET | Specific report by run ID |\n| `/signals/api/runs` | GET | List all runs with metadata |\n| `/signals/api/runs/{id}` | GET | Run details as JSON |\n| `/signals/api/run` | POST | Trigger manual run (requires X-Admin-Token) |\n| `/signals/og-image.png` | GET | Dynamic OG image for social sharing |\n\n## Agent Docs\n\nAgent-discovery and markdown docs are published as static frontend endpoints:\n\n- `https://pxicommand.com/llms.txt`\n- `https://pxicommand.com/agent.md`\n- `https://pxicommand.com/signals/agent.md`\n\nCanonical read endpoints referenced by `llms.txt`:\n\n- `https://api.pxicommand.com/health`\n- `https://api.pxicommand.com/api/pxi`\n- `https://pxicommand.com/signals/api/runs`\n- `https://pxicommand.com/signals/api/accuracy`\n- `https://pxicommand.com/signals/api/predictions`\n\nWrite/admin endpoints remain auth-protected and are not intended for autonomous agent writes.\n\n## Data Freshness SLA\n\n`npm run cron:daily` enforces per-indicator freshness SLAs before any write/recalculate calls.\n\n### SLA Classes\n\n| Class | Max age (days) |\n|---|---:|\n| daily | 4 |\n| realtime | 4 |\n| weekly | 10 |\n| monthly | 45 |\n| source-lagged (`wti_crude`) | 7 |\n| source-lagged (`dollar_index`) | 10 |\n\n### Explicit Threshold Overrides\n\n| Indicator | Max age (days) |\n|---|---:|\n| `cfnai` | 120 |\n| `m2_yoy` | 120 |\n| `fed_balance_sheet` | 14 |\n| `treasury_general_account` | 14 |\n| `reverse_repo` | 14 |\n| `net_liquidity` | 14 |\n\n### Critical SLA Gate\n\nThe daily refresh fails if any of these are stale or missing after fetch stage:\n\n- `aaii_sentiment`\n- `copper_gold_ratio`\n- `vix`\n- `spy_close`\n- `dxy`\n- `hyg`\n- `lqd`\n- `fear_greed`\n\nRun summary output is written to `/tmp/pxi-sla-summary.json` and published to GitHub Actions step summary.\n\n## Market Product Automation\n\n- `Daily PXI Refresh` now runs ingestion + SLA gate + post-refresh product generation (`/api/market/refresh-products`).\n- Product summary output is written to `/tmp/pxi-market-summary.json` and appended to the Actions job summary.\n- A separate `Daily PXI Digest` workflow runs at `13:00 UTC` (8:00 AM ET standard) and calls `/api/market/send-digest`.\n- Digest summary output is written to `/tmp/pxi-digest-summary.json`.\n\n## PXI Audit Findings Remediation\n\nTaylor’s PXI audit findings are being remediated with trust-first controls:\n\n1. **Opportunity coherence gate**\n- Directional opportunities are only published when contract checks are coherent.\n- Bullish items must have non-negative expectancy and `p_correct \u003e= 0.50` when available.\n- Bearish items must have non-positive expectancy and `p_correct \u003e= 0.50` when available.\n- Neutral items are not published in phase 1 actionable feed.\n\n2. **Degraded-mode suppression**\n- `/api/opportunities` is hard-suppressed (`items: []`) when:\n  - `critical_stale_count \u003e 0`, or\n  - market consistency state is `FAIL`.\n- Response includes `suppressed_count` and `degraded_reason` (for example `suppressed_data_quality`, `coherence_gate_failed`, `quality_filtered`).\n\n3. **Calibration diagnostics transparency**\n- New endpoint: `GET /api/diagnostics/calibration`\n- Includes Brier score, ECE, log loss, quality band, and insufficient-sample reasons.\n\n4. **Freshness reliability governance**\n- New endpoint: `GET /api/ops/freshness-slo`\n- Reports rolling 7d and 30d SLO attainment using `market_refresh_runs`, including recent critical stale incidents.\n\n5. **Edge-proof diagnostics + promotion gate**\n- New endpoint: `GET /api/diagnostics/edge`\n- Reports forward-chaining directional uplift vs lagged baseline, CI bounds, and leakage sentinel health per horizon.\n- `/api/market/refresh-products` now fails closed when leakage sentinel checks fail, blocking publish/promotion.\n\n6. **Decision-stack unification + cross-horizon coherence**\n- `/api/plan` now includes additive `decision_stack` and `cross_horizon` blocks.\n- `cross_horizon.state` (`ALIGNED|MIXED|CONFLICT|INSUFFICIENT`) downgrades `ACTIONABLE -\u003e WATCH` on conflict/insufficient evidence.\n- Additional invalidation guidance is attached when horizons conflict or one horizon is missing.\n\n7. **Signals sanitation + stability**\n- Adapter-side ticker sanitation (allowlist regex, jargon stopwords, dedupe/cap) before PXI opportunity blending.\n- Signals source velocity cap tightened (`GROWTH_RATIO_CAP = 25`) with explicit `growth_ratio_capped` flag in metrics payload.\n\n8. **Opportunity TTL timebox + cache safety**\n- `/api/opportunities` now emits refresh recency metadata:\n  - `data_age_seconds`\n  - `ttl_state` (`fresh|stale|overdue|unknown`)\n  - `next_expected_refresh_at`\n  - `overdue_seconds`\n- CTA is hard-disabled when `ttl_state` is `overdue` or `unknown`.\n- Cache policy is timebox-aware: overdue/unknown states return `Cache-Control: no-store` to avoid stale hard-CTA exposure.\n\n9. **Utility funnel instrumentation (Phase 3)**\n- New ingestion endpoint: `POST /api/metrics/utility-event`.\n- New ops endpoint: `GET /api/ops/utility-funnel?window=7|30`.\n- Frontend now emits additive utility events for:\n  - `session_start`\n  - `plan_view`\n  - `opportunities_view`\n  - decision-state exposures (`decision_actionable_view|decision_watch_view|decision_no_action_view`)\n  - `no_action_unlock_view` (tracks no-action days as positive threshold-communication workflow events)\n  - `cta_action_click` (anonymous action intent from `/opportunities`)\n\n10. **Decision-grade governance (Phase 4)**\n- Immutable opportunity ledger tracks candidate-vs-published counts per horizon on every product refresh.\n- New ops endpoint: `GET /api/ops/decision-grade?window=7|30`.\n- Scorecard components:\n  - freshness SLO reliability\n  - consistency-state quality\n  - calibration quality band health\n  - edge-promotion evidence\n  - opportunity hygiene (over-suppression + cross-horizon conflict persistence)\n  - utility funnel adoption\n\n11. **Outcome attribution + utility lift (Phase 5)**\n- New endpoint: `GET /api/decision-impact?horizon=7d|30d\u0026scope=market|theme\u0026window=30|90`\n- New endpoint: `GET /api/ops/decision-impact?window=30|90`\n- Refresh pipeline persists:\n  - item-level publish/suppression ledger (`market_opportunity_item_ledger`)\n  - decision-impact snapshots (`market_decision_impact_snapshots`)\n- Attribution basis is `spy_forward_proxy` (market and theme scope in this phase).\n- Governance is **observe-only** in this phase. Breaches are surfaced in ops/workflow summaries but do not fail refresh runs.\n- Observe thresholds:\n  - `market_7d.hit_rate \u003e= 0.52`\n  - `market_30d.hit_rate \u003e= 0.50`\n  - `market_7d.avg_signed_return_pct \u003e 0`\n  - `market_30d.avg_signed_return_pct \u003e 0`\n  - `cta_action_rate_pct \u003e= 2.0`\n\n12. **Decision-impact enforcement + attribution hardening (Phase 6)**\n- `ops/decision-impact` now reports governance mode (`observe|enforce`), enforce readiness, and enforce breach list/count.\n- Enforce mode is sample-gated and disabled by default:\n  - `FEATURE_ENABLE_DECISION_IMPACT_ENFORCE=false`\n  - `DECISION_IMPACT_ENFORCE_MIN_SAMPLE=30`\n  - `DECISION_IMPACT_ENFORCE_MIN_ACTIONABLE_SESSIONS=10`\n- Theme attribution basis upgraded from pure SPY proxy to theme proxy blend (credit/vol/global/crypto mappings) with explicit SPY fallback when proxy coverage is unavailable.\n- Utility funnel CTA denominator now uses actionable sessions including CTA-click sessions (not only explicit actionable-view events) to reduce denominator undercount.\n- `POST /api/market/backfill-products` can now rebuild opportunity ledgers and regenerate decision-impact snapshots from historical opportunity snapshots (`rebuild_ledgers`, default `true`).\n\n13. **Go-live readiness + maturity-window correction (Phase 7)**\n- Decision-impact sampling now uses maturity-window semantics (outcome date in-window) instead of raw `as_of` filtering, so 30d attribution no longer collapses to zero in a 30d window.\n- `/api/ops/decision-grade` now emits explicit `go_live_blockers[]` plus readiness context (`decision_impact_enforce_ready`, sample counts, minimum thresholds).\n- New endpoint: `GET /api/ops/go-live-readiness?window=30` for a compact operator view of readiness blockers and score context.\n\n14. **Go-live blocker reduction + enforce readiness normalization (Phase 8)**\n- Utility decision target now scales by observed days in-window (instead of fixed full-window counts), improving early-window status stability.\n- Decision-impact actionable-session minimum is normalized by observed days (with configured minimum still reported) to avoid false readiness negatives during partial windows.\n- Go-live blocker logic now keys edge on promotion-gate safety (`edge_promotion_gate_fail`) rather than strict edge component `pass/watch` state.\n- Enforcement should be flipped only when `/api/ops/go-live-readiness` shows `go_live_ready=true` and no blockers.\n\n## Scheduler Ownership Runbook\n\nTarget ownership is GitHub Actions (`Daily PXI Refresh`) only. Keep Cloudflare cron enabled during hardening, then cut over after stability validation.\n\n### 72-hour Shadow Procedure\n\n1. Keep Cloudflare and GitHub schedulers active.\n2. Require 12 consecutive successful scheduled GitHub runs (4/day over 72 hours) with zero critical SLA violations.\n3. Disable Cloudflare cron triggers for:\n   - `pxi-api-production`\n   - `pxi-api`\n4. Re-verify Cloudflare schedules are empty and GitHub continues refreshing data.\n\n## Development\n\n```bash\n# Install dependencies\nnpm install\n\n# Set up environment\ncp .env.example .env\n# Edit .env with your credentials\n\n# Run daily data refresh\nnpm run cron:daily\n\n# Start frontend dev server\ncd frontend \u0026\u0026 npm run dev\n\n# Deploy main worker\ncd worker \u0026\u0026 npx wrangler deploy --env production\n\n# Deploy signals worker\ncd signals \u0026\u0026 npm install \u0026\u0026 npx wrangler deploy --env production\n```\n\n### Launch Readiness Smoke Checks\n\nUse these checks after deployment or before releases:\n\n```bash\n# Frontend route checks\ncurl -I https://pxicommand.com/\ncurl -I https://pxicommand.com/spec\ncurl -I https://pxicommand.com/alerts\ncurl -I https://pxicommand.com/guide\ncurl -I https://pxicommand.com/signals\ncurl -I https://pxicommand.com/signals/latest\n\n# API checks (canonical host)\ncurl -I https://api.pxicommand.com/health\ncurl -I https://api.pxicommand.com/api/pxi\ncurl -I https://api.pxicommand.com/api/alerts\ncurl -I https://api.pxicommand.com/api/signal\ncurl -I https://api.pxicommand.com/api/diagnostics/edge?horizon=all\n\n# CORS preflight check\ncurl -X OPTIONS https://api.pxicommand.com/api/refresh \\\n  -H \"Origin: https://pxicommand.com\" \\\n  -H \"Access-Control-Request-Method: POST\" \\\n  -H \"Access-Control-Request-Headers: Content-Type, Authorization, X-Admin-Token\"\n\n# Backfill validation check (expect 400/401 depending on auth mode)\ncurl -X POST https://api.pxicommand.com/api/backfill \\\n  -H \"Content-Type: application/json\" \\\n  -d '{\"start\":\"invalid-date\",\"limit\":\"bad\"}'\n```\n\nTemporary rollback path remains available via `https://pxi-api.novoamorx1.workers.dev` during cutover.\n\n### Signals Worker Route Check\n\nConfirm the route is attached and active:\n\n```bash\ncd /Users/scott/pxi/signals\nnpx wrangler whoami\nnpx wrangler deployments list --name pxi-signals --env production\n```\n\nIf `/signals` is unreachable (404), verify:\n\n1. `signals/wrangler.toml` has `pxicommand.com/signals` and `pxicommand.com/signals/*` route entries.\n2. The worker deploy succeeds after route changes.\n3. The `pxi-signals` worker has active production bindings (`d1`, `r2`, `kv`) for `pxicommand.com`.\n\n### Signals Development\n\n```bash\ncd signals\n\n# Run tests (258 tests)\nnpm test\n\n# Generate offline report (uses sample data)\nnpm run offline\n\n# Deploy to Cloudflare\nnpx wrangler deploy --env production\n\n# Set admin token for manual runs\nnpx wrangler secret put ADMIN_RUN_TOKEN\n```\n\n### ML Model Training\n\n```bash\n# Install Python dependencies\ncd ml \u0026\u0026 pip install -r requirements.txt\n\n# Train XGBoost models (requires WRITE_API_KEY for data export)\nexport WRITE_API_KEY=your_key\npython train_xgboost.py\n\n# Train LSTM models (requires PyTorch)\npip install torch\npython train_lstm.py\n\n# Upload models to Cloudflare KV\nnpx wrangler kv key put \"pxi_model\" --path=pxi_model_compact.json \\\n  --namespace-id=88901ff0216a484eb81b8004be0f5aea --remote\nnpx wrangler kv key put \"pxi_lstm_model\" --path=pxi_lstm_compact.json \\\n  --namespace-id=88901ff0216a484eb81b8004be0f5aea --remote\n```\n\n**XGBoost** (`train_xgboost.py`):\n- Engineers 36 features (momentum, dispersion, extremes, rolling stats)\n- Gradient boosted trees for 7d/30d PXI change prediction\n- Exports to JSON (318KB compact)\n\n**LSTM** (`train_lstm.py`):\n- Uses 20-day sequences of 12 features (PXI, categories, VIX, dispersion)\n- Single-layer LSTM with 32 hidden units\n- Exports weights to JSON for edge inference (239KB compact)\n\n### MCP Server Setup\n\n```bash\n# Build the MCP server\ncd mcp-server \u0026\u0026 npm install \u0026\u0026 npm run build\n```\n\n**Claude Desktop** - add to `~/Library/Application Support/Claude/claude_desktop_config.json`:\n```json\n{\n  \"mcpServers\": {\n    \"pxi\": {\n      \"command\": \"node\",\n      \"args\": [\"/path/to/pxi/mcp-server/dist/index.js\"]\n    }\n  }\n}\n```\n\n**Available Tools:**\n| Tool | Description |\n|------|-------------|\n| `get_pxi` | Current score, categories, trend |\n| `get_predictions` | ML ensemble forecasts (7d/30d) |\n| `get_similar_periods` | Vector similarity search |\n| `get_signal` | Risk allocation signal |\n| `get_regime` | Market regime analysis |\n| `get_market_context` | Comprehensive agent context |\n| `get_history` | Historical scores |\n\n## Environment Variables\n\n| Variable | Description |\n|----------|-------------|\n| `FRED_API_KEY` | FRED API key ([get one free](https://fred.stlouisfed.org/docs/api/api_key.html)) |\n| `WRITE_API_KEY` | API key for write operations |\n| `WRITE_API_URL` | Worker API URL for cron |\n\n### Cloudflare Secrets (set via wrangler)\n```bash\nnpx wrangler secret put WRITE_API_KEY\nnpx wrangler secret put FRED_API_KEY\n```\n\n## Database Schema\n\n### Core Tables\n- `indicator_values` - Raw indicator data from sources\n- `indicator_scores` - Normalized 0-100 scores\n- `category_scores` - Category-level aggregations\n- `pxi_scores` - Final composite scores\n\n### ML Tables\n- `prediction_log` - Predictions vs actual outcomes\n- `model_params` - Tunable model parameters\n- `period_accuracy` - Historical period prediction quality\n- `market_embeddings` - Vector embeddings for similarity search\n\n### Signal Tables\n- `pxi_signal` - Risk allocation signals\n- `alert_history` - Generated alerts\n- `backtest_results` - Strategy performance\n\n## Data Sources\n\n- **FRED** - Federal Reserve economic data (liquidity, credit spreads, yields)\n- **Yahoo Finance** - Market prices, ETFs, VIX, currencies\n- **DeFiLlama** - Stablecoin market cap\n- **Coinglass** - BTC funding rates\n- **CNN** - Fear \u0026 Greed index\n\n## License\n\nMIT\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fscottdhughes%2Fpxi-command","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fscottdhughes%2Fpxi-command","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fscottdhughes%2Fpxi-command/lists"}