# 888 Stock Quant Platform - Full System Specification

> 專業級台美股深度學習與多維量化決策平台全量架構規格、數學模型定義與資料庫字典。

> ⚠️ **Continuous Feature Evolution Active**: Caller LLM Agents should dynamically fetch the latest live specifications from `https://stockdata.david888.com/llms.txt` and `https://stockdata.david888.com/skill` before execution to leverage newly released models, tools, and endpoints.

## 1. System Architecture & Core Philosophy
888 Stock Quant 定位為「**盤前買進決策指南 (Pre-Market Buy Guide)**」與「**純股市時序資料庫**」，每天於台股開盤前 (08:00 TWN / 00:00 UTC) 與美股開盤前 (20:30 TWN / 12:30 UTC) 自動運算完成並推播決策。系統透過 `--market auto` 實施時段防護，白天專注台股、夜間專注美股，非指定全市場時杜絕算力浪費。

### Core Quantitative Pillars:
1. **宏觀門檻與大盤風控 (Macro & Market Regime)**:
   - 🇹🇼 台股市場：加權指數 (`^TWII`) 站穩 MA60/MA20 + 費城半導體 (`^SOX`) + VIX 國際連動。
   - 🇺🇸 美股市場：S&P 500 (`SPY`) 站穩 MA60 + VIX 恐慌指數 + 費城半導體動態風控。
   - 曝險比例：全面多頭 (100%)、多頭回調 (85%)、避險防禦 (30~50%)、極度恐慌 (0%)。當費半破季線時，科技股部位強制上限 30%。
2. **波段策略 - 玄鐵重劍 (Xuantie Technical Pullback)**:
   - 順大勢：MA60 > MA120 或斜率向上。
   - 逆小勢：價格回調至季線/半年線支撐帶（價格在 MA60/120 之 ±3% 內，且未跌破超過 -1%）。
3. **時序基礎大模型 - Mistral Timestral-209M (Timestral 5-Day Forecast & Monte Carlo Bands)**:
   - 採用 Mistral AI 209M 參數架構開源時序基礎大模型。
   - 輸入過去 96+ 交易日高精度 OHLCV 價格序列，自回歸產生未來 5 日目標價路徑。
   - 結合蒙地卡羅抽樣輸出 P10 (下行防守位)、P50 (中位預期) 與 P90 (樂觀目標位)。
4. **時序基礎大模型 - Google TimesFM (TimesFM 5-Day Forecast & Quantiles)**:
   - 採用 Google Research 預訓練 Decoder 架構時序基礎大模型 (TimesFM 2.0 200M / 2.5 500M)。
   - 輸出 1~5 日預測目標價軌跡，並以設定 horizon 的最後一天計算 P10 (下行防守位)、P50 (中位預期) 與 P90 (上行參考位)。
   - 真實盈虧比 (Risk/Reward Ratio): $RR = \\frac{P_{50,h} - P_0}{P_0 - P_{10,h}}$。當 $RR \\ge 1.5$ 且 horizon P50 $> P_0$ 時判定為高勝率看漲標的；次日潛力僅供診斷。
5. **籌碼策略 - 三大法人鎖碼 (TWSE Institutional Accumulation)**:
   - 分析外資、投信、自營商買賣超。篩選「投信連買 >= 3 天」或「土洋合買（外資與投信同向買超）」主力標的。
6. **產業板塊資金輪動 (Sector Rotation)**:
   - 追蹤 7 大核心板塊 10D (40%) + 15D (30%) + 20D (30%) 動量加權資金流，鎖定市場前 3 大主流板塊。
7. **多維交集共振架構 (Multi-Model Resonance Hierarchy)**:
   - **多模型看多共識**: TimesFM、Timestral、MOIRAI-2 等多時序大模型波形共識，同向看漲。
   - **玄鐵均線波段**: 「順大勢、逆小勢」，MA60/120 多頭排列下精準回踩支撐之波段買點。
   - **三大法人合買**: 外資與投信 5 日同步買超。
   - **高盈虧比**: 時序大模型盈虧比 $RR \\ge 1.5$。

## 2. Mathematical Formulations

### 2.1 TimesFM Quantile Risk/Reward Ratio
給定現價 $P_0$、未來 5 日 TimesFM 中位數預測價 $P_{50}$、下行 10% 分位數價格 $P_{10}$：
$$\\text{Potential (\\%)} = \\frac{P_{50} - P_0}{P_0} \\times 100\\%$$
$$\\text{Risk/Reward Ratio} = \\begin{cases} \\frac{P_{50} - P_0}{P_0 - P_{10}}, & \\text{if } P_{50} > P_0 \\text{ and } P_0 > P_{10} \\\\ 0.0, & \\text{otherwise} \\end{cases}$$

### 2.2 Composite Weighted Score
綜合評分以動態權重計算，若大盤處於降級狀態則折減曝險比例：
$$\\text{Score}_{raw} = \\frac{\\sum_{s} w_s \\cdot S_s}{\\sum_s w_s}$$
$$\\text{Score}_{final} = \\text{Score}_{raw} \\times \\text{Exposure}$$

## 3. DuckDB Time-Series Data Tables

- `tw_daily_bars`:
  `date` (DATE), `ticker` (VARCHAR), `raw_code` (VARCHAR), `name` (VARCHAR), `open` (DOUBLE), `high` (DOUBLE), `low` (DOUBLE), `close` (DOUBLE), `volume` (BIGINT), `market` (VARCHAR)
- `tw_institutional_daily`:
  `date` (DATE), `ticker` (VARCHAR), `raw_code` (VARCHAR), `name` (VARCHAR), `foreign_net` (BIGINT), `trust_net` (BIGINT), `dealer_net` (BIGINT), `total_net` (BIGINT), `foreign_ratio` (DOUBLE), `market` (VARCHAR)
- `tw_broker_trades`:
  `date` (DATE), `ticker` (VARCHAR), `broker_name` (VARCHAR), `buy_shares` (BIGINT), `sell_shares` (BIGINT), `net_shares` (BIGINT)
- `predictions`:
  `index_name` (VARCHAR), `model_name` (VARCHAR), `strategy_type` (VARCHAR), `ticker` (VARCHAR), `current_price` (DOUBLE), `predicted_price` (DOUBLE), `potential` (DOUBLE), `ma5` (DOUBLE), `ma10` (DOUBLE), `ma60` (DOUBLE), `ma120` (DOUBLE), `ma250` (DOUBLE), `pullback_type` (VARCHAR), `pe` (DOUBLE), `pb` (DOUBLE), `forward_pe` (DOUBLE), `ev_ebitda` (DOUBLE), `period` (VARCHAR), `timestamp` (TIMESTAMP), `macro_regime` (VARCHAR), `trust_net_5d` (DOUBLE), `foreign_net_5d` (DOUBLE), `tags` (VARCHAR)
- `earnings_calls`:
  `id` (VARCHAR), `market` (VARCHAR: TW/US/JP/KR/OTHER), `ticker` (VARCHAR), `name` (VARCHAR), `call_date` (VARCHAR: YYYY-MM-DD), `call_time` (VARCHAR), `timezone` (VARCHAR), `meeting_type` (VARCHAR), `location` (VARCHAR), `webcast_url` (VARCHAR), `presentation_url` (VARCHAR), `transcript_url` (VARCHAR), `language` (VARCHAR), `eps_estimate` (DOUBLE), `eps_actual` (DOUBLE), `revenue_estimate` (DOUBLE), `revenue_actual` (DOUBLE), `is_weight_stock` (BOOLEAN), `financial_period` (VARCHAR), `guidance_summary` (VARCHAR), `guidance_outlook` (VARCHAR), `guidance_margin` (VARCHAR), `guidance_capex` (VARCHAR), `guidance_qa` (VARCHAR), `source` (VARCHAR)
- `macro_snapshots`:
  `category` (VARCHAR: PRIMARY KEY, 如 fed_rate_monitor, investing_summary, commodities_summary, economic_calendar, polymarket_macro_sentiment), `data_json` (VARCHAR: JSON 結構), `source` (VARCHAR), `updated_at` (VARCHAR: YYYY-MM-DD HH:MM:SS)
- `discovery_candidates`:
  `ticker`, `market`, `name`, `theme_id`, `theme_name`, `total_score` (DOUBLE), `recommendation` (VARCHAR), `review_status`, `in_pool` (BOOLEAN), 7-factor breakdown scores, `catalyst_summary`, `us_anchor`, `run_id`, `as_of`
- `discovery_papers`:
  `paper_id`, `title`, `authors`, `abstract`, `category`, `published_date`, `bottleneck_tag`, `related_tickers`, `url`, `significance_score`, `as_of`
- `discovery_signals`:
  `signal_id`, `ticker`, `theme_id`, `source_type`, `title`, `content`, `url`, `sentiment_score`, `detected_at`, `as_of`
- `discovery_history`:
  `run_id`, `as_of`, `total_candidates`, `propose_add_count`, `observe_count`, `already_in_pool_count`, `paper_count`, `signal_count`, `avg_total_score`

## 4. REST API Endpoints Specification

### 4.1 Quantitative Strategies
- `GET /api/v1/predictions/resonance?index_name=台灣50&limit=30`: 查詢雙時序大模型共振與多策略焦點推薦清單。
- `GET /api/v1/predictions/timestral/top-bullish?index_name=...&limit=20`: Mistral Timestral 5日看漲榜與蒙地卡羅區間。
- `GET /api/v1/predictions/timestral/top-bearish?index_name=...&limit=20`: Mistral Timestral 5日看跌避險榜。
- `GET /api/v1/predictions/timesfm/top-bullish?index_name=...&limit=20`: Google TimesFM 5日看漲榜與盈虧比。
- `GET /api/v1/predictions/timesfm/top-bearish?index_name=...&limit=20`: Google TimesFM 5日看跌避險榜。
- `GET /api/v1/predictions/xuantie?index_name=...&limit=20`: 玄鐵重劍 MA60/120 波段買點。
- `GET /api/v1/predictions/latest?index_name=...&limit=50`: 最新日報完整批次快照。
- `GET /api/v1/predictions/history/{ticker}?limit=30`: 單一標的歷史預測軌跡與籌碼時序。
- `GET /api/v1/predictions/resolve/{query}`: 模糊匹配股票名稱並解析為標準代號。

### 4.2 Macro & Investing Catalysts
- `GET /api/v1/macro/latest?market=tw|us`: 大盤風控與建議曝險比例。
- `GET /api/v1/macro/investing/summary`: 整合 CME FedWatch、美股財報、大宗商品與財經日曆。
- `GET /api/v1/macro/investing/fed-rate`: 聯準會利率決策機率分布與 FOMC 倒數。
- `GET /api/v1/macro/investing/earnings-calendar`: 美股重量級企業財報公布行事曆。
- `GET /api/v1/macro/investing/commodities`: 黃金、銅、WTI 原油行情與週期漲跌。
- `GET /api/v1/macro/investing/economic-calendar`: 全球重磅總經行事曆（CPI、非農等）。
- `GET /api/v1/macro/polymarket/sentiment`: Polymarket 真金白銀預測市場宏觀情緒（FOMC 利率、地緣關稅、科技巨頭、經濟衰退）；機率為 0~100 百分比，並回傳 `success`/`stale`/`error` 狀態。

### 4.3 Institutional & Company Profile
- `GET /api/v1/market/institutional/top?order_by=total_net&limit=30`: 三大法人買賣超排行。
- `GET /api/v1/market/broker/summary/{ticker}?days=20`: 券商關鍵分點主力累計買賣超。
- `GET /api/v1/market/company-profile?ticker=2330.TW`: 2MD 繁體中文公司簡介與即時新聞。
- `POST /api/v1/market/company-profiles/batch`: 並發批次預載多支股票之公司營運摘要。

### 4.4 Global Corporate Earnings Calls & Guidance (法說會與官方指引)
- `GET /api/v1/earnings-call/upcoming?market=ALL&days=14&is_weight_stock=true&limit=50`: 查詢近期跨市場法說會，支援 market (ALL/TW/US/JP/KR/OTHER)、雙時區換算與倒數天數。
- `GET /api/v1/earnings-call/calendar?year=2026&month=10&market=ALL`: 月度法說會日程聚合統計與每日公司摘要。
- `GET /api/v1/earnings-call/{ticker}?limit=20`: 個股歷史法說會歷程、官方財測指引 (營收/毛利率/資本支出) 與簡報 PDF 原始連結。
- `POST /api/v1/earnings-call/sync`: 觸發背景非同步多視窗跨市場全量法說會同步。

### 4.5 Watchlist, Live Sessions & Signal Alignment
- `GET /api/v1/watchlist?profile_id=default`: 查詢使用者本地 DuckDB 持久化之自選股清單（附帶最新預測）。
- `POST /api/v1/watchlist`: 新增自選股（生產環境需 WATCHLIST_API_KEY 金鑰驗證）。
- `DELETE /api/v1/watchlist/{ticker}`: 刪除自選股（生產環境需 WATCHLIST_API_KEY 金鑰驗證）。
- `GET /api/v1/market/calendar/sessions`: 查詢台股、美股與日股即時五態交易時段與東京午休倒數。
- `GET /api/v1/predictions/alignment/{ticker}`: 查詢多源量化訊號一致度卡（模型、籌碼、情報、前沿雷達共識）。
- `GET /api/v1/alerts`: 查詢使用者之量化價位與動態分位數告警清單。
- `POST /api/v1/alerts`: 新增量化告警（生產環境需 WATCHLIST_API_KEY 金鑰驗證）。
- `POST /api/v1/alerts/check`: 觸發量化到價告警批次巡檢與原子冷卻推播（生產環境需 WATCHLIST_API_KEY 金鑰驗證）。

### 4.6 Public SEO, Dynamic Sitemap & Crawler Standards
- `GET /s/{ticker}`: 免登入公開個股量化檔案 (SSR & 結構化 JSON-LD，強制正則檢驗與 XSS 跳脫)。
- `GET /sitemap.xml`: 全站動態 XML 網站地圖 (1 小時記憶體快取，lastmod 取實際交易日)。
- `GET /robots.txt`: 搜尋引擎爬蟲指引文件。

## 5. Model Context Protocol (MCP) Server
- FastMCP Server: `mcp_server.py`
- WebMCP Endpoint: `/mcp/sse`
- WebMCP Manifest: `/.well-known/mcp.json`
- Tools (32 Native Tools): `get_market_macro_regime`, `screen_quant_stocks`, `get_triple_resonance_stocks`, `get_timestral_top_predictions`, `get_timesfm_top_predictions`, `get_moirai_top_predictions`, `get_xuantie_pullback_stocks`, `get_stock_history`, `get_latest_market_snapshot`, `get_top_institutional_flows`, `get_broker_trades_for_stock`, `get_company_profile`, `get_company_network`, `get_fed_rate_monitor`, `get_us_earnings_calendar`, `get_economic_calendar`, `get_commodities_summary`, `resolve_stock_ticker`, `get_polymarket_macro_sentiment`, `get_clef_stock_verdict`, `get_upcoming_earnings_calls`, `get_ticker_earnings_calls`, `open_company_network`, `get_company_tenders`, `get_industry_chain`, `get_discovery_signals`, `get_model_performance_scorecard`, `get_watchlist`, `get_market_live_sessions`, `get_signal_alignment`, `get_portfolio_risk_xray`, `get_canary_loader_health`.

## 6. Recommended 4-Step Agent Trading Workflow
1. **檢查宏觀風控**: 呼叫 `get_market_macro_regime()` 決定整體建議曝險 (0%~100%)。
2. **多維量化自訂篩選**: 呼叫 `screen_quant_stocks()`，依照交易方向 (bullish/bearish)、時序模型多選 (timesfm, timestral, moirai)、PE估值、預期空間與核心因子精準挑選標的。
3. **模型預測與績效驗證**: 呼叫 `get_model_performance_scorecard()` 與時序模型獨立排行 (`get_timesfm_top_predictions`, `get_timestral_top_predictions`, `get_moirai_top_predictions`)。
4. **產業鏈與個股確認**: 呼叫 `get_industry_chain()`、`get_stock_history()` 與 `get_company_profile()` 檢視產業鏈拓撲、近期走勢與法人籌碼。

Specification Conformance: https://llmstxt.org/
