# 888 Stock Quant Platform - Full System Specification

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

## 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. **短線預測 - LSTM 深度學習 (LSTM Next-Day Forecast)**:
   - 輸入過去 60 日 OHLCV 與技術指標，2 層雙向 LSTM 輸出次日收盤價預測與漲跌幅潛力。
4. **時序基礎大模型 - Google TimesFM (TimesFM 5-Day Forecast & Quantiles)**:
   - 採用 Google Research 預訓練 Decoder 架構時序基礎大模型 (TimesFM 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)**:
   - 👑 **四重共振**: 玄鐵技術買點 ∩ 法人鎖碼 ∩ LSTM 看漲 ∩ TimesFM 看漲 (勝率頂級)。
   - 🏆 **三重共振**: 玄鐵技術買點 ∩ 法人鎖碼 ∩ (LSTM ∪ TimesFM) 看漲 ∩ 估值合理 (PE<25 / PB<3.5)。
   - 🔮 **雙ML共振**: LSTM ∩ TimesFM 同步看漲（微觀記憶 ∩ 宏觀預訓練波形共振）。
   - ⚖️ **高盈虧比**: TimesFM 盈虧比 $RR \ge 2.0$。

## 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)

## 4. REST API Endpoints Specification

### 4.1 Quantitative Strategies
- `GET /api/v1/predictions/resonance?index_name=台灣50&limit=30`: 查詢三重/四重共振推薦清單。
- `GET /api/v1/predictions/timesfm/top-bullish?index_name=...&limit=20`: TimesFM 5日看漲榜與盈虧比。
- `GET /api/v1/predictions/timesfm/top-bearish?index_name=...&limit=20`: TimesFM 5日看跌避險榜。
- `GET /api/v1/predictions/lstm/top-bullish?index_name=...&limit=20`: LSTM 次日看漲榜。
- `GET /api/v1/predictions/lstm/top-bearish?index_name=...&limit=20`: LSTM 次日看跌榜。
- `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`: 並發批次預載多支股票之公司營運摘要。

## 5. Model Context Protocol (MCP) Server
- FastMCP Server: `mcp_server.py`
- WebMCP Endpoint: `/mcp/sse`
- WebMCP Manifest: `/.well-known/mcp.json`
- Tools (16 Native Tools): `get_market_macro_regime`, `get_triple_resonance_stocks`, `get_timesfm_top_predictions`, `get_lstm_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_fed_rate_monitor`, `get_us_earnings_calendar`, `get_economic_calendar`, `get_commodities_summary`, `resolve_stock_ticker`, `get_polymarket_macro_sentiment`.

## 6. Recommended 4-Step Agent Trading Workflow
1. **檢查宏觀風控**: 呼叫 `get_market_macro_regime()` 決定整體建議曝險 (0%~100%)。
2. **首選共振焦點**: 呼叫 `get_triple_resonance_stocks()`，優先挑選含 `👑四重共振`、`🔮雙ML共振`、`高盈虧比` 標的。
3. **分流補充選股**:
   - 波段投資人: `get_xuantie_pullback_stocks()` (MA60/120 回踩買點)。
   - 大模型動量投資人: `get_timesfm_top_predictions()` (5日盈虧比優勢)。
   - 短線爆發投資人: `get_lstm_top_predictions()` (次日動量)。
4. **個股確認與防守**: 呼叫 `get_stock_history()` 與 `get_company_profile()` 檢視近期走勢、法人籌碼支撐與公司基本面。

Specification Conformance: https://llmstxt.org/
