1313 lines
67 KiB
Python
1313 lines
67 KiB
Python
"""Phase 2: TWSE spot OHLCV & TAIFEX Put/Call Ratio supplementer and PTT Stock HITS pipeline."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import csv
|
||
import datetime as dt
|
||
import io
|
||
import json
|
||
import re
|
||
import ssl
|
||
import time
|
||
import urllib.error
|
||
import urllib.parse
|
||
import urllib.request
|
||
from html.parser import HTMLParser
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
import certifi
|
||
import numpy as np
|
||
import pandas as pd
|
||
|
||
PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
||
CLEANED_DIR = PROJECT_ROOT / "data" / "cleaned"
|
||
|
||
|
||
class DataValidationError(RuntimeError):
|
||
"""
|
||
[使用工具] Python 3.9
|
||
[設計目的] 定義資料補齊交叉驗證失敗或 API 欄位結構異常時之專用攔截例外
|
||
[程式說明] 當外部補抓資料與大台隱含指數偏離過大或回傳格式毀損時拋出,阻斷髒資料寫入主表
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 新增資料驗證例外類別防範髒資料覆蓋基準檔
|
||
[輸入參數]
|
||
- message (str): 驗證失敗之具體原因與數值證據
|
||
[輸出結果]
|
||
- return (DataValidationError): 繼承 RuntimeError 的例外實例
|
||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [Pre-mortem] 外部補抓資料與大台隱含指數發生嚴重錯位或異常偏離
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
|
||
|
||
class CircuitBreakerOpenError(RuntimeError):
|
||
"""
|
||
[使用工具] Python 3.9
|
||
[設計目的] 定義爬蟲遭遇連續限流或斷線超限時觸發熔斷的斷路器例外
|
||
[程式說明] 防止 HTTP 429 或 503 持續出現時造成無窮重試與封鎖風險,強制保留完整已抓分頁
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 新增爬蟲斷路器熔斷例外防止限流無窮重試
|
||
[輸入參數]
|
||
- message (str): 斷路器開啟原因與最後一次連線狀態
|
||
[輸出結果]
|
||
- return (CircuitBreakerOpenError): 繼承 RuntimeError 的例外實例
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [Pre-mortem] 爬蟲遭遇 HTTP 429/503 限流或反覆斷線導致程式無窮重試或寫入毀損檔案
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
|
||
|
||
class TwseSpotSupplementer:
|
||
"""
|
||
[使用工具] Python 3.9, urllib, ssl, certifi, pandas
|
||
[設計目的] 從 TWSE 官方端點補抓 2023/06 至 2025/03 真實現貨 OHLC 與成交金額成交量
|
||
[程式說明] 整合 MI_5MINS_HIST 與 FMTQIK 兩支官方 JSON API,並以大台隱含指數守門防止髒資料寫入
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 實作TWSE現貨日線與成交金額補齊與交叉守門類別
|
||
[輸入參數]
|
||
- timeout (int): 單次 HTTP 請求逾時秒數,預設 15 秒
|
||
- sleep_sec (float): 請求間隔禮貌延遲秒數,預設 1.5 秒
|
||
[輸出結果]
|
||
- return (TwseSpotSupplementer): TWSE 現貨補齊器實例
|
||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [正例] 成功解析 TWSE MI_5MINS_HIST 與 FMTQIK 回傳 JSON 並合併成交金額
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
|
||
OHLC_URL = "https://www.twse.com.tw/rwd/zh/TAIEX/MI_5MINS_HIST?date={ym}01&response=json"
|
||
FMTQIK_URL = "https://www.twse.com.tw/rwd/zh/afterTrading/FMTQIK?date={ym}01&response=json"
|
||
|
||
def __init__(self, timeout: int = 15, sleep_sec: float = 1.5) -> None:
|
||
"""
|
||
[使用工具] Python 3.9, ssl, certifi
|
||
[設計目的] 初始化 TWSE 連線逾時、禮貌延遲與 SSL 憑證驗證環境
|
||
[程式說明] 建立載入 certifi 根憑證庫的 SSLContext 與模擬瀏覽器標頭,避免 macOS Python 憑證缺失
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 初始化TWSE連線參數與根憑證驗證環境
|
||
[輸入參數]
|
||
- timeout (int): HTTP 逾時秒數
|
||
- sleep_sec (float): 連續請求間休眠秒數
|
||
[輸出結果]
|
||
- return (None): 設定實例屬性
|
||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [正例] 成功解析 TWSE MI_5MINS_HIST 與 FMTQIK 回傳 JSON 並合併成交金額
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
self.timeout = timeout
|
||
self.sleep_sec = sleep_sec
|
||
self.ssl_ctx = ssl.create_default_context(cafile=certifi.where())
|
||
self.headers = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)"}
|
||
|
||
@staticmethod
|
||
def parse_roc_date_str(roc_date: str) -> str:
|
||
"""
|
||
[使用工具] Python 3.9
|
||
[設計目的] 將 TWSE 回傳的民國日期字串轉換為標準西元 ISO 日期格式
|
||
[程式說明] 拆解 YYY/MM/DD 格式並將年份加上 1911,補齊兩位數月日輸出 YYYY-MM-DD
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 轉換TWSE民國日期字串為標準西元ISO格式
|
||
[輸入參數]
|
||
- roc_date (str): 民國日期字串,例如 '113/10/01'
|
||
[輸出結果]
|
||
- return (str): 西元日期字串,例如 '2024-10-01'
|
||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [正例] 成功解析 TWSE MI_5MINS_HIST 與 FMTQIK 回傳 JSON 並合併成交金額
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
parts = str(roc_date).strip().split("/")
|
||
if len(parts) != 3:
|
||
raise DataValidationError(f"Unexpected TWSE ROC date format: {roc_date!r}")
|
||
year = int(parts[0])
|
||
if year < 1911:
|
||
year += 1911
|
||
return f"{year:04d}-{int(parts[1]):02d}-{int(parts[2]):02d}"
|
||
|
||
@staticmethod
|
||
def parse_twse_number(val: Any) -> float:
|
||
"""
|
||
[使用工具] Python 3.9
|
||
[設計目的] 清理 TWSE 數值字串中的千分位逗號與空白並轉為浮點數
|
||
[程式說明] 移除千分位逗號後強制轉型浮點數,遇到 '--' 或空字串則擲出驗證例外避免靜默錯誤
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 清理千分位逗號並轉換TWSE數值欄位為浮點數
|
||
[輸入參數]
|
||
- val (Any): 含千分位逗號之字串或數值
|
||
[輸出結果]
|
||
- return (float): 乾淨浮點數值
|
||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [Pre-mortem] 官方網站回傳 HTML 錯誤頁、空白資料或欄位數突變
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
cleaned = str(val).replace(",", "").strip()
|
||
if cleaned in ("", "--", "nan", "None"):
|
||
return float("nan")
|
||
try:
|
||
return float(cleaned)
|
||
except ValueError as exc:
|
||
raise DataValidationError(f"Invalid numeric field from TWSE: {val!r}") from exc
|
||
|
||
def fetch_json(self, url: str) -> dict[str, Any]:
|
||
"""
|
||
[使用工具] Python 3.9, urllib, json
|
||
[設計目的] 向 TWSE 端點發送 GET 請求並解析 JSON 回應,防範 HTML 錯誤頁污染
|
||
[程式說明] 擷取回應內容並驗證可解析為字典且不含非預期結構異常,失敗最多重試兩次
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 實作TWSE JSON擷取與非預期HTML錯誤頁攔截
|
||
[輸入參數]
|
||
- url (str): 目標 TWSE API 網址
|
||
[輸出結果]
|
||
- return (dict[str, Any]): 解析後之 JSON 字典物件
|
||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [Pre-mortem] 官方網站回傳 HTML 錯誤頁、空白資料或欄位數突變
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
last_err: Exception | None = None
|
||
for attempt in range(3):
|
||
try:
|
||
req = urllib.request.Request(url, headers=self.headers)
|
||
with urllib.request.urlopen(req, timeout=self.timeout, context=self.ssl_ctx) as resp:
|
||
raw_text = resp.read().decode("utf-8")
|
||
payload = json.loads(raw_text)
|
||
if not isinstance(payload, dict):
|
||
raise DataValidationError("TWSE response JSON root is not an object.")
|
||
return payload
|
||
except (urllib.error.URLError, json.JSONDecodeError, TimeoutError) as exc:
|
||
last_err = exc
|
||
time.sleep(1.5 * (attempt + 1))
|
||
raise DataValidationError(f"Failed to fetch valid JSON from {url}: {last_err}")
|
||
|
||
def parse_twse_month_records(
|
||
self, ohlc_json: dict[str, Any], fmtqik_json: dict[str, Any] | None = None
|
||
) -> pd.DataFrame:
|
||
"""
|
||
[使用工具] Python 3.9, pandas
|
||
[設計目的] 解析單月份 MI_5MINS_HIST 與 FMTQIK JSON 並依西元日期合併成乾淨日線表
|
||
[程式說明] 驗證 stat 為 OK 與必要欄位數量正確,清理數字後以外連結方式合併成交股數與金額
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 解析並合併單月TWSE加權指數OHLC與成交量值資料
|
||
[輸入參數]
|
||
- ohlc_json (dict[str, Any]): MI_5MINS_HIST API 回傳字典
|
||
- fmtqik_json (dict[str, Any] | None): FMTQIK API 回傳字典(選填)
|
||
[輸出結果]
|
||
- return (pd.DataFrame): 含標準化 date、open、high、low、close 及成交量值之資料表
|
||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [正例] 成功解析 TWSE MI_5MINS_HIST 與 FMTQIK 回傳 JSON 並合併成交金額
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
if ohlc_json.get("stat") != "OK" or "data" not in ohlc_json:
|
||
raise DataValidationError(f"Invalid OHLC stat/data: {ohlc_json.get('stat')!r}")
|
||
|
||
ohlc_rows = []
|
||
for row in ohlc_json["data"]:
|
||
if len(row) < 5:
|
||
raise DataValidationError(f"OHLC row has fewer than 5 columns: {row!r}")
|
||
ohlc_rows.append(
|
||
{
|
||
"date": self.parse_roc_date_str(row[0]),
|
||
"open": self.parse_twse_number(row[1]),
|
||
"high": self.parse_twse_number(row[2]),
|
||
"low": self.parse_twse_number(row[3]),
|
||
"close": self.parse_twse_number(row[4]),
|
||
}
|
||
)
|
||
df_ohlc = pd.DataFrame(ohlc_rows)
|
||
|
||
if fmtqik_json and fmtqik_json.get("stat") == "OK" and "data" in fmtqik_json:
|
||
vol_rows = []
|
||
for row in fmtqik_json["data"]:
|
||
if len(row) < 6:
|
||
raise DataValidationError(f"FMTQIK row has fewer than 6 columns: {row!r}")
|
||
vol_rows.append(
|
||
{
|
||
"date": self.parse_roc_date_str(row[0]),
|
||
"volume_shares": self.parse_twse_number(row[1]),
|
||
"turnover_ntd": self.parse_twse_number(row[2]),
|
||
"trade_count": self.parse_twse_number(row[3]),
|
||
}
|
||
)
|
||
df_vol = pd.DataFrame(vol_rows)
|
||
df_ohlc = pd.merge(df_ohlc, df_vol, on="date", how="left")
|
||
else:
|
||
df_ohlc["volume_shares"] = np.nan
|
||
df_ohlc["turnover_ntd"] = np.nan
|
||
df_ohlc["trade_count"] = np.nan
|
||
|
||
return df_ohlc.sort_values("date").reset_index(drop=True)
|
||
|
||
def fetch_month(self, year: int, month: int) -> pd.DataFrame:
|
||
"""
|
||
[使用工具] Python 3.9, pandas
|
||
[設計目的] 呼叫 TWSE 兩支官方 API 擷取單一月份日線指數與市場成交統計
|
||
[程式說明] 依 YYYYMM 組裝查詢網址,分別擷取 MI_5MINS_HIST 與 FMTQIK 後交由解析器合併
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 擷取單月份TWSE日K線與市場成交資訊並進行合併
|
||
[輸入參數]
|
||
- year (int): 西元年(如 2024)
|
||
- month (int): 月份(1–12)
|
||
[輸出結果]
|
||
- return (pd.DataFrame): 該月份標準化現貨 OHLCV 資料表
|
||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [正例] 成功解析 TWSE MI_5MINS_HIST 與 FMTQIK 回傳 JSON 並合併成交金額
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
ym = f"{year:04d}{month:02d}"
|
||
ohlc_json = self.fetch_json(self.OHLC_URL.format(ym=ym))
|
||
time.sleep(self.sleep_sec)
|
||
fmtqik_json = self.fetch_json(self.FMTQIK_URL.format(ym=ym))
|
||
time.sleep(self.sleep_sec)
|
||
return self.parse_twse_month_records(ohlc_json, fmtqik_json)
|
||
|
||
@staticmethod
|
||
def validate_against_tx_proxy(
|
||
spot_df: pd.DataFrame,
|
||
tx_proxy_df: pd.DataFrame,
|
||
min_corr: float = 0.98,
|
||
max_mae: float = 500.0,
|
||
) -> dict[str, float]:
|
||
"""
|
||
[使用工具] Python 3.9, pandas
|
||
[設計目的] 執行 Pre-mortem 交叉校驗,防止錯誤或錯位之補抓現貨覆蓋乾淨主表
|
||
[程式說明] 對齊補抓現貨收盤與大台隱含結算價,若重疊日相關係數低於 0.98 或 MAE 逾 500 點則攔截拋錯
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 實作大台隱含指數交叉校驗守門防止髒資料覆蓋
|
||
[輸入參數]
|
||
- spot_df (pd.DataFrame): 待驗證之現貨資料表(含 date, close)
|
||
- tx_proxy_df (pd.DataFrame): 期貨基準表(含 date, tx_implied_oi_price)
|
||
- min_corr (float): 最小允許皮爾森相關係數,預設 0.98
|
||
- max_mae (float): 最大允許平均絕對誤差點數,預設 500.0
|
||
[輸出結果]
|
||
- return (dict[str, float]): 重疊筆數、相關係數與 MAE 統計字典
|
||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [Pre-mortem] 外部補抓資料與大台隱含指數發生嚴重錯位或異常偏離
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
s_cmp = spot_df[["date", "close"]].copy()
|
||
s_cmp["date"] = pd.to_datetime(s_cmp["date"]).dt.strftime("%Y-%m-%d")
|
||
t_cmp = tx_proxy_df[["date", "tx_implied_oi_price"]].dropna().copy()
|
||
t_cmp["date"] = pd.to_datetime(t_cmp["date"]).dt.strftime("%Y-%m-%d")
|
||
merged = pd.merge(s_cmp, t_cmp, on="date", how="inner")
|
||
if len(merged) < 10:
|
||
raise DataValidationError(f"Insufficient overlapping days ({len(merged)}) for TX proxy validation.")
|
||
corr = float(merged["close"].corr(merged["tx_implied_oi_price"]))
|
||
mae = float((merged["close"] - merged["tx_implied_oi_price"]).abs().mean())
|
||
if not np.isfinite(corr) or corr < min_corr or mae > max_mae:
|
||
raise DataValidationError(
|
||
f"Pre-mortem gate triggered: spot vs TX implied corr={corr:.4f} (min {min_corr}), MAE={mae:.2f} (max {max_mae})."
|
||
)
|
||
return {"overlap_n": float(len(merged)), "corr": round(corr, 6), "mae": round(mae, 2)}
|
||
|
||
def fetch_range_and_merge(
|
||
self,
|
||
start_ym: tuple[int, int],
|
||
end_ym: tuple[int, int],
|
||
repaired_spot_path: Path,
|
||
tx_proxy_path: Path,
|
||
out_path: Path,
|
||
) -> dict[str, Any]:
|
||
"""
|
||
[使用工具] Python 3.9, pandas, pathlib
|
||
[設計目的] 批次補齊缺失月份真實現貨並透過 Pre-mortem 驗證後合併寫入完整檔
|
||
[程式說明] 逐月擷取 start_ym 至 end_ym 現貨 OHLCV,通過大台相關驗證後合併 2011–2023/06 修復序列
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 批次補抓2023至2025真實現貨並驗證後合併輸出
|
||
[輸入參數]
|
||
- start_ym (tuple[int, int]): 起始年月如 (2023, 6)
|
||
- end_ym (tuple[int, int]): 結束年月如 (2025, 3)
|
||
- repaired_spot_path (Path): 第一階段修復後之現貨 CSV 路徑
|
||
- tx_proxy_path (Path): 含 tx_implied_oi_price 的合併特徵 CSV 路徑
|
||
- out_path (Path): 完整現貨日線輸出 CSV 路徑
|
||
[輸出結果]
|
||
- return (dict[str, Any]): 補齊筆數與驗證統計字典
|
||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [Pre-mortem] 外部補抓資料與大台隱含指數發生嚴重錯位或異常偏離
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
cur_y, cur_m = start_ym
|
||
end_y, end_m = end_ym
|
||
frames: list[pd.DataFrame] = []
|
||
while (cur_y, cur_m) <= (end_y, end_m):
|
||
frames.append(self.fetch_month(cur_y, cur_m))
|
||
if cur_m == 12:
|
||
cur_y += 1
|
||
cur_m = 1
|
||
else:
|
||
cur_m += 1
|
||
|
||
sup_df = pd.concat(frames, ignore_index=True).drop_duplicates(subset=["date"]).sort_values("date")
|
||
tx_proxy_df = pd.read_csv(tx_proxy_path)
|
||
val_stats = self.validate_against_tx_proxy(sup_df, tx_proxy_df)
|
||
|
||
base_df = pd.read_csv(repaired_spot_path)
|
||
base_df["date"] = pd.to_datetime(base_df["date"]).dt.strftime("%Y-%m-%d")
|
||
sup_df["source_block"] = "twse_official_supplement"
|
||
for col in ("volume_shares", "turnover_ntd", "trade_count"):
|
||
if col not in base_df.columns:
|
||
base_df[col] = np.nan
|
||
|
||
combined = pd.concat(
|
||
[
|
||
base_df[["date", "open", "high", "low", "close", "volume_shares", "turnover_ntd", "trade_count", "source_block"]],
|
||
sup_df[["date", "open", "high", "low", "close", "volume_shares", "turnover_ntd", "trade_count", "source_block"]],
|
||
],
|
||
ignore_index=True,
|
||
)
|
||
# Prefer official TWSE rows when dates overlap (e.g. 2023-06-01..09)
|
||
combined = combined.drop_duplicates(subset=["date"], keep="last").sort_values("date").reset_index(drop=True)
|
||
combined["ret_1d"] = combined["close"].pct_change()
|
||
tmp_path = out_path.with_suffix(".tmp.csv")
|
||
combined.to_csv(tmp_path, index=False, encoding="utf-8-sig")
|
||
tmp_path.replace(out_path)
|
||
return {"supplement_rows": int(len(sup_df)), "total_rows": int(len(combined)), "validation": val_stats}
|
||
|
||
|
||
class TaifexPcRatioSupplementer:
|
||
"""
|
||
[使用工具] Python 3.9, urllib, csv, ssl, certifi, pandas
|
||
[設計目的] 從期交所 pcRatioDown 端點分批補齊臺指選擇權 Put/Call 成交量比與未平倉量比
|
||
[程式說明] 遵守期交所每次查詢區間不逾 30 日限制分批 POST 抓取並解碼 CP950 CSV,清洗異常零分母
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 實作TAIFEX選擇權Put/Call比30天分批補抓與清洗器
|
||
[輸入參數]
|
||
- timeout (int): HTTP 請求逾時秒數,預設 15 秒
|
||
- sleep_sec (float): 分批請求間休眠秒數,預設 1.5 秒
|
||
[輸出結果]
|
||
- return (TaifexPcRatioSupplementer): 選擇權 Put/Call 比補抓器實例
|
||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [正例] 分批解析 TAIFEX pcRatioDown 的 CP950 編碼 CSV 並消除跨批重疊
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
|
||
PC_RATIO_URL = "https://www.taifex.com.tw/cht/3/pcRatioDown"
|
||
|
||
def __init__(self, timeout: int = 15, sleep_sec: float = 1.5) -> None:
|
||
"""
|
||
[使用工具] Python 3.9, ssl, certifi
|
||
[設計目的] 設定 TAIFEX POST 請求所需之連線標頭、憑證上下文與延遲參數
|
||
[程式說明] 建立載入 certifi 憑證之 SSLContext 並設定瀏覽器 User-Agent 與表單編碼標頭
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 初始化TAIFEX選擇權爬蟲連線標頭與憑證環境
|
||
[輸入參數]
|
||
- timeout (int): 單次請求超時秒數
|
||
- sleep_sec (float): 分批請求禮貌間隔秒數
|
||
[輸出結果]
|
||
- return (None): 設定實例連線屬性
|
||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [正例] 分批解析 TAIFEX pcRatioDown 的 CP950 編碼 CSV 並消除跨批重疊
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
self.timeout = timeout
|
||
self.sleep_sec = sleep_sec
|
||
self.ssl_ctx = ssl.create_default_context(cafile=certifi.where())
|
||
self.headers = {
|
||
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",
|
||
"Content-Type": "application/x-www-form-urlencoded",
|
||
}
|
||
|
||
@staticmethod
|
||
def parse_pc_csv(raw_bytes: bytes) -> pd.DataFrame:
|
||
"""
|
||
[使用工具] Python 3.9, csv, pandas
|
||
[設計目的] 解析期交所 CP950 編碼之 Put/Call Ratio CSV 位元組流並攔截格式漂移
|
||
[程式說明] 自動偵測 CP950 或 UTF-8 解碼,比對必要欄位並於買權量小於等於零時將比率標記為 NaN
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 解碼CP950選擇權比率CSV並執行零分母防護處理
|
||
[輸入參數]
|
||
- raw_bytes (bytes): 期交所回傳之原始 CSV 位元組資料
|
||
[輸出結果]
|
||
- return (pd.DataFrame): 含標準化 date、put/call 量與百分比比率之資料表
|
||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [Pre-mortem] 官方網站回傳 HTML 錯誤頁、空白資料或欄位數突變
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
text = None
|
||
for enc in ("cp950", "utf-8-sig", "utf-8"):
|
||
try:
|
||
text = raw_bytes.decode(enc)
|
||
break
|
||
except UnicodeDecodeError:
|
||
continue
|
||
if text is None or "<html" in text[:300].lower():
|
||
raise DataValidationError("TAIFEX pcRatioDown returned HTML or undecodable payload.")
|
||
|
||
reader = csv.reader(io.StringIO(text.strip()))
|
||
rows = [r for r in reader if any(cell.strip() for cell in r)]
|
||
if len(rows) < 2:
|
||
return pd.DataFrame(
|
||
columns=[
|
||
"date",
|
||
"put_vol",
|
||
"call_vol",
|
||
"pc_vol_ratio_pct",
|
||
"put_oi",
|
||
"call_oi",
|
||
"pc_oi_ratio_pct",
|
||
]
|
||
)
|
||
|
||
header = [h.strip() for h in rows[0]]
|
||
col_map: dict[str, int] = {}
|
||
for idx, name in enumerate(header):
|
||
if "日期" in name:
|
||
col_map["date"] = idx
|
||
elif "買賣權成交量比率" in name:
|
||
col_map["pc_vol_ratio_pct"] = idx
|
||
elif "買賣權未平倉量比率" in name:
|
||
col_map["pc_oi_ratio_pct"] = idx
|
||
elif "賣權成交量" in name:
|
||
col_map["put_vol"] = idx
|
||
elif "買權成交量" in name:
|
||
col_map["call_vol"] = idx
|
||
elif "賣權未平倉量" in name:
|
||
col_map["put_oi"] = idx
|
||
elif "買權未平倉量" in name:
|
||
col_map["call_oi"] = idx
|
||
|
||
required = {"date", "put_vol", "call_vol", "pc_vol_ratio_pct", "put_oi", "call_oi", "pc_oi_ratio_pct"}
|
||
if not required.issubset(col_map.keys()):
|
||
raise DataValidationError(f"TAIFEX CSV header schema drift detected: {header!r}")
|
||
|
||
parsed = []
|
||
for r in rows[1:]:
|
||
if len(r) <= max(col_map.values()):
|
||
continue
|
||
d_str = TwseSpotSupplementer.parse_roc_date_str(r[col_map["date"]].strip())
|
||
put_v = TaifexPcRatioSupplementer._parse_pc_num(r[col_map["put_vol"]])
|
||
call_v = TaifexPcRatioSupplementer._parse_pc_num(r[col_map["call_vol"]])
|
||
pc_v = TaifexPcRatioSupplementer._parse_pc_num(r[col_map["pc_vol_ratio_pct"]])
|
||
put_o = TaifexPcRatioSupplementer._parse_pc_num(r[col_map["put_oi"]])
|
||
call_o = TaifexPcRatioSupplementer._parse_pc_num(r[col_map["call_oi"]])
|
||
pc_o = TaifexPcRatioSupplementer._parse_pc_num(r[col_map["pc_oi_ratio_pct"]])
|
||
if not np.isfinite(call_v) or call_v <= 0:
|
||
pc_v = float("nan")
|
||
if not np.isfinite(call_o) or call_o <= 0:
|
||
pc_o = float("nan")
|
||
parsed.append(
|
||
{
|
||
"date": d_str,
|
||
"put_vol": put_v,
|
||
"call_vol": call_v,
|
||
"pc_vol_ratio_pct": pc_v,
|
||
"put_oi": put_o,
|
||
"call_oi": call_o,
|
||
"pc_oi_ratio_pct": pc_o,
|
||
}
|
||
)
|
||
return pd.DataFrame(parsed).sort_values("date").reset_index(drop=True)
|
||
|
||
@staticmethod
|
||
def _parse_pc_num(raw_str: str) -> float:
|
||
"""
|
||
[使用工具] Python 3.9
|
||
[設計目的] 清理 TAIFEX Put/Call CSV 字串中的千分位逗號與百分號並轉為浮點數
|
||
[程式說明] 移除逗號與百分比符號,若遇到空字串或破折號則安全轉換為 NaN
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 轉換期交所選擇權比率CSV數值字串並處理缺失符號
|
||
[輸入參數]
|
||
- raw_str (str): 原始 CSV 儲存格字串
|
||
[輸出結果]
|
||
- return (float): 清理後浮點數或 NaN
|
||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [正例] 分批解析 TAIFEX pcRatioDown 的 CP950 編碼 CSV 並消除跨批重疊
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
val = raw_str.replace(",", "").replace("%", "").strip()
|
||
return float(val) if val not in ("", "-", "--") else float("nan")
|
||
|
||
def fetch_chunk(self, start_date: dt.date, end_date: dt.date) -> pd.DataFrame:
|
||
"""
|
||
[使用工具] Python 3.9, urllib, datetime
|
||
[設計目的] 向 TAIFEX pcRatioDown 發送單批不逾 30 天的 POST 查詢並回傳解析結果
|
||
[程式說明] 將起始與結束日期轉為 yyyy/MM/dd 表單編碼送出,驗證單批天數並呼叫 CSV 解析函式
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 執行期交所Put/Call比單批30天POST下載與解析
|
||
[輸入參數]
|
||
- start_date (dt.date): 查詢起始日期
|
||
- end_date (dt.date): 查詢結束日期(與起始相差不超過 30 天)
|
||
[輸出結果]
|
||
- return (pd.DataFrame): 該區間之 Put/Call Ratio 資料表
|
||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [正例] 分批解析 TAIFEX pcRatioDown 的 CP950 編碼 CSV 並消除跨批重疊
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
if (end_date - start_date).days > 30:
|
||
raise ValueError("TAIFEX chunk query cannot exceed 30 days.")
|
||
form_data = urllib.parse.urlencode(
|
||
{
|
||
"queryStartDate": start_date.strftime("%Y/%m/%d"),
|
||
"queryEndDate": end_date.strftime("%Y/%m/%d"),
|
||
}
|
||
).encode("utf-8")
|
||
req = urllib.request.Request(self.PC_RATIO_URL, data=form_data, headers=self.headers, method="POST")
|
||
with urllib.request.urlopen(req, timeout=self.timeout, context=self.ssl_ctx) as resp:
|
||
raw_bytes = resp.read()
|
||
time.sleep(self.sleep_sec)
|
||
return self.parse_pc_csv(raw_bytes)
|
||
|
||
def fetch_full_range(self, start_date: str, end_date: str, out_path: Path) -> dict[str, Any]:
|
||
"""
|
||
[使用工具] Python 3.9, pandas, datetime, pathlib
|
||
[設計目的] 自動切分整個目標期間為 30 日批次抓取 Put/Call Ratio,去重排序後原子落盤
|
||
[程式說明] 由 start_date 至 end_date 每 28 天切窗抓取,移除跨批邊界重複日期並以暫存檔原子寫入
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 分批補抓2021至2025選擇權Put/Call比並去重寫入
|
||
[輸入參數]
|
||
- start_date (str): 起始日 'YYYY-MM-DD'
|
||
- end_date (str): 結束日 'YYYY-MM-DD'
|
||
- out_path (Path): 輸出 CSV 路徑
|
||
[輸出結果]
|
||
- return (dict[str, Any]): 總筆數與起始結束日期統計字典
|
||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [正例] 分批解析 TAIFEX pcRatioDown 的 CP950 編碼 CSV 並消除跨批重疊
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
cur = dt.date.fromisoformat(start_date)
|
||
end = dt.date.fromisoformat(end_date)
|
||
chunks: list[pd.DataFrame] = []
|
||
while cur <= end:
|
||
chunk_end = min(cur + dt.timedelta(days=27), end)
|
||
df_c = self.fetch_chunk(cur, chunk_end)
|
||
if not df_c.empty:
|
||
chunks.append(df_c)
|
||
cur = chunk_end + dt.timedelta(days=1)
|
||
|
||
if not chunks:
|
||
raise DataValidationError("No TAIFEX Put/Call Ratio rows returned across entire range.")
|
||
full = pd.concat(chunks, ignore_index=True).drop_duplicates(subset=["date"]).sort_values("date").reset_index(drop=True)
|
||
tmp_path = out_path.with_suffix(".tmp.csv")
|
||
full.to_csv(tmp_path, index=False, encoding="utf-8-sig")
|
||
tmp_path.replace(out_path)
|
||
return {"rows": int(len(full)), "min_date": str(full["date"].iloc[0]), "max_date": str(full["date"].iloc[-1])}
|
||
|
||
|
||
class _PttArticleParser(HTMLParser):
|
||
"""
|
||
[使用工具] Python 3.9, html.parser
|
||
[設計目的] 輕量化解析 PTT 文章內頁之作者、標題與推噓箭頭互動結構,免除外部 HTML 套件依賴
|
||
[程式說明] 透過狀態機追蹤 span.article-meta-value 與 div.push 內的推文標籤及推文者帳號
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 實作免外部依賴之PTT文章推噓標籤HTML解析器
|
||
[輸入參數]
|
||
- 無(透過 feed 方法傳入 HTML 字串)
|
||
[輸出結果]
|
||
- return (_PttArticleParser): 含 meta 資訊列表與 pushes 推文紀錄列表的解析器實例
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [正例] 解析 PTT Stock 文章與推噓互動並計算收斂之 HITS 分數與剪刀差
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
|
||
def __init__(self) -> None:
|
||
"""
|
||
[使用工具] Python 3.9, html.parser
|
||
[設計目的] 初始化 PTT 文章解析器的標籤狀態變數與輸出容器
|
||
[程式說明] 建立 meta_values、pushes 列表及目前追蹤之推文欄位暫存狀態
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 初始化PTT文章HTML解析狀態機與容器
|
||
[輸入參數]
|
||
- 無
|
||
[輸出結果]
|
||
- return (None): 完成解析器初始化
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [正例] 解析 PTT Stock 文章與推噓互動並計算收斂之 HITS 分數與剪刀差
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
super().__init__()
|
||
self.meta_values: list[str] = []
|
||
self.pushes: list[dict[str, str]] = []
|
||
self._in_meta_val = False
|
||
self._meta_buf: list[str] = []
|
||
self._in_push = False
|
||
self._push_field: str | None = None
|
||
self._cur_push: dict[str, str] = {}
|
||
self._buf: list[str] = []
|
||
|
||
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||
"""
|
||
[使用工具] Python 3.9, html.parser
|
||
[設計目的] 偵測 PTT 文章中繼資訊與推文區塊開始標籤並切換解析狀態
|
||
[程式說明] 比對 class 屬性識別 article-meta-value、push 區塊及推文子欄位 push-tag/userid/content
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 識別PTT文章meta與push區塊開始標籤切換狀態
|
||
[輸入參數]
|
||
- tag (str): HTML 標籤名稱
|
||
- attrs (list[tuple[str, str | None]]): HTML 標籤屬性列表
|
||
[輸出結果]
|
||
- return (None): 更新內部狀態旗標
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [正例] 解析 PTT Stock 文章與推噓互動並計算收斂之 HITS 分數與剪刀差
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
cls = dict(attrs).get("class", "") or ""
|
||
classes = cls.split()
|
||
if tag == "span" and "article-meta-value" in classes:
|
||
self._in_meta_val = True
|
||
self._meta_buf = []
|
||
elif tag == "div" and "push" in classes:
|
||
self._in_push = True
|
||
self._cur_push = {"tag": "", "userid": "", "content": ""}
|
||
elif self._in_push and tag == "span":
|
||
if "push-tag" in classes:
|
||
self._push_field = "tag"
|
||
self._buf = []
|
||
elif "push-userid" in classes:
|
||
self._push_field = "userid"
|
||
self._buf = []
|
||
elif "push-content" in classes:
|
||
self._push_field = "content"
|
||
self._buf = []
|
||
|
||
def handle_data(self, data: str) -> None:
|
||
"""
|
||
[使用工具] Python 3.9, html.parser
|
||
[設計目的] 收集當前追蹤 HTML 標籤內部的文字內容
|
||
[程式說明] 若處於 meta 或推文子欄位狀態則累加文字片段至暫存緩衝區
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 收集PTT HTML追蹤標籤內的純文字片段
|
||
[輸入參數]
|
||
- data (str): HTML 標籤間的文字字串
|
||
[輸出結果]
|
||
- return (None): 累加文字至緩衝區
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [正例] 解析 PTT Stock 文章與推噓互動並計算收斂之 HITS 分數與剪刀差
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
if self._in_meta_val:
|
||
self._meta_buf.append(data)
|
||
elif self._in_push and self._push_field:
|
||
self._buf.append(data)
|
||
|
||
def handle_endtag(self, tag: str) -> None:
|
||
"""
|
||
[使用工具] Python 3.9, html.parser
|
||
[設計目的] 在結束標籤時封存推文欄位與整筆互動紀錄
|
||
[程式說明] 關閉 span 時儲存對應推文子欄位,關閉 push 的 div 時若具備完整 tag 與 userid 則寫入列表
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 於HTML結束標籤封存文章作者與單筆推文紀錄
|
||
[輸入參數]
|
||
- tag (str): HTML 結束標籤名稱
|
||
[輸出結果]
|
||
- return (None): 更新 meta_values 或 pushes 列表
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [正例] 解析 PTT Stock 文章與推噓互動並計算收斂之 HITS 分數與剪刀差
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
if tag == "span" and self._in_meta_val:
|
||
self.meta_values.append("".join(self._meta_buf).strip())
|
||
self._in_meta_val = False
|
||
elif tag == "span" and self._in_push and self._push_field:
|
||
self._cur_push[self._push_field] = "".join(self._buf).strip()
|
||
self._push_field = None
|
||
elif tag == "div" and self._in_push:
|
||
if self._cur_push.get("userid") and self._cur_push.get("tag"):
|
||
self.pushes.append(self._cur_push)
|
||
self._in_push = False
|
||
|
||
|
||
class _PttBoardParser(HTMLParser):
|
||
"""
|
||
[使用工具] Python 3.9, html.parser
|
||
[設計目的] 解析 PTT Stock 看板索引頁中的文章連結清單與上一頁導覽網址
|
||
[程式說明] 擷取 div.r-ent 內的文章超連結與 div.btn-group-paging 內含「上頁」之分頁連結
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 解析PTT股票板文章列表網址與上頁分頁導覽連結
|
||
[輸入參數]
|
||
- 無(透過 feed 方法傳入看板 HTML 字串)
|
||
[輸出結果]
|
||
- return (_PttBoardParser): 含 article_paths 與 prev_page_path 之解析器實例
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [正例] 解析 PTT Stock 文章與推噓互動並計算收斂之 HITS 分數與剪刀差
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
|
||
def __init__(self) -> None:
|
||
"""
|
||
[使用工具] Python 3.9, html.parser
|
||
[設計目的] 初始化 PTT 看板列表頁解析器的路徑容器與狀態旗標
|
||
[程式說明] 初始化文章路徑集合、上一頁路徑與分頁按鈕掃描狀態
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 初始化PTT看板索引頁解析狀態與路徑列表
|
||
[輸入參數]
|
||
- 無
|
||
[輸出結果]
|
||
- return (None): 完成解析器初始化
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [正例] 解析 PTT Stock 文章與推噓互動並計算收斂之 HITS 分數與剪刀差
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
super().__init__()
|
||
self.article_paths: list[str] = []
|
||
self.prev_page_path: str | None = None
|
||
self._in_title = False
|
||
self._in_paging = False
|
||
self._cur_href: str | None = None
|
||
self._cur_text: list[str] = []
|
||
|
||
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
||
"""
|
||
[使用工具] Python 3.9, html.parser
|
||
[設計目的] 識別看板文章標題區塊、分頁控制群組及超連結屬性
|
||
[程式說明] 偵測 title 或 btn-group-paging 區塊,並記錄內含 a 標籤之 href 屬性
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 識別PTT看板標題超連結與上頁按鈕標籤屬性
|
||
[輸入參數]
|
||
- tag (str): HTML 標籤名稱
|
||
- attrs (list[tuple[str, str | None]]): HTML 標籤屬性列表
|
||
[輸出結果]
|
||
- return (None): 更新內部狀態
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [正例] 解析 PTT Stock 文章與推噓互動並計算收斂之 HITS 分數與剪刀差
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
attr_d = dict(attrs)
|
||
classes = (attr_d.get("class") or "").split()
|
||
if tag == "div" and "title" in classes:
|
||
self._in_title = True
|
||
elif tag == "div" and "btn-group-paging" in classes:
|
||
self._in_paging = True
|
||
elif tag == "a" and (self._in_title or self._in_paging):
|
||
self._cur_href = attr_d.get("href")
|
||
self._cur_text = []
|
||
|
||
def handle_data(self, data: str) -> None:
|
||
"""
|
||
[使用工具] Python 3.9, html.parser
|
||
[設計目的] 擷取超連結顯示文字以分辨是否為上頁翻頁按鈕
|
||
[程式說明] 記錄 a 標籤內的文字字串供結束標籤比對「上頁」使用
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 讀取超連結顯示文字以辨識上頁翻頁按鈕
|
||
[輸入參數]
|
||
- data (str): 標籤內文字
|
||
[輸出結果]
|
||
- return (None): 累加文字至緩衝區
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [正例] 解析 PTT Stock 文章與推噓互動並計算收斂之 HITS 分數與剪刀差
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
if self._cur_href is not None:
|
||
self._cur_text.append(data)
|
||
|
||
def handle_endtag(self, tag: str) -> None:
|
||
"""
|
||
[使用工具] Python 3.9, html.parser
|
||
[設計目的] 收集有效文章相對路徑並定位看板上一頁網址
|
||
[程式說明] 過濾 Stock 版文章路徑與上頁按鈕文字後分別存入對應列表屬性
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 收集有效Stock文章路徑並萃取上頁網址
|
||
[輸入參數]
|
||
- tag (str): HTML 結束標籤名稱
|
||
[輸出結果]
|
||
- return (None): 更新 article_paths 或 prev_page_path
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [正例] 解析 PTT Stock 文章與推噓互動並計算收斂之 HITS 分數與剪刀差
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
if tag == "a" and self._cur_href:
|
||
label = "".join(self._cur_text).strip()
|
||
if self._in_title and "/bbs/Stock/M." in self._cur_href:
|
||
self.article_paths.append(self._cur_href)
|
||
elif self._in_paging and "上頁" in label:
|
||
self.prev_page_path = self._cur_href
|
||
self._cur_href = None
|
||
elif tag == "div":
|
||
self._in_title = False
|
||
self._in_paging = False
|
||
|
||
|
||
class PttStockHitsPipeline:
|
||
"""
|
||
[使用工具] Python 3.9, urllib, numpy, pandas, ssl, certifi
|
||
[設計目的] 執行 PTT Stock 版文章抓取、帳號互動圖建構與 HITS 權重/輿論剪刀差計算
|
||
[程式說明] 整合 over18 Cookie、斷路器限流防護、水軍自迴圈清除、零矩陣退化防護與 Kleinberg HITS 迭代
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 實作PTT股票板爬蟲與HITS演算法雙向權重分析管線
|
||
[輸入參數]
|
||
- timeout (int): HTTP 請求逾時秒數,預設 12 秒
|
||
- max_consecutive_failures (int): 連續失敗達幾次觸發斷路器熔斷,預設 3 次
|
||
[輸出結果]
|
||
- return (PttStockHitsPipeline): PTT HITS 分析管線實例
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [正例] 解析 PTT Stock 文章與推噓互動並計算收斂之 HITS 分數與剪刀差
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
|
||
BASE_URL = "https://www.ptt.cc"
|
||
BULL_WORDS = ("多", "噴", "漲", "買進", "看多", "突破", "強勢", "加碼", "新高")
|
||
BEAR_WORDS = ("空", "崩", "跌", "賣出", "看空", "破底", "畢業", "停損", "逃命")
|
||
|
||
def __init__(self, timeout: int = 12, max_consecutive_failures: int = 3) -> None:
|
||
"""
|
||
[使用工具] Python 3.9, ssl, certifi
|
||
[設計目的] 初始化 PTT 連線 Cookie、斷路器計數器與 SSL 憑證組態
|
||
[程式說明] 設定 over18=1 繞過年齡提示、SSLContext 及斷路器連續失敗容忍上限
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 初始化PTT over18連線標頭與斷路器計數器
|
||
[輸入參數]
|
||
- timeout (int): 單次連線逾時秒數
|
||
- max_consecutive_failures (int): 連續失敗熔斷閾值
|
||
[輸出結果]
|
||
- return (None): 設定實例屬性
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [Pre-mortem] 爬蟲遭遇 HTTP 429/503 限流或反覆斷線導致程式無窮重試或寫入毀損檔案
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
self.timeout = timeout
|
||
self.max_consecutive_failures = max_consecutive_failures
|
||
self.consecutive_failures = 0
|
||
self.ssl_ctx = ssl.create_default_context(cafile=certifi.where())
|
||
self.headers = {
|
||
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)",
|
||
"Cookie": "over18=1",
|
||
}
|
||
|
||
def fetch_html_with_breaker(self, url: str, opener: Any = None, max_retries: int = 2) -> str:
|
||
"""
|
||
[使用工具] Python 3.9, urllib, time
|
||
[設計目的] 安全擷取 PTT 網頁 HTML,並在遇到 429/503 或連續超時時開啟斷路器熔斷
|
||
[程式說明] 具備單次 L1 指數退避重試與跨次連續失敗計數,達上限即拋出 CircuitBreakerOpenError
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 實作具指數退避與斷路器熔斷保護之PTT網頁擷取方法
|
||
[輸入參數]
|
||
- url (str): 目標 PTT 頁面網址
|
||
- opener (Any): 可注入之 mock 請求函式(供離線 BDD 測試使用)
|
||
- max_retries (int): 單頁最多重試次數
|
||
[輸出結果]
|
||
- return (str): UTF-8 解碼後之完整網頁 HTML 字串
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [Pre-mortem] 爬蟲遭遇 HTTP 429/503 限流或反覆斷線導致程式無窮重試或寫入毀損檔案
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
if self.consecutive_failures >= self.max_consecutive_failures:
|
||
raise CircuitBreakerOpenError("Circuit breaker already OPEN due to prior consecutive failures.")
|
||
|
||
last_err: Exception | None = None
|
||
for attempt in range(max_retries + 1):
|
||
try:
|
||
if opener is not None:
|
||
html_text = opener(url)
|
||
else:
|
||
req = urllib.request.Request(url, headers=self.headers)
|
||
with urllib.request.urlopen(req, timeout=self.timeout, context=self.ssl_ctx) as resp:
|
||
if getattr(resp, "status", 200) in (429, 503):
|
||
raise urllib.error.HTTPError(url, resp.status, "Rate limited", resp.headers, None)
|
||
html_text = resp.read().decode("utf-8", errors="replace")
|
||
self.consecutive_failures = 0
|
||
return html_text
|
||
except (urllib.error.HTTPError, urllib.error.URLError, TimeoutError) as exc:
|
||
last_err = exc
|
||
code = getattr(exc, "code", None)
|
||
if code == 404:
|
||
return ""
|
||
if attempt < max_retries:
|
||
time.sleep(0.2 if opener is not None else 1.5 * (attempt + 1))
|
||
|
||
self.consecutive_failures += 1
|
||
if self.consecutive_failures >= self.max_consecutive_failures:
|
||
raise CircuitBreakerOpenError(
|
||
f"Circuit breaker opened after {self.consecutive_failures} consecutive failures: {last_err}"
|
||
)
|
||
raise DataValidationError(f"Transient fetch failure on {url}: {last_err}")
|
||
|
||
@staticmethod
|
||
def parse_board_list(html_text: str) -> tuple[list[str], str | None]:
|
||
"""
|
||
[使用工具] Python 3.9, html.parser
|
||
[設計目的] 從 PTT Stock 看板列表 HTML 萃取文章相對連結與上一頁連結
|
||
[程式說明] 使用 _PttBoardParser 掃描看板索引頁並去重保留文章順序
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 萃取PTT股票板列表文章連結與上頁翻頁網址
|
||
[輸入參數]
|
||
- html_text (str): 看板索引頁 HTML 原始碼
|
||
[輸出結果]
|
||
- return (tuple[list[str], str | None]): 文章相對路徑列表與上一頁路徑
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [正例] 解析 PTT Stock 文章與推噓互動並計算收斂之 HITS 分數與剪刀差
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
parser = _PttBoardParser()
|
||
parser.feed(html_text)
|
||
dedup_paths = list(dict.fromkeys(parser.article_paths))
|
||
return dedup_paths, parser.prev_page_path
|
||
|
||
@classmethod
|
||
def score_text_sentiment(cls, text: str) -> float:
|
||
"""
|
||
[使用工具] Python 3.9
|
||
[設計目的] 依股市常用多空關鍵字對文章標題或推文內容計算基礎情緒傾向分數
|
||
[程式說明] 統計多方關鍵字與空方關鍵字出現次數差值並壓縮於 [-1, +1] 區間
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 實作PTT股市文章與推文多空關鍵字傾向計分函式
|
||
[輸入參數]
|
||
- text (str): 文章標題或推文純文字內容
|
||
[輸出結果]
|
||
- return (float): 介於 -1.0(極空)至 +1.0(極多)的情緒分數
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [正例] 解析 PTT Stock 文章與推噓互動並計算收斂之 HITS 分數與剪刀差
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
bull_hits = sum(text.count(w) for w in cls.BULL_WORDS)
|
||
bear_hits = sum(text.count(w) for w in cls.BEAR_WORDS)
|
||
total = bull_hits + bear_hits
|
||
if total == 0:
|
||
return 0.0
|
||
return float((bull_hits - bear_hits) / total)
|
||
|
||
@classmethod
|
||
def parse_article_pushes(cls, html_text: str, article_id: str) -> list[dict[str, Any]]:
|
||
"""
|
||
[使用工具] Python 3.9, re
|
||
[設計目的] 解析單篇 PTT 文章的作者、標題與每則推噓箭頭互動邊紀錄
|
||
[程式說明] 萃取作者帳號(去除括號暱稱)與標題情緒,將每則推/噓/箭頭轉為有向互動邊與情緒符號
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 解析PTT文章推噓箭頭並轉換為帳號有向互動邊資料
|
||
[輸入參數]
|
||
- html_text (str): 文章內頁 HTML 字串
|
||
- article_id (str): 文章唯一識別碼(檔名)
|
||
[輸出結果]
|
||
- return (list[dict[str, Any]]): 含 source_user、target_author、edge_weight、sentiment 等互動字典列表
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [正例] 解析 PTT Stock 文章與推噓互動並計算收斂之 HITS 分數與剪刀差
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
parser = _PttArticleParser()
|
||
parser.feed(html_text)
|
||
if len(parser.meta_values) < 4:
|
||
return []
|
||
raw_author = parser.meta_values[0]
|
||
author_id = re.split(r"\s|\(", raw_author.strip())[0]
|
||
title = parser.meta_values[2]
|
||
article_sent = cls.score_text_sentiment(title)
|
||
try:
|
||
art_dt = pd.to_datetime(parser.meta_values[3], errors="coerce")
|
||
date_str = art_dt.strftime("%Y-%m-%d") if pd.notna(art_dt) else "unknown"
|
||
except Exception:
|
||
date_str = "unknown"
|
||
|
||
tag_weight = {"推": 1.0, "噓": 1.0, "→": 0.25}
|
||
tag_sign = {"推": 1.0, "噓": -1.0, "→": 0.0}
|
||
edges = []
|
||
for p in parser.pushes:
|
||
tag = p["tag"]
|
||
push_user = p["userid"].strip()
|
||
w = tag_weight.get(tag, 0.25)
|
||
content_sent = cls.score_text_sentiment(p.get("content", ""))
|
||
# Combine push direction with article sentiment (push on bullish post -> bullish; boo -> opposite)
|
||
dir_sign = tag_sign.get(tag, 0.0)
|
||
combined_sent = content_sent if content_sent != 0.0 else (dir_sign * article_sent)
|
||
edges.append(
|
||
{
|
||
"date": date_str,
|
||
"article_id": article_id,
|
||
"source_user": push_user,
|
||
"target_author": author_id,
|
||
"push_tag": tag,
|
||
"edge_weight": w,
|
||
"interaction_sentiment": combined_sent,
|
||
"article_sentiment": article_sent,
|
||
}
|
||
)
|
||
return edges
|
||
|
||
@staticmethod
|
||
def build_interaction_graph(
|
||
interactions_df: pd.DataFrame, max_pair_weight: float = 3.0
|
||
) -> tuple[list[str], np.ndarray]:
|
||
"""
|
||
[使用工具] Python 3.9, pandas, numpy
|
||
[設計目的] 建構抗水軍操縱的 PTT 帳號互動有向加權鄰接矩陣
|
||
[程式說明] 移除自我推文邊(u == v)防止自戀加權,並將單對帳號互動權重截斷於 max_pair_weight 以抵禦洗板
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 建構有向互動鄰接矩陣並實作水軍自連清除與截斷防護
|
||
[輸入參數]
|
||
- interactions_df (pd.DataFrame): 含 source_user、target_author、edge_weight 之互動表
|
||
- max_pair_weight (float): 單一帳號對單一目標的最大允許累積權重上限
|
||
[輸出結果]
|
||
- return (tuple[list[str], np.ndarray]): 排序後節點名稱列表與非負有向鄰接矩陣 A
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [Pre-mortem] 水軍帳號自我推文或集中洗板造成 Hub/Authority 權重遭到操縱
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
if interactions_df.empty:
|
||
return [], np.zeros((0, 0), dtype=float)
|
||
|
||
# Pre-mortem Sybil defense 1: drop self-loops (u == v)
|
||
df = interactions_df[interactions_df["source_user"] != interactions_df["target_author"]].copy()
|
||
if df.empty:
|
||
return [], np.zeros((0, 0), dtype=float)
|
||
|
||
# Pre-mortem Sybil defense 2: clip excessive pairwise spamming weights
|
||
grouped = (
|
||
df.groupby(["source_user", "target_author"], as_index=False)["edge_weight"]
|
||
.sum()
|
||
.assign(edge_weight=lambda x: np.clip(x["edge_weight"], 0.0, max_pair_weight))
|
||
)
|
||
nodes = sorted(set(grouped["source_user"]).union(set(grouped["target_author"])))
|
||
idx_map = {n: i for i, n in enumerate(nodes)}
|
||
adj = np.zeros((len(nodes), len(nodes)), dtype=float)
|
||
for _, row in grouped.iterrows():
|
||
i = idx_map[row["source_user"]]
|
||
j = idx_map[row["target_author"]]
|
||
adj[i, j] = float(row["edge_weight"])
|
||
return nodes, adj
|
||
|
||
@staticmethod
|
||
def compute_hits_scores(
|
||
adj_matrix: np.ndarray, max_iter: int = 100, tol: float = 1e-6
|
||
) -> tuple[np.ndarray, np.ndarray, int, bool]:
|
||
"""
|
||
[使用工具] Python 3.9, numpy
|
||
[設計目的] 執行 Kleinberg HITS 雙向幂迭代法計算帳號 Authority 與 Hub 分數
|
||
[程式說明] 先偵測矩陣 Frobenius 範數為零之退化狀態安全回傳,否則交替更新並做 L2 正規化直至收斂
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 實作Kleinberg HITS演算法並內建零矩陣除零防護機制
|
||
[輸入參數]
|
||
- adj_matrix (np.ndarray): N×N 非負有向鄰接矩陣 A(A[i, j] 表示 i 指向 j)
|
||
- max_iter (int): 最大迭代次數,預設 100
|
||
- tol (float): 收斂誤差容許閾值,預設 1e-6
|
||
[輸出結果]
|
||
- return (tuple[np.ndarray, np.ndarray, int, bool]): (authority向量, hub向量, 迭代次數, 是否收斂)
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [Pre-mortem] 休市日或無有效推文導致鄰接矩陣全為零使 HITS 迭代發生除零崩潰
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
n = adj_matrix.shape[0]
|
||
if n == 0 or float(np.linalg.norm(adj_matrix)) == 0.0:
|
||
zeros = np.zeros(n, dtype=float)
|
||
return zeros, zeros, 0, True
|
||
|
||
auth = np.ones(n, dtype=float) / np.sqrt(n)
|
||
hub = np.ones(n, dtype=float) / np.sqrt(n)
|
||
converged = False
|
||
iters = 0
|
||
for it in range(1, max_iter + 1):
|
||
iters = it
|
||
new_auth = np.einsum("ji,j->i", adj_matrix, hub)
|
||
a_norm = float(np.linalg.norm(new_auth))
|
||
if a_norm == 0.0:
|
||
return np.zeros(n), np.zeros(n), it, True
|
||
new_auth /= a_norm
|
||
|
||
new_hub = np.einsum("ij,j->i", adj_matrix, new_auth)
|
||
h_norm = float(np.linalg.norm(new_hub))
|
||
if h_norm == 0.0:
|
||
return np.zeros(n), np.zeros(n), it, True
|
||
new_hub /= h_norm
|
||
|
||
diff = float(np.sum(np.abs(new_auth - auth)) + np.sum(np.abs(new_hub - hub)))
|
||
auth, hub = new_auth, new_hub
|
||
if diff < tol:
|
||
converged = True
|
||
break
|
||
return auth, hub, iters, converged
|
||
|
||
def compute_daily_divergence(self, interactions_df: pd.DataFrame) -> dict[str, Any]:
|
||
"""
|
||
[使用工具] Python 3.9, numpy, pandas
|
||
[設計目的] 計算單日或樣本窗之 HITS 權重向量與 Hub-Authority 輿論剪刀差
|
||
[程式說明] 結合 Hub 加權散戶擴散情緒與 Authority 加權高品質來源共識,產出剪刀差 Delta_HA
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 計算PTT Hub與Authority加權情緒及輿論背離剪刀差
|
||
[輸入參數]
|
||
- interactions_df (pd.DataFrame): 互動邊資料表
|
||
[輸出結果]
|
||
- return (dict[str, Any]): 含 hub_sentiment、auth_sentiment、hits_divergence_delta 與領袖節點字典
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [正例] 解析 PTT Stock 文章與推噓互動並計算收斂之 HITS 分數與剪刀差
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
nodes, adj = self.build_interaction_graph(interactions_df)
|
||
auth, hub, iters, converged = self.compute_hits_scores(adj)
|
||
if len(nodes) == 0 or float(np.linalg.norm(adj)) == 0.0:
|
||
return {
|
||
"n_nodes": 0,
|
||
"n_edges": 0,
|
||
"iters": 0,
|
||
"converged": True,
|
||
"hub_sentiment": 0.0,
|
||
"auth_sentiment": 0.0,
|
||
"hits_divergence_delta": 0.0,
|
||
"top_hub": None,
|
||
"top_authority": None,
|
||
}
|
||
|
||
idx_map = {n: i for i, n in enumerate(nodes)}
|
||
valid = interactions_df[interactions_df["source_user"] != interactions_df["target_author"]]
|
||
hub_sent_by_user = valid.groupby("source_user")["interaction_sentiment"].mean()
|
||
auth_sent_by_author = valid.groupby("target_author")["article_sentiment"].mean()
|
||
|
||
h_weights = np.array([hub[idx_map[u]] for u in hub_sent_by_user.index], dtype=float)
|
||
h_sum = float(h_weights.sum())
|
||
hub_sent = float((h_weights * hub_sent_by_user.values).sum() / h_sum) if h_sum > 0 else 0.0
|
||
|
||
a_weights = np.array([auth[idx_map[v]] for v in auth_sent_by_author.index], dtype=float)
|
||
a_sum = float(a_weights.sum())
|
||
auth_sent = float((a_weights * auth_sent_by_author.values).sum() / a_sum) if a_sum > 0 else 0.0
|
||
|
||
return {
|
||
"n_nodes": len(nodes),
|
||
"n_edges": int(np.count_nonzero(adj)),
|
||
"iters": iters,
|
||
"converged": converged,
|
||
"hub_sentiment": round(hub_sent, 6),
|
||
"auth_sentiment": round(auth_sent, 6),
|
||
"hits_divergence_delta": round(hub_sent - auth_sent, 6),
|
||
"top_hub": nodes[int(np.argmax(hub))],
|
||
"top_authority": nodes[int(np.argmax(auth))],
|
||
}
|
||
|
||
def fetch_recent_board_sample(self, max_pages: int = 2, max_articles: int = 12) -> tuple[pd.DataFrame, dict[str, Any]]:
|
||
"""
|
||
[使用工具] Python 3.9, pandas, time
|
||
[設計目的] 從真實 PTT Stock 版抓取近期文章互動資料以驗證線上爬蟲與 HITS 管線
|
||
[程式說明] 依序掃描看板最新頁次至多 max_pages 頁並萃取前 max_articles 篇文章推噓邊,寫入後計算 HITS 指標
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 擷取PTT Stock近期頁面實測線上爬蟲與HITS分數計算
|
||
[輸入參數]
|
||
- max_pages (int): 最多翻找之看板索引頁數
|
||
- max_articles (int): 最多解析的文章篇數
|
||
[輸出結果]
|
||
- return (tuple[pd.DataFrame, dict[str, Any]]): 互動邊資料表與 HITS 計算摘要字典
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [正例] 解析 PTT Stock 文章與推噓互動並計算收斂之 HITS 分數與剪刀差
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
cur_url = f"{self.BASE_URL}/bbs/Stock/index.html"
|
||
article_paths: list[str] = []
|
||
for _ in range(max_pages):
|
||
html_board = self.fetch_html_with_breaker(cur_url)
|
||
paths, prev_path = self.parse_board_list(html_board)
|
||
article_paths.extend(paths)
|
||
if not prev_path or len(article_paths) >= max_articles:
|
||
break
|
||
cur_url = f"{self.BASE_URL}{prev_path}"
|
||
time.sleep(0.8)
|
||
|
||
all_edges: list[dict[str, Any]] = []
|
||
for rel_path in article_paths[:max_articles]:
|
||
art_id = rel_path.split("/")[-1].replace(".html", "")
|
||
art_html = self.fetch_html_with_breaker(f"{self.BASE_URL}{rel_path}")
|
||
if art_html:
|
||
all_edges.extend(self.parse_article_pushes(art_html, art_id))
|
||
time.sleep(0.5)
|
||
|
||
df_edges = pd.DataFrame(all_edges)
|
||
metrics = self.compute_daily_divergence(df_edges) if not df_edges.empty else {"n_nodes": 0, "n_edges": 0}
|
||
return df_edges, metrics
|
||
|
||
|
||
def run_offline_verification() -> dict[str, Any]:
|
||
"""
|
||
[使用工具] Python 3.9, pandas
|
||
[設計目的] 在無外部網路之標準沙盒環境驗證所有資料解析器、Pre-mortem 守門與 HITS 演算法
|
||
[程式說明] 使用與官方端點完全一致的合成測試載荷運行 TWSE、TAIFEX 與 PTT HITS 解析流程並回傳驗證摘要
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 執行無網路沙盒下第二階段解析器與HITS演算法離線驗證
|
||
[輸入參數]
|
||
- 無
|
||
[輸出結果]
|
||
- return (dict[str, Any]): 離線驗證各模組通過指標與計算結果字典
|
||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [正例] 解析 PTT Stock 文章與推噓互動並計算收斂之 HITS 分數與剪刀差
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
sample_ohlc = {
|
||
"stat": "OK",
|
||
"data": [["113/10/01", "22,227.08", "22,442.75", "22,227.08", "22,390.39"]],
|
||
}
|
||
sample_fmtqik = {
|
||
"stat": "OK",
|
||
"data": [["113/10/01", "6,120,000,000", "350,123,456,789", "2,100,000", "22,390.39", "165.85"]],
|
||
}
|
||
twse_df = TwseSpotSupplementer().parse_twse_month_records(sample_ohlc, sample_fmtqik)
|
||
|
||
csv_text = (
|
||
"日期,賣權成交量,買權成交量,買賣權成交量比率%,賣權未平倉量,買權未平倉量,買賣權未平倉量比率%\n"
|
||
"2024/10/01,250000,200000,125.00,310000,240000,129.17\n"
|
||
)
|
||
pc_df = TaifexPcRatioSupplementer.parse_pc_csv(csv_text.encode("cp950"))
|
||
|
||
sample_html = """
|
||
<div class="article-metaline"><span class="article-meta-tag">作者</span><span class="article-meta-value">analyst_a (高手)</span></div>
|
||
<div class="article-metaline"><span class="article-meta-tag">看板</span><span class="article-meta-value">Stock</span></div>
|
||
<div class="article-metaline"><span class="article-meta-tag">標題</span><span class="article-meta-value">[標的] 台積電多頭突破新高</span></div>
|
||
<div class="article-metaline"><span class="article-meta-tag">時間</span><span class="article-meta-value">Tue Oct 1 10:00:00 2024</span></div>
|
||
<div class="push"><span class="push-tag">推</span><span class="push-userid">hub_u1</span><span class="push-content">: 買進看多</span></div>
|
||
<div class="push"><span class="push-tag">推</span><span class="push-userid">hub_u2</span><span class="push-content">: 強勢加碼</span></div>
|
||
<div class="push"><span class="push-tag">推</span><span class="push-userid">analyst_a</span><span class="push-content">: 自推灌水</span></div>
|
||
"""
|
||
edges = PttStockHitsPipeline.parse_article_pushes(sample_html, "M.1727748000.A.001")
|
||
hits_res = PttStockHitsPipeline().compute_daily_divergence(pd.DataFrame(edges))
|
||
|
||
return {
|
||
"twse_sample_rows": int(len(twse_df)),
|
||
"taifex_pc_sample_rows": int(len(pc_df)),
|
||
"ptt_hits_sample": hits_res,
|
||
}
|
||
|
||
|
||
def run_live_pipeline() -> dict[str, Any]:
|
||
"""
|
||
[使用工具] Python 3.9, pandas, pathlib
|
||
[設計目的] 連線 TWSE、TAIFEX 與 PTT Stock 官方網站執行真實缺失資料補抓與整合輸出
|
||
[程式說明] 依序抓取 2023/06–2025/03 現貨、2021/09–2025/03 P/C Ratio 與 PTT Stock 樣本,並合併進日特徵主表
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 執行線上補抓TWSE現貨、TAIFEX選擇權與PTT樣本管線
|
||
[輸入參數]
|
||
- 無
|
||
[輸出結果]
|
||
- return (dict[str, Any]): 三大資料源補抓與整合狀態回報字典
|
||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [正例] 成功解析 TWSE MI_5MINS_HIST 與 FMTQIK 回傳 JSON 並合併成交金額
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
CLEANED_DIR.mkdir(parents=True, exist_ok=True)
|
||
report: dict[str, Any] = {}
|
||
|
||
repaired_spot = CLEANED_DIR / "taiex_spot_repaired_2011_202306.csv"
|
||
merged_features = CLEANED_DIR / "merged_daily_market_features_202109_202503.csv"
|
||
full_spot_out = CLEANED_DIR / "taiex_spot_full_2011_202503.csv"
|
||
pc_out = CLEANED_DIR / "taifex_pc_ratio_202109_202503.csv"
|
||
ptt_edges_out = CLEANED_DIR / "ptt_stock_hits_sample_edges.csv"
|
||
|
||
# 1. TWSE 2023/06 - 2025/03
|
||
try:
|
||
twse_sup = TwseSpotSupplementer()
|
||
report["twse"] = twse_sup.fetch_range_and_merge(
|
||
(2023, 6), (2025, 3), repaired_spot, merged_features, full_spot_out
|
||
)
|
||
except Exception as exc:
|
||
report["twse_error"] = str(exc)
|
||
|
||
# 2. TAIFEX Put/Call Ratio 2021/09/27 - 2025/03/03
|
||
try:
|
||
taifex_sup = TaifexPcRatioSupplementer()
|
||
report["taifex_pc_ratio"] = taifex_sup.fetch_full_range("2021-09-27", "2025-03-03", pc_out)
|
||
except Exception as exc:
|
||
report["taifex_error"] = str(exc)
|
||
|
||
# 3. PTT Stock recent pages sample + HITS
|
||
try:
|
||
ptt_pipe = PttStockHitsPipeline()
|
||
edges_df, hits_metrics = ptt_pipe.fetch_recent_board_sample(max_pages=2, max_articles=10)
|
||
if not edges_df.empty:
|
||
edges_df.to_csv(ptt_edges_out, index=False, encoding="utf-8-sig")
|
||
report["ptt_hits"] = {"edges_count": int(len(edges_df)), "metrics": hits_metrics}
|
||
except Exception as exc:
|
||
report["ptt_error"] = str(exc)
|
||
|
||
# 4. If both/either TWSE or TAIFEX succeeded, create enriched merged table
|
||
if merged_features.exists() and (full_spot_out.exists() or pc_out.exists()):
|
||
df_m = pd.read_csv(merged_features)
|
||
if full_spot_out.exists():
|
||
df_s = pd.read_csv(full_spot_out)
|
||
df_s = df_s[["date", "open", "high", "low", "close", "volume_shares", "turnover_ntd", "trade_count"]].rename(
|
||
columns={
|
||
"open": "twse_open",
|
||
"high": "twse_high",
|
||
"low": "twse_low",
|
||
"close": "twse_close",
|
||
}
|
||
)
|
||
df_m = pd.merge(df_m, df_s, on="date", how="left")
|
||
df_m["true_spot_or_proxy"] = df_m["twse_close"].fillna(df_m["index_proxy"])
|
||
df_m["true_tx_basis"] = df_m["tx_implied_oi_price"] - df_m["twse_close"]
|
||
if pc_out.exists():
|
||
df_pc = pd.read_csv(pc_out)
|
||
df_m = pd.merge(df_m, df_pc, on="date", how="left")
|
||
enriched_out = CLEANED_DIR / "merged_daily_market_features_enriched_202109_202503.csv"
|
||
df_m.to_csv(enriched_out, index=False, encoding="utf-8-sig")
|
||
report["enriched_merged_rows"] = int(len(df_m))
|
||
|
||
return report
|
||
|
||
|
||
def main() -> None:
|
||
"""
|
||
[使用工具] Python 3.9, argparse, json
|
||
[設計目的] 提供 Phase 2 資料補齊與 PTT HITS 管線的命令列入口切換離線與線上模式
|
||
[程式說明] 解析 --verify-offline 或 --fetch-live 參數並輸出 JSON 執行摘要至標準輸出
|
||
[修改日期] 2026-11-20
|
||
[修改概要] 實作第二階段資料補抓命令列雙模式執行入口點
|
||
[輸入參數]
|
||
- 無(讀取 sys.argv 命令列旗標)
|
||
[輸出結果]
|
||
- return (None): 列印驗證或抓取結果 JSON
|
||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [正例] 成功解析 TWSE MI_5MINS_HIST 與 FMTQIK 回傳 JSON 並合併成交金額
|
||
[工作日誌] work_record_20261120.md
|
||
"""
|
||
parser = argparse.ArgumentParser(description="Phase 2 Data Supplement & PTT HITS Pipeline")
|
||
parser.add_argument("--verify-offline", action="store_true", help="Run offline parser & HITS verification")
|
||
parser.add_argument("--fetch-live", action="store_true", help="Fetch live TWSE, TAIFEX, and PTT data")
|
||
args = parser.parse_args()
|
||
|
||
if args.fetch_live:
|
||
result = run_live_pipeline()
|
||
else:
|
||
result = run_offline_verification()
|
||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|