[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7ECWVQHZPX9JRQ752NTSHP9":3,"skill-same:01M7ECWVQHZPX9JRQ752NTSHP9":49},{"skillNo":4,"name":5,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":20,"frontMatter":21,"refName":22,"commitSha":23,"skillDirectory":24,"forksCount":13,"repositoryHtmlUrl":25,"repositoryHomepageUrl":6,"ownerHtmlUrl":26,"ownerBlogUrl":6,"ownerDescription":27,"updatedAt":28,"install":29,"resources":42},"01M7ECWVQHZPX9JRQ752NTSHP9","quant-hq-operations-console",null,"jonahthan433\u002FCortexOS","jonahthan433","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F211465495?v=4","01M7ECH9HPHGA89DCXHHJBTS3C","jonah.ai","01M7ECH9JCEM45DZMWPT7148S1",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002Fmlops\u002Fquant-hq-operations-console\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"# quant-hq-operations-console\n\n# Quant Lab HQ Operations Console\n\nCinematic command-center for monitoring a 12-room \u002F 24-agent quantitative research organization. All visual state comes from real PostgreSQL data via SSE — never simulated.\n\n## Architecture\n\n### Backend (CT106, \u002Fopt\u002Fcortexquant)\n| File | Purpose |\n|---|---|\n| `src\u002Fquant_hq\u002Frooms_schema.py` | SQLAlchemy models: ResearchAgent, ResearchMessage, ResearchExperiment, ResearchAuditLog, ResearchTask, ResearchPromotion, RoomType, PipelineStage |\n| `src\u002Fquant_hq\u002Frooms.py` | Room classes, ChiefQuantDirector, MessageBus, MemoryStore, QuantHQOrchestrator singleton |\n| `src\u002Fquant_hq\u002Fevents.py` | SSE router with `_get_full_state()` |\n| `src\u002Fquant_hq\u002Forchestrator.py` | Orchestration helpers |\n| `src\u002Fquant_hq\u002Fschema.py` | Canonical enums (ResearchStage, AgentRole, TaskStatus) |\n| `src\u002Fquant_hq\u002Falpha_pipeline.py` | 12-step alpha extraction: demeaning, variance, normalization, truncation, cross-sectional demean, expected return, orthogonalization, weighting, combination |\n| `src\u002Fquant_hq\u002Fmonitor.py` | DecayDetector (rolling Sharpe + sustained-period flagging), HMRegimeDetector (2-state Gaussian HMM + forward algorithm), PermissionGraph (room write\u002Fread permissions), MonitoringService (orchestration + feedback loop) |\n| `src\u002Fingestion\u002Ftg_schema.py` | Raw message storage, parsed signal storage, backfill checkpoints, metrics |\n| `src\u002Fingestion\u002Ftg_parser.py` | v2.0.0 — parses CKPscanner Scout Opportunity lists (symbol, direction, RSI15\u002F4H, TSI15\u002F4H, divergence, funding) |\n| `src\u002Fingestion\u002Ftg_service.py` | Telethon MTProto ingester with pagination + real-time listener |\n| `src\u002Fingestion\u002Ftg_publisher.py` | Routes parsed signals → creates ALTCOIN_SIGNAL_RECEIVED events → MessageBus → 10 rooms |\n| `src\u002Fapi\u002Ftg_routes.py` | Telegram ingestion endpoints (health, signals, stats, reparse) |\n| `src\u002Fapi\u002Fmonitoring_routes.py` | Monitoring endpoints (decay, regime, DSR, permissions) |\n| `src\u002Fapi\u002Falpha_routes.py` | 12-step validation and combination endpoints |\n| `main.py` | Entry point; starts scheduler, ingester, publisher, API |\n\n### Frontend (`\u002Fconsole`)\n- Canvas facility map: Chief Quant Director center, 12 rooms in a circle\n- Agent dots on rings inside each room\n- Data packets animate along conduits when messages flow\n- SSE-driven: no polling, no fake animation\n\n## 12-Step Alpha Extraction Pipeline\n\nEvery signal must pass through all 12 steps before any further action. From the RuujSs \"Unified Framework for Alpha Extraction and Signal Combination\":\n\n| Step | Math | What |\n|---|---|---|\n| 1 | `X = R - mean(R)` | Linear demeaning (drift removal) |\n| 2 | `σ² = mean(X²)` | Variance estimation |\n| 3 | `Y = X \u002F σ` | Return normalization (unit variance) |\n| 4 | `Y[:M-1]` | Time-series truncation |\n| 5 | `Λ = Y - mean(Y across N)` | Cross-sectional demeaning |\n| 6 | `Λ[:M-1]` | Final trimming |\n| 7 | `E = mean(R[-d:])` | Expected return (forward-looking) |\n| 8 | `E_norm = E \u002F σ` | Return normalization |\n| 9 | `E_norm = β·Λ + ε` | Residual extraction (orthogonalize) |\n| 10 | `w = ε \u002F σ` | Signal weighting (inverse vol) |\n| 11 | `Σ\\|w\\| = 1` | Weight normalization (gross exposure = 1) |\n| 12 | `Combined = Σ w(i)·S_i` | Combined signal |\n\nValidation runs in `AlphaExtractionPipeline.validate_signal()` → returns `(passed, results, output)`. Combine N signals via `combine_signals()`.\n\n## Monitoring System\n\n### DecayDetector\nRolling Sharpe with sustained-period flagging. A single bad window is variance. N consecutive bad windows is a signal. From the RuujSs alpha engine article:\n\n```python\nclass DecayDetector:\n    def __init__(self, window_size=20, sustained_periods=3, decay_threshold=0.5):\n        ...\n    def check_decay(self, research_id, live_returns) -> Tuple[bool, Dict]:\n        ...\n```\n\n### HMRegimeDetector\nTwo-state Gaussian HMM with forward algorithm for regime probability. Secondary correlation check catches what the model alone misses.\n\n```python\nclass HMRegimeDetector:\n    def __init__(self, n_states=2): ...\n    def fit(self, returns) -> bool: ...\n    def predict(self, returns) -> Dict: ...  # {fitted, regime, confidence, divergence}\n```\n\n### PermissionGraph\nEnforces room-to-room write\u002Fread permissions at the data level. Maps each room to the set of statuses it can write and read.\n\n```python\nclass PermissionGraph:\n    WRITE_PERMISSIONS = {RoomType.QUANT_RESEARCH: {\"CANDIDATE\"}, ...}\n    READ_PERMISSIONS = {RoomType.QUANT_RESEARCH: {\"CANDIDATE\", \"APPROVED\", \"FLAGGED\"}, ...}\n    def can_write(self, room, status) -> bool: ...\n    def can_read(self, room, status) -> bool: ...\n```\n\n### MonitoringService\nOrchestrates decay + HMM + feedback. When decay or regime divergence is detected, sends HIGH priority messages to the research room.\n\n```python\nclass MonitoringService:\n    async def check_experiment(self, research_id, returns, baseline_sharpe) -> Dict: ...\n    async def _alert(self, research_id, alert_type, data): ...\n```\n\n## Deflated Sharpe Ratio\n\nMultiple-testing correction for strategy validation. Converts Sharpe into a probability that the strategy is not overfit.\n\n```\ndef deflated_sharpe_ratio(sharpe, n_observations, skew=0.0, kurtosis=3.0, n_trials=1, alpha=0.05) -> Dict:\n    # Returns {dsr, probability, pass, expected_max_sr, threshold, n_trials}\n```\n\nUses `scipy.stats.norm` (Bailey & Lopez de Prado expected max SR under null).\n\n## SSE Protocol\n\n\u002Fapi\u002Fquant-hq\u002Fevents emits named SSE events:\n- `state` — full state snapshot\n- `audit_log` — incremental new audit events\n- `heartbeat` — timestamp ping\n\nClient uses `addEventListener` for named events. `onmessage` does NOT fire for named SSE events.\n\n## Common pitfalls\n\n- **Agent duplication on restart**: `initialize()` calls `register_agent()` unconditionally — add a guard to check for existing agent before insert.\n- **PSQL table name mismatch**: model `__tablename__` may be singular (`research_audit_log`) while raw psql uses plural.\n- **Port bind failure on restart**: `fuser -k 8080\u002Ftcp` BEFORE restarting, or get `[Errno 98] address already in use`.\n- **Shell quoting kills JSON**: nested ssh\u002Fpct\u002Fbash -c with curl -d JSON mangles. Write to file, use `curl --data-binary @file`.\n- **State endpoint wrapper**: `\u002Fapi\u002Fquant-hq\u002Fstate` returns `{state: {...}}` — console accesses `data.state`.\n- **Room initialization is lazy**: only 5 of 12 rooms registered in `initialize()`. Add missing room classes + init calls + agent registrations.\n- **AsyncSessionLocal**: always use async with context manager.\n- **`scipy` must be in the venv, not system**. `pip install scipy` inside the CT106 venv (`\u002Fopt\u002Fcortexquant\u002Fvenv`), not the host. System pip won't put it where the FastAPI app can import it.\n- **`python-multipart` for FastAPI POST bodies**. FastAPI requires it for form data \u002F JSON body parsing. `pip install python-multipart` in the venv.\n- **`numpy.bool_` is not JSON-serializable**. Always wrap in `bool()` when returning from an API endpoint (e.g. `\"pass\": bool(probability >= threshold)`).\n- **Stale `__pycache__`**. Always `find \u002Fopt\u002Fcortexquant -name __pycache__ -exec rm -rf {} +` after patching `.py` files, then restart.\n- **`.env` vs `pydantic-settings`**. `settings.TELEGRAM_API_ID` reads `.env` but `os.environ.get(\"TELEGRAM_API_ID\")` returns None until you manually load `.env` (e.g. for the Telethon ingester constructor).\n- **Telegram session lock**. Kill the running server BEFORE running auth interactively, or get `sqlite3.OperationalError: database is locked`.\n- **Auth codes expire in ~30s**. Run auth directly on the server (not via background polls) and type code immediately.\n- **uvicorn `serve()` blocks forever — background tasks must precede it**. Any async work that must run for the lifetime of the server (e.g. a 7-day demo trading orchestrator, background reconcilers, cron-like jobs) must be started with `asyncio.create_task(...)` BEFORE `await server.serve()`. Code after `serve()` never executes.\n- **Parser variable-name typo in success branch** — `for p in parsed:` instead of `for p in parsed_results:` silently breaks the main parse path. When patching parser loops, re-read the surrounding 5 lines after every edit to catch a wrong variable name — a NameError in the success branch is silent when the function returns early on `None`.\n- **Scout message regex must handle leading whitespace** — CKPscanner emits lines like ` 1. ALCH-USDT | ...` (2 spaces before number). A pattern `r\"(\\d+)\\.\\s+\"` matches zero lines. Always include `\\s*` before numeric tokens in signal-line regexes.\n- **MAX_POSITION_SIZE_PCT caps risk target** — `position_size = (capital * risk_pct) \u002F |entry - sl|` is then `min(position_size, max_pos)`. If `MAX_POSITION_SIZE_PCT` is too tight (e.g. 5%), the position cap binds and actual risk falls well below `PER_TRADE_RISK_PCT`. Set cap high enough (e.g. 50%) that it doesn't bind for realistic stops.\n- **ML model can have negative R²** — a trained GradientBoosting\u002FRandomForest on financial OHLCV can score R² \u003C 0 (worse than predicting the mean). The validation gate must check `val_r2 > 0` before enabling trades; a saved model file is not proof of predictive power.\n- **Fresh CKPscanner signals arrive in batches** — one Scout message contains 20+ symbols, all with identical timestamps. Deduplicate by symbol (keep highest-confidence) and process as a single signal batch, not 20+ independent trades.\n- **CT services have no systemd\u002Fsupervisorctl** — CT106 runs processes via a custom launcher (`main.py`). After code changes, the reliable restart is `fuser -k 8080\u002Ftcp && PYTHONPATH=\u002Fopt\u002Fcortexquant nohup python main.py > \u002Ftmp\u002Fcq.log 2>&1 & disown`, not `systemctl restart`.\n\n## Dependencies (CT106 venv)\n\n```bash\nsource \u002Fopt\u002Fcortexquant\u002Fvenv\u002Fbin\u002Factivate\npip install numpy scipy scikit-learn hmmlearn telethon python-multipart pytest-asyncio\n```\n\n- `scipy` — for `deflated_sharpe_ratio` (norm.ppf, norm.cdf)\n- `scikit-learn` — for `hmmlearn` dependency\n- `hmmlearn` — Gaussian HMM for regime detection\n- `telethon` — MTProto user-client for Telegram\n- `python-multipart` — FastAPI POST body parsing\n- `pytest-asyncio` — async test support (v0.23.8 works best; v1.4.0 has mode=STRICT issues)\n\n## Regression tests\n\n`tests\u002Ftest_quant_hq_agents.py` — 6 tests. Run:\n```bash\nPYTHONPATH=\u002Fopt\u002Fcortexquant python3 tests\u002Ftest_quant_hq_agents.py\n```\nOr: `bash scripts\u002Fregression_test.sh`\n\n`tests\u002Ftest_tg.py` — 9 parser tests + storage tests:\n```bash\ncd \u002Fopt\u002Fcortexquant && source venv\u002Fbin\u002Factivate && PYTHONPATH=\u002Fopt\u002Fcortexquant python3 -m pytest tests\u002Ftest_tg.py -v\n```\n\n`tests\u002Fpyproject.toml`:\n```toml\n[tool.pytest.ini_options]\nasyncio_mode = \"auto\"\n```\n\n## Deployment (CT106 in LXC)\n\n```bash\n# Kill old process + free port\nssh pve 'pct exec 106 -- bash -c \"fuser -k 8080\u002Ftcp 2>\u002Fdev\u002Fnull; sleep 2\"'\n# Clear stale bytecode\nssh pve 'pct exec 106 -- bash -c \"find \u002Fopt\u002Fcortexquant -name __pycache__ -exec rm -rf {} + 2>\u002Fdev\u002Fnull\"'\n# Restart\nssh pve 'pct exec 106 -- bash -c \"cd \u002Fopt\u002Fcortexquant && source venv\u002Fbin\u002Factivate && PYTHONPATH=\u002Fopt\u002Fcortexquant nohup python main.py > \u002Ftmp\u002Fcq.log 2>&1 & disown\"'\n# Verify\nssh pve 'pct exec 106 -- bash -c \"sleep 4; curl -s http:\u002F\u002Flocalhost:8080\u002Fhealth\"'\nssh pve 'pct exec 106 -- bash -c \"curl -s http:\u002F\u002Flocalhost:8080\u002Fopenapi.json | python3 -c \\\"import sys,json; d=json.load(sys.stdin); print(len(d[\\\\\\\"paths\\\\\\\"].keys()), \\\\\\\"endpoints\\\\\\\"}\\\"\"'\n```\n\n## LIVE_TRADING=false always — research agents isolated from execution.\n\nSSE protocol details (named events, client-side handling): see `references\u002Fsse-protocol.md`\n",{},"main","38b32c99e7ed0b8e215d638e92cfa452c1ec3079","skills\u002Fimported\u002Fmlops\u002Fquant-hq-operations-console","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS","https:\u002F\u002Fgithub.com\u002Fjonahthan433","AI Consultant","2026-10-24 05:13:39",{"source":7,"skillName":5,"commands":30,"prompt":40,"zipAvailable":41},[31,34,37],{"tool":32,"command":33},"npx","npx skills add jonahthan433\u002FCortexOS --skill quant-hq-operations-console",{"tool":35,"command":36},"bunx","bunx skills add jonahthan433\u002FCortexOS --skill quant-hq-operations-console",{"tool":38,"command":39},"pnpm","pnpm dlx skills add jonahthan433\u002FCortexOS --skill quant-hq-operations-console","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002Fmlops\u002Fquant-hq-operations-console\u002FSKILL.md",true,[43],{"path":44,"resourceType":45,"resourceTypeDesc":46,"sizeBytes":47,"sourceHtmlUrl":48},"skill.json","REFERENCE","参考文档",373,"https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fimported\u002Fmlops\u002Fquant-hq-operations-console\u002Fskill.json",[50,56,62,68,74,80],{"skillNo":51,"name":52,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":18},"01M7EDQZDQX3Q8Y7GCQX6KN9V7","opportunity-brief","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fsales\u002Fopportunity-brief\u002FSKILL.md",[],[],{"skillNo":57,"name":58,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":18},"01M7EDQYA0V9Y99VKBREJJ3MRT","morning-intel","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fmorning-intel\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M7EDQVX1JVY0B6PDHKKGM19G","decision-brief","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fdecision-brief\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M7EDQV1GENZAC2SZSD8KZ3GM","weekly-review","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fproductivity\u002Fweekly-review\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":18},"01M7EDQT2KETJ1Y3CGVN9EKW2J","system-health","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fops\u002Fsystem-health\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":7,"ownerLogin":8,"ownerAvatarUrl":9,"ownerAccountNo":10,"ownerDisplayName":11,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":18},"01M7EDQQN2JK3XPWMS1M4T0F3K","backup-restore","https:\u002F\u002Fgithub.com\u002Fjonahthan433\u002FCortexOS\u002Fblob\u002Fmain\u002Fskills\u002Fops\u002Fbackup-restore\u002FSKILL.md",[],[]]