Files
eco_analyse/src/phase3_ptt_10yr_history_and_topics.py
T
2026-11-20 18:36:00 +08:00

1016 lines
49 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Phase 3: PTT Stock 10-year historical explorer, hot-article HITS series, and industry/topic extractor."""
from __future__ import annotations
import argparse
import datetime as dt
import json
import re
import time
from html.parser import HTMLParser
from pathlib import Path
from typing import Any
import numpy as np
import pandas as pd
from phase2_data_supplement_and_hits import (
CircuitBreakerOpenError,
DataValidationError,
PttStockHitsPipeline,
)
PROJECT_ROOT = Path(__file__).resolve().parent.parent
CLEANED_DIR = PROJECT_ROOT / "data" / "cleaned"
TW_TZ = dt.timezone(dt.timedelta(hours=8))
INDUSTRY_LEXICON: dict[str, list[str]] = {
"ind_semiconductor": [
"台積電", "2330", "TSMC", "聯電", "2303", "聯發科", "2454", "日月光",
"CoWoS", "晶圓", "半導體", "矽光子", "IC設計", "艾司摩爾", "ASML", "先進製程", "世芯", "創意",
],
"ind_ai_server": [
"AI", "輝達", "NVIDIA", "NVDA", "廣達", "2382", "緯創", "3231", "技嘉",
"鴻海", "2317", "緯穎", "散熱", "奇鋐", "雙鴻", "GB200", "伺服器", "CPO", "機器人", "光通訊",
],
"ind_shipping": [
"航運", "長榮", "2603", "陽明", "2609", "萬海", "2615", "貨櫃", "SCFI",
"運價", "海運", "航空", "長榮航", "華航", "水手", "船票", "散裝", "航海王",
],
"ind_etf_dividend": [
"ETF", "0050", "0056", "00878", "00919", "00929", "00940", "00713",
"006208", "高股息", "正2", "00631L", "00675L", "美債", "00679B", "00687B", "殖利率", "配息", "換股",
],
"ind_financials": [
"金融", "金控", "玉山金", "富邦金", "國泰金", "兆豐金", "中信金", "開發金",
"凱基金", "元大金", "永豐金", "第一金", "合庫金", "銀行", "壽險", "存股",
],
"ind_power_grid": [
"重電", "華城", "1519", "士電", "1503", "中興電", "1513", "亞力",
"台電", "電網", "儲能", "綠能", "風電", "太陽能", "缺電", "核電", "電價",
],
"ind_biotech": [
"生技", "新藥", "藥華藥", "保瑞", "合一", "高端", "疫苗", "疫情",
"口罩", "快篩", "CDMO", "FDA", "解盲", "醫材",
],
"ind_memory_panel": [
"面板", "友達", "2409", "群創", "3481", "DRAM", "記憶體", "南亞科",
"華邦電", "群聯", "HBM", "蘋果", "iPhone", "蘋概", "大立光", "玉晶光",
],
"ind_commodity_trad": [
"鋼鐵", "中鋼", "2002", "大成鋼", "台塑", "1301", "南亞", "台化",
"塑化", "水泥", "台泥", "造紙", "黃金", "銅價", "油價", "OPEC", "原物料",
],
"ind_ev_auto": [
"電動車", "特斯拉", "Tesla", "TSLA", "裕隆", "中華", "和泰車",
"充電樁", "車用", "自駕", "比亞迪", "電池",
],
"ind_defense_aero": [
"軍工", "漢翔", "2634", "雷虎", "無人機", "龍德造船", "台船", "國防", "資安",
],
"ind_tourism_housing": [
"觀光", "飯店", "餐飲", "王品", "雄獅", "晶華", "解封", "旅遊",
"營建", "房市", "建商", "新青安", "打房", "超商",
],
}
TOPIC_LEXICON: dict[str, list[str]] = {
"top_macro_rates": [
"聯準會", "Fed", "鮑爾", "Powell", "升息", "降息", "CPI", "PCE", "非農",
"通膨", "殖利率", "美債", "央行", "匯率", "台幣", "日圓", "美元", "衰退", "硬著陸",
],
"top_geopolitics_tariff": [
"川普", "Trump", "拜登", "關稅", "貿易戰", "制裁", "禁令", "兩岸",
"軍演", "俄烏", "中東", "以巴", "晶片法案", "大選", "地緣",
],
"top_institutional_flow": [
"外資", "投信", "自營商", "三大法人", "大賣", "大買", "空單", "未平倉",
"淨空單", "倒貨", "連買", "連賣", "認錯", "吃豆腐", "作帳",
],
"top_futures_options": [
"期貨", "大台", "小台", "微台", "選擇權", "Put", "Call", "結算",
"夜盤", "台指期", "嘎空", "軋空", "殺多", "崩盤", "熔斷", "漲停", "跌停",
],
"top_extreme_margin": [
"畢業", "斷頭", "融資", "維持率", "追繳", "違約交割", "停損", "歐印",
"All in", "韭菜", "恐慌", "FOMO", "擦鞋童", "質押", "借錢", "信貸",
],
"top_fundamentals": [
"財報", "EPS", "法說", "營收", "月增", "年增", "毛利率", "除息",
"除權", "填息", "股利", "庫藏股", "減資", "增資", "處置", "注意股",
],
}
def compile_keyword_patterns(lexicon: dict[str, list[str]]) -> dict[str, list[tuple[str, re.Pattern[str]]]]:
"""
[使用工具] Python 3.9, re
[設計目的] 將產業與話題關鍵字辭典編譯為防止英文短字誤判之正則表達式表
[程式說明] 純 ASCII 字詞自動加上字母邊界守護避免 AI 誤中 Taiwan,並保留原始關鍵字供人讀萃取
[修改日期] 2026-11-20
[修改概要] 預編譯具英文邊界守護的產業與話題關鍵字配對清單
[輸入參數]
- lexicon (dict[str, list[str]]): 類別對應關鍵字列表字典
[輸出結果]
- return (dict[str, list[tuple[str, re.Pattern[str]]]]): 類別對應 (關鍵字, 正則) 元組清單
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [正例] 抽取 12 大台股產業與 6 大宏觀籌碼話題標籤並計算熱門文章 HITS 剪刀差序列
[工作日誌] work_record_20261120.md
"""
compiled: dict[str, list[tuple[str, re.Pattern[str]]]] = {}
for cat, terms in lexicon.items():
pats: list[tuple[str, re.Pattern[str]]] = []
for term in terms:
escaped = re.escape(term)
if term.isascii() and any(ch.isalpha() for ch in term):
pats.append((term, re.compile(rf"(?<![A-Za-z]){escaped}(?![A-Za-z])", re.IGNORECASE)))
else:
pats.append((term, re.compile(escaped, re.IGNORECASE)))
compiled[cat] = pats
return compiled
COMPILED_INDUSTRIES = compile_keyword_patterns(INDUSTRY_LEXICON)
COMPILED_TOPICS = compile_keyword_patterns(TOPIC_LEXICON)
class _PttRichBoardParser(HTMLParser):
"""
[使用工具] Python 3.9, html.parser
[設計目的] 完整解析 PTT 看板列表頁每篇文章的推文熱度、標題、連結、作者與置底分隔旗標
[程式說明] 使用堆疊追蹤巢狀 div 結構,準確辨識 r-list-sep 後之置底公告並避免刪文列遺漏
[修改日期] 2026-11-20
[修改概要] 實作支援巢狀div與置底分隔偵測的PTT看板富列表解析器
[輸入參數]
- 無(透過 feed 方法傳入看板 HTML)
[輸出結果]
- return (_PttRichBoardParser): 含 entries 文章列表與 prev_page_path 之解析器實例
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [Pre-mortem] 歷史刪文、置底公告或無效時間戳記導致二分搜尋陷入無窮迴圈或頁碼錯位
[工作日誌] work_record_20261120.md
"""
def __init__(self) -> None:
"""
[使用工具] Python 3.9, html.parser
[設計目的] 初始化看板富列表解析器的巢狀堆疊與文章項目暫存狀態
[程式說明] 建立 div class 堆疊、置底分隔旗標及當前解析中的文章欄位緩衝
[修改日期] 2026-11-20
[修改概要] 初始化PTT看板富列表解析狀態機與堆疊結構
[輸入參數]
- 無
[輸出結果]
- return (None): 完成初始化
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [Pre-mortem] 歷史刪文、置底公告或無效時間戳記導致二分搜尋陷入無窮迴圈或頁碼錯位
[工作日誌] work_record_20261120.md
"""
super().__init__()
self.entries: list[dict[str, Any]] = []
self.prev_page_path: str | None = None
self._div_stack: list[str] = []
self._after_sep = False
self._cur_entry: dict[str, Any] | None = None
self._in_a = False
self._cur_href: str | None = None
self._a_text: list[str] = []
self._field_buf: list[str] = []
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
"""
[使用工具] Python 3.9, html.parser
[設計目的] 追蹤看板 HTML 巢狀 div 區塊與超連結標籤以定位文章屬性欄位
[程式說明] 偵測 r-list-sep 切換置底狀態,於 r-ent 開啟新項目並記錄 nrec/title/author/date
[修改日期] 2026-11-20
[修改概要] 追蹤PTT列表頁巢狀div與置底分隔標記開啟文章欄位
[輸入參數]
- tag (str): HTML 標籤名稱
- attrs (list[tuple[str, str | None]]): HTML 標籤屬性列表
[輸出結果]
- return (None): 更新堆疊與當前文章暫存字典
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [Pre-mortem] 歷史刪文、置底公告或無效時間戳記導致二分搜尋陷入無窮迴圈或頁碼錯位
[工作日誌] work_record_20261120.md
"""
attr_d = dict(attrs)
cls = attr_d.get("class") or ""
classes = cls.split()
if tag == "div":
role = ""
for cand in ("r-ent", "nrec", "title", "author", "date", "mark", "btn-group-paging", "r-list-sep"):
if cand in classes:
role = cand
break
self._div_stack.append(role)
if role == "r-list-sep":
self._after_sep = True
elif role == "r-ent":
self._cur_entry = {
"nrec_raw": "",
"title": "",
"href": "",
"author": "",
"date_md": "",
"is_pinned": self._after_sep,
}
elif role in ("nrec", "title", "author", "date") and self._cur_entry is not None:
self._field_buf = []
elif tag == "a":
self._in_a = True
self._cur_href = attr_d.get("href")
self._a_text = []
def handle_data(self, data: str) -> None:
"""
[使用工具] Python 3.9, html.parser
[設計目的] 收集看板文章各欄位或翻頁超連結內部的純文字內容
[程式說明] 依目前堆疊頂端角色決定將文字存入欄位緩衝或超連結文字緩衝
[修改日期] 2026-11-20
[修改概要] 收集看板文章屬性欄位與超連結顯示文字片段
[輸入參數]
- data (str): 標籤內文字片段
[輸出結果]
- return (None): 累加文字緩衝
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [Pre-mortem] 歷史刪文、置底公告或無效時間戳記導致二分搜尋陷入無窮迴圈或頁碼錯位
[工作日誌] work_record_20261120.md
"""
if self._in_a:
self._a_text.append(data)
if self._cur_entry is not None and self._div_stack:
top = self._div_stack[-1]
if top in ("nrec", "title", "author", "date"):
self._field_buf.append(data)
def handle_endtag(self, tag: str) -> None:
"""
[使用工具] Python 3.9, html.parser
[設計目的] 在 HTML 標籤閉合時寫入文章超連結、熱度分數或上頁翻頁路徑
[程式說明] 彈出 div 堆疊時保存對應欄位,若為 r-ent 結束則封存整筆文章字典
[修改日期] 2026-11-20
[修改概要] 閉合標籤時封存單篇文章連結熱度與上頁按鈕路徑
[輸入參數]
- tag (str): 結束標籤名稱
[輸出結果]
- return (None): 更新 entries 與 prev_page_path
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [Pre-mortem] 歷史刪文、置底公告或無效時間戳記導致二分搜尋陷入無窮迴圈或頁碼錯位
[工作日誌] work_record_20261120.md
"""
if tag == "a" and self._in_a:
label = "".join(self._a_text).strip()
top = self._div_stack[-1] if self._div_stack else ""
if top == "title" and self._cur_entry is not None and self._cur_href:
self._cur_entry["href"] = self._cur_href
self._cur_entry["title"] = label
elif "btn-group-paging" in self._div_stack and "上頁" in label and self._cur_href:
self.prev_page_path = self._cur_href
self._in_a = False
self._cur_href = None
elif tag == "div" and self._div_stack:
role = self._div_stack.pop()
if self._cur_entry is not None:
val = "".join(self._field_buf).strip()
if role == "nrec":
self._cur_entry["nrec_raw"] = val
elif role == "title" and not self._cur_entry["title"]:
self._cur_entry["title"] = val
elif role == "author":
self._cur_entry["author"] = val
elif role == "date":
self._cur_entry["date_md"] = val
elif role == "r-ent":
self.entries.append(self._cur_entry)
self._cur_entry = None
class PttTenYearExplorer:
"""
[使用工具] Python 3.9, pandas, numpy, re, datetime
[設計目的] 探測 PTT Stock 版十年歷史頁碼邊界、抓取跨期熱門文章 HITS 序列並抽取產業/話題文字特徵
[程式說明] 結合 Unix 時間戳內插二分搜尋、置底刪文過濾、12 大產業與 6 大話題詞庫及原子斷點續傳爬蟲
[修改日期] 2026-11-20
[修改概要] 實作PTT Stock十年歷史頁碼搜尋、熱門HITS與話題抽取類別
[輸入參數]
- board_sleep (float): 看板頁抓取禮貌間隔秒數,預設 0.3 秒
- article_sleep (float): 文章內頁抓取禮貌間隔秒數,預設 0.35 秒
[輸出結果]
- return (PttTenYearExplorer): 十年歷史探測與輿論特徵抽取器實例
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [正例] 由 M.<TIMESTAMP>.A 解析精確西元日期並以二分搜尋定位十年歷史頁碼
[工作日誌] work_record_20261120.md
"""
BASE_URL = "https://www.ptt.cc"
MIN_VALID_TS = 1072915200 # 2004-01-01 UTC
MAX_VALID_TS = 1893456000 # 2030-01-01 UTC
def __init__(self, board_sleep: float = 0.3, article_sleep: float = 0.35) -> None:
"""
[使用工具] Python 3.9
[設計目的] 初始化十年歷史爬蟲的底層 HITS 連線管線與頁面快取容器
[程式說明] 複用 PttStockHitsPipeline 以繼承 over18 Cookie 與斷路器防護,並建立快取字典減少重複請求
[修改日期] 2026-11-20
[修改概要] 初始化十年歷史爬蟲連線管線與頁碼快取字典
[輸入參數]
- board_sleep (float): 看板翻頁延遲秒數
- article_sleep (float): 文章內頁延遲秒數
[輸出結果]
- return (None): 設定實例屬性
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [正例] 由 M.<TIMESTAMP>.A 解析精確西元日期並以二分搜尋定位十年歷史頁碼
[工作日誌] work_record_20261120.md
"""
self.pipe = PttStockHitsPipeline(timeout=12, max_consecutive_failures=4)
self.board_sleep = board_sleep
self.article_sleep = article_sleep
self.page_cache: dict[int, dict[str, Any]] = {}
@classmethod
def extract_timestamp_from_href(cls, href: str) -> int | None:
"""
[使用工具] Python 3.9, re
[設計目的] 從 PTT 文章連結路徑萃取 Unix 秒級發文時間戳記並過濾異常值
[程式說明] 以正則匹配 M.<digits>.A 模式並檢查範圍介於 2004 至 2030 年之間
[修改日期] 2026-11-20
[修改概要] 由PTT文章URL萃取並驗證合法Unix時間戳記
[輸入參數]
- href (str): 文章相對或絕對連結路徑
[輸出結果]
- return (int | None): Unix 秒級時間戳記,無效或刪文無連結則回傳 None
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [Pre-mortem] 歷史刪文、置底公告或無效時間戳記導致二分搜尋陷入無窮迴圈或頁碼錯位
[工作日誌] work_record_20261120.md
"""
if not href:
return None
m = re.search(r"M\.(\d{9,11})\.A\.", href)
if not m:
return None
ts = int(m.group(1))
if cls.MIN_VALID_TS <= ts <= cls.MAX_VALID_TS:
return ts
return None
@staticmethod
def ts_to_date_str(ts: int) -> str:
"""
[使用工具] Python 3.9, datetime
[設計目的] 將 Unix 秒級時間戳記轉換為台北時區(UTC+8)之 ISO 西元日期字串
[程式說明] 使用 TW_TZ 時區轉換後格式化為 YYYY-MM-DD
[修改日期] 2026-11-20
[修改概要] 將Unix時間戳轉為台北時區標準YYYY-MM-DD格式
[輸入參數]
- ts (int): Unix 秒級時間戳記
[輸出結果]
- return (str): 標準日期字串 'YYYY-MM-DD'
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [正例] 由 M.<TIMESTAMP>.A 解析精確西元日期並以二分搜尋定位十年歷史頁碼
[工作日誌] work_record_20261120.md
"""
return dt.datetime.fromtimestamp(ts, tz=TW_TZ).strftime("%Y-%m-%d")
@staticmethod
def parse_nrec_score(nrec_raw: str) -> int:
"""
[使用工具] Python 3.9
[設計目的] 將 PTT 看板推文熱度文字轉換為可量化排序的整數熱度分數
[程式說明] 轉換「爆」為 100、「XX」為 -100、「X1~X9」為 -10~-90,其餘數字直接轉整數
[修改日期] 2026-11-20
[修改概要] 轉換PTT推文熱度字串如爆與X1為整數分數
[輸入參數]
- nrec_raw (str): 看板 nrec 原始字串
[輸出結果]
- return (int): 量化熱度整數(範圍 -100 至 100)
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [正例] 抽取 12 大台股產業與 6 大宏觀籌碼話題標籤並計算熱門文章 HITS 剪刀差序列
[工作日誌] work_record_20261120.md
"""
s = nrec_raw.strip()
if not s:
return 0
if s == "爆":
return 100
if s == "XX":
return -100
if s.startswith("X") and len(s) == 2 and s[1].isdigit():
return -10 * int(s[1])
if s.lstrip("-").isdigit():
return int(s)
return 0
@staticmethod
def extract_industry_and_topic_tags(title: str) -> dict[str, Any]:
"""
[使用工具] Python 3.9, re
[設計目的] 從 PTT 文章標題抽取出文章類別前綴、12 大台股產業標籤與 6 大宏觀籌碼話題標籤
[程式說明] 解析方括號分類標籤(如 [標的]、[新聞])並以預編譯正則匹配關鍵字與多空傾向
[修改日期] 2026-11-20
[修改概要] 萃取文章分類標籤、十二大產業與六大話題關鍵字特徵
[輸入參數]
- title (str): PTT 文章標題文字
[輸出結果]
- return (dict[str, Any]): 含 post_type、industries、topics、matched_keywords、title_sentiment 之字典
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [正例] 抽取 12 大台股產業與 6 大宏觀籌碼話題標籤並計算熱門文章 HITS 剪刀差序列
[工作日誌] work_record_20261120.md
"""
m_type = re.match(r"^(?:Re:\s*|Fw:\s*)*\[([^\]]+)\]", title.strip())
post_type = m_type.group(1).strip() if m_type else "其他"
industries: list[str] = []
topics: list[str] = []
readable_kw: list[str] = []
for cat, pats in COMPILED_INDUSTRIES.items():
hits = [term for term, pat in pats if pat.search(title)]
if hits:
industries.append(cat)
for h in hits:
if h not in readable_kw:
readable_kw.append(h)
for cat, pats in COMPILED_TOPICS.items():
hits = [term for term, pat in pats if pat.search(title)]
if hits:
topics.append(cat)
for h in hits:
if h not in readable_kw:
readable_kw.append(h)
return {
"post_type": post_type,
"industries": "|".join(industries) if industries else "none",
"topics": "|".join(topics) if topics else "none",
"matched_keywords": "|".join(readable_kw),
"title_sentiment": PttStockHitsPipeline.score_text_sentiment(title),
}
@classmethod
def parse_rich_board_html(cls, html_text: str, page_no: int | None = None) -> dict[str, Any]:
"""
[使用工具] Python 3.9, numpy
[設計目的] 將單頁看板 HTML 轉為結構化文章列表、上頁編號與中位數發文時間戳記
[程式說明] 濾除置底公告與刪文列後計算中位數時間戳記,供二分搜尋精準判斷頁碼年份位置
[修改日期] 2026-11-20
[修改概要] 解析單頁看板文章詳情並計算非置底文章中位數時間戳
[輸入參數]
- html_text (str): 看板索引頁 HTML 字串
- page_no (int | None): 當前頁碼(選填)
[輸出結果]
- return (dict[str, Any]): 含 page_no、prev_page_no、median_ts、median_date 與 entries 之字典
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [Pre-mortem] 歷史刪文、置底公告或無效時間戳記導致二分搜尋陷入無窮迴圈或頁碼錯位
[工作日誌] work_record_20261120.md
"""
parser = _PttRichBoardParser()
parser.feed(html_text)
prev_page_no: int | None = None
if parser.prev_page_path:
m_prev = re.search(r"index(\d+)\.html", parser.prev_page_path)
if m_prev:
prev_page_no = int(m_prev.group(1))
enriched_entries: list[dict[str, Any]] = []
valid_ts_list: list[int] = []
for ent in parser.entries:
ts = cls.extract_timestamp_from_href(ent["href"])
nrec_score = cls.parse_nrec_score(ent["nrec_raw"])
tags = cls.extract_industry_and_topic_tags(ent["title"])
item = {
"page_no": page_no,
"article_id": ent["href"].split("/")[-1].replace(".html", "") if ent["href"] else "",
"href": ent["href"],
"unix_ts": ts,
"date": cls.ts_to_date_str(ts) if ts is not None else "",
"author": ent["author"],
"title": ent["title"],
"nrec_raw": ent["nrec_raw"],
"nrec_score": nrec_score,
"is_pinned": ent["is_pinned"],
**tags,
}
enriched_entries.append(item)
if ts is not None and not ent["is_pinned"]:
valid_ts_list.append(ts)
median_ts = int(np.median(valid_ts_list)) if valid_ts_list else None
return {
"page_no": page_no,
"prev_page_no": prev_page_no,
"median_ts": median_ts,
"median_date": cls.ts_to_date_str(median_ts) if median_ts is not None else None,
"entries": enriched_entries,
}
def fetch_board_page_cached(self, page_no: int | None = None, opener: Any = None) -> dict[str, Any]:
"""
[使用工具] Python 3.9, time
[設計目的] 讀取指定 PTT 看板頁碼並快取解析結果,徹底避免重複 HTTP 請求
[程式說明] 若快取命中直接回傳,否則連線抓取並於快取註冊該頁文章與中位數日期
[修改日期] 2026-11-20
[修改概要] 實作具記憶體快取保護之PTT看板頁碼讀取方法
[輸入參數]
- page_no (int | None): 目標頁碼,None 代表最新首頁 index.html
- opener (Any): 可注入之離線 mock 函式
[輸出結果]
- return (dict[str, Any]): 該頁解析結果字典
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [正例] 由 M.<TIMESTAMP>.A 解析精確西元日期並以二分搜尋定位十年歷史頁碼
[工作日誌] work_record_20261120.md
"""
if page_no is not None and page_no in self.page_cache:
return self.page_cache[page_no]
url = f"{self.BASE_URL}/bbs/Stock/index.html" if page_no is None else f"{self.BASE_URL}/bbs/Stock/index{page_no}.html"
html_text = self.pipe.fetch_html_with_breaker(url, opener=opener)
if opener is None:
time.sleep(self.board_sleep)
parsed = self.parse_rich_board_html(html_text, page_no=page_no)
if page_no is None and parsed["prev_page_no"] is not None:
inferred_no = parsed["prev_page_no"] + 1
parsed["page_no"] = inferred_no
for e in parsed["entries"]:
e["page_no"] = inferred_no
self.page_cache[inferred_no] = parsed
elif page_no is not None:
self.page_cache[page_no] = parsed
return parsed
def locate_page_for_target_date(
self,
target_date: str,
min_page: int,
max_page: int,
opener: Any = None,
max_steps: int = 24,
) -> dict[str, Any]:
"""
[使用工具] Python 3.9, datetime
[設計目的] 使用結合快取界限收縮的內插二分搜尋精確定位歷史目標日期之 PTT 頁碼
[程式說明] 利用所有已探測快取點先收緊搜尋區間 [lo, hi],再以中點或線性內插探針逼近,內建步數與無有效時間戳保護
[修改日期] 2026-11-20
[修改概要] 實作具快取界限收縮與步數守護的歷史頁碼二分搜尋
[輸入參數]
- target_date (str): 目標搜尋日期 'YYYY-MM-DD'
- min_page (int): 最小起始頁碼(通常為 1)
- max_page (int): 最新頁碼
- opener (Any): 可注入之離線 mock 函式
- max_steps (int): 最大允許搜尋迭代次數,防範異常無窮迴圈
[輸出結果]
- return (dict[str, Any]): 包含 target_date、matched_page、matched_date、steps 之定位結果
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [Pre-mortem] 歷史刪文、置底公告或無效時間戳記導致二分搜尋陷入無窮迴圈或頁碼錯位
[工作日誌] work_record_20261120.md
"""
target_ts = int(dt.datetime.strptime(target_date, "%Y-%m-%d").replace(tzinfo=TW_TZ).timestamp())
lo, hi = min_page, max_page
# Tighten initial [lo, hi] bounds using any already cached pages
for p_no, info in self.page_cache.items():
m_ts = info.get("median_ts")
if m_ts is None:
continue
if m_ts <= target_ts and p_no > lo:
lo = p_no
if m_ts >= target_ts and p_no < hi:
hi = p_no
best_page = lo
best_diff = float("inf")
best_date = None
steps = 0
while lo <= hi and steps < max_steps:
steps += 1
lo_ts = self.page_cache.get(lo, {}).get("median_ts")
hi_ts = self.page_cache.get(hi, {}).get("median_ts")
if lo_ts is not None and hi_ts is not None and hi_ts > lo_ts and lo_ts <= target_ts <= hi_ts and (hi - lo) > 4:
ratio = (target_ts - lo_ts) / float(hi_ts - lo_ts)
mid = lo + int(round(ratio * (hi - lo)))
mid = max(lo + 1, min(hi - 1, mid))
else:
mid = (lo + hi) // 2
info = self.fetch_board_page_cached(mid, opener=opener)
m_ts = info.get("median_ts")
# Pre-mortem guard: if a page is full of deleted posts with no valid timestamp, nudge forward safely
probe_offset = 0
while m_ts is None and (mid + probe_offset) < hi and probe_offset < 3:
probe_offset += 1
info = self.fetch_board_page_cached(mid + probe_offset, opener=opener)
m_ts = info.get("median_ts")
if m_ts is None:
lo = mid + 1
continue
diff = abs(m_ts - target_ts)
if diff < best_diff:
best_diff = diff
best_page = info["page_no"]
best_date = info["median_date"]
if diff <= 86400:
break
if m_ts < target_ts:
lo = max(mid + 1, lo + 1)
else:
hi = min(mid - 1, hi - 1)
return {
"target_date": target_date,
"matched_page": int(best_page),
"matched_date": best_date,
"steps": steps,
}
def map_ten_year_milestones(self, opener: Any = None) -> tuple[int, list[dict[str, Any]]]:
"""
[使用工具] Python 3.9
[設計目的] 探測 PTT Stock 最早歷史起點(index1)與 2015–2025 各年度及轉折事件頁碼位置
[程式說明] 先取最新頁與第一頁確認版面時間跨度,再依序定位 15 個跨十年關鍵時間點頁碼
[修改日期] 2026-11-20
[修改概要] 探測PTT Stock看板起點與近十年十五個里程碑頁碼地圖
[輸入參數]
- opener (Any): 可注入之離線 mock 函式
[輸出結果]
- return (tuple[int, list[dict[str, Any]]]): (最新頁碼 max_page, 里程碑頁碼對照列表)
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [正例] 由 M.<TIMESTAMP>.A 解析精確西元日期並以二分搜尋定位十年歷史頁碼
[工作日誌] work_record_20261120.md
"""
latest_info = self.fetch_board_page_cached(None, opener=opener)
max_page = int(latest_info["page_no"])
first_info = self.fetch_board_page_cached(1, opener=opener)
targets = [
("origin_page_1", None, 1),
("2015_peak_correction", "2015-06-15", None),
("2016_mid_year", "2016-06-15", None),
("2017_10k_era", "2017-06-15", None),
("2018_trade_war_oct", "2018-10-15", None),
("2019_rally", "2019-06-15", None),
("2020_covid_crash", "2020-03-19", None),
("2021_shipping_boom", "2021-06-15", None),
("2022_bear_trough", "2022-10-25", None),
("2023_ai_launch", "2023-06-15", None),
("2024_etf_940_wave", "2024-03-20", None),
("2024_peak_24k", "2024-07-11", None),
("2024_aug5_crash", "2024-08-05", None),
("2024_q4_consolidation", "2024-11-15", None),
("2025_q1_high", "2025-02-20", None),
("2025_q4_window", "2025-11-15", None),
("2026_q1_window", "2026-02-15", None),
("2026_q2_window", "2026-05-15", None),
("2026_q3_window", "2026-08-15", None),
("2026_q4_oct_window", "2026-10-15", None),
("latest_page", None, max_page),
]
milestones: list[dict[str, Any]] = []
for label, tgt_dt, fixed_page in targets:
if fixed_page is not None:
info = first_info if fixed_page == 1 else latest_info
milestones.append(
{
"milestone": label,
"target_date": info["median_date"],
"matched_page": int(info["page_no"]),
"matched_date": info["median_date"],
"steps": 0,
}
)
else:
res = self.locate_page_for_target_date(tgt_dt, 1, max_page, opener=opener)
milestones.append({"milestone": label, **res})
return max_page, milestones
def crawl_historical_windows_and_hits(
self,
milestones: list[dict[str, Any]],
max_page: int,
recent_pages: int = 8,
pages_per_milestone: int = 2,
min_nrec_hot: int = 25,
max_hot_per_window: int = 4,
checkpoint_dir: Path | None = None,
) -> dict[str, Any]:
"""
[使用工具] Python 3.9, pandas, pathlib
[設計目的] 擴大抓取十年各里程碑視窗標題與熱門文章推文,產出日頻 HITS 剪刀差序列與斷點快取
[程式說明] 抓取各歷史視窗列表並篩選高熱度文章深入解析內頁推噓文,支援斷點原子存檔與斷路器中斷續傳
[修改日期] 2026-11-20
[修改概要] 執行十年視窗與近期熱門文章爬取及日頻HITS剪刀差計算
[輸入參數]
- milestones (list[dict[str, Any]]): 十年關鍵頁碼里程碑列表
- max_page (int): 看板最新頁碼
- recent_pages (int): 近期連續抓取頁數(預設 8 頁)
- pages_per_milestone (int): 每個歷史里程碑抓取鄰近頁數(預設 2 頁)
- min_nrec_hot (int): 深入抓取內頁推文的最低推文熱度門檻(預設 25)
- max_hot_per_window (int): 每個歷史視窗最多抓幾篇熱門文章(預設 4 篇)
- checkpoint_dir (Path | None): 斷點檢查存檔目錄
[輸出結果]
- return (dict[str, Any]): 含 articles_df、edges_df 與 hits_series_df 的完整成果字典
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [Pre-mortem] 長區間歷史爬取中途斷線或斷路器觸發導致既有進度遺失或重複寫入
[工作日誌] work_record_20261120.md
"""
ckpt_articles_path = checkpoint_dir / "ptt_ckpt_articles.csv" if checkpoint_dir else None
ckpt_edges_path = checkpoint_dir / "ptt_ckpt_edges.csv" if checkpoint_dir else None
existing_articles: list[dict[str, Any]] = []
seen_article_ids: set[str] = set()
if ckpt_articles_path and ckpt_articles_path.exists():
df_old_a = pd.read_csv(ckpt_articles_path)
existing_articles = df_old_a.to_dict("records")
seen_article_ids = set(df_old_a["article_id"].dropna().astype(str))
existing_edges: list[dict[str, Any]] = []
crawled_edge_article_ids: set[str] = set()
if ckpt_edges_path and ckpt_edges_path.exists():
df_old_e = pd.read_csv(ckpt_edges_path)
existing_edges = df_old_e.to_dict("records")
crawled_edge_article_ids = set(df_old_e["article_id"].dropna().astype(str))
window_pages: list[tuple[str, int]] = []
for ms in milestones:
if ms["milestone"] == "origin_page_1":
continue
p0 = int(ms["matched_page"])
for offset in range(pages_per_milestone):
p = max(1, min(max_page, p0 + offset))
window_pages.append((ms["milestone"], p))
for p in range(max(1, max_page - recent_pages + 1), max_page + 1):
window_pages.append(("recent_continuous", p))
# Deduplicate while preserving window label
seen_pages: set[int] = set()
unique_window_pages: list[tuple[str, int]] = []
for w_label, p_no in window_pages:
if p_no not in seen_pages:
seen_pages.add(p_no)
unique_window_pages.append((w_label, p_no))
new_articles: list[dict[str, Any]] = []
breaker_tripped = False
try:
for w_label, p_no in unique_window_pages:
info = self.fetch_board_page_cached(p_no)
for ent in info["entries"]:
if ent["is_pinned"] or not ent["article_id"]:
continue
if ent["article_id"] not in seen_article_ids:
seen_article_ids.add(ent["article_id"])
new_articles.append({"window_label": w_label, **ent})
except (CircuitBreakerOpenError, DataValidationError):
breaker_tripped = True
all_articles = existing_articles + new_articles
articles_df = pd.DataFrame(all_articles)
if not articles_df.empty:
articles_df = articles_df.drop_duplicates(subset=["article_id"]).sort_values("unix_ts").reset_index(drop=True)
if ckpt_articles_path:
tmp_a = ckpt_articles_path.with_suffix(".tmp.csv")
articles_df.to_csv(tmp_a, index=False, encoding="utf-8-sig")
tmp_a.replace(ckpt_articles_path)
# Select top hot articles per window (prioritizing 爆/high nrec)
hot_candidates: list[dict[str, Any]] = []
if not articles_df.empty:
for w_label, grp in articles_df.groupby("window_label"):
limit = 20 if w_label == "recent_continuous" else max_hot_per_window
hot_sub = grp[grp["nrec_score"] >= min_nrec_hot].sort_values("nrec_score", ascending=False).head(limit)
if hot_sub.empty:
hot_sub = grp.sort_values("nrec_score", ascending=False).head(min(2, limit))
hot_candidates.extend(hot_sub.to_dict("records"))
new_edges: list[dict[str, Any]] = []
if not breaker_tripped:
try:
for cand in hot_candidates:
art_id = str(cand["article_id"])
if art_id in crawled_edge_article_ids or not cand.get("href"):
continue
art_html = self.pipe.fetch_html_with_breaker(f"{self.BASE_URL}{cand['href']}")
time.sleep(self.article_sleep)
if art_html:
edges = self.pipe.parse_article_pushes(art_html, art_id)
for ed in edges:
ed["window_label"] = cand["window_label"]
ed["article_date"] = cand["date"]
ed["industries"] = cand["industries"]
ed["topics"] = cand["topics"]
new_edges.extend(edges)
crawled_edge_article_ids.add(art_id)
except (CircuitBreakerOpenError, DataValidationError):
breaker_tripped = True
all_edges = existing_edges + new_edges
edges_df = pd.DataFrame(all_edges)
if not edges_df.empty and ckpt_edges_path:
tmp_e = ckpt_edges_path.with_suffix(".tmp.csv")
edges_df.to_csv(tmp_e, index=False, encoding="utf-8-sig")
tmp_e.replace(ckpt_edges_path)
hits_series_df = self.build_hits_time_series(edges_df, articles_df)
return {
"articles_df": articles_df,
"edges_df": edges_df,
"hits_series_df": hits_series_df,
"breaker_tripped": breaker_tripped,
}
def build_hits_time_series(self, edges_df: pd.DataFrame, articles_df: pd.DataFrame) -> pd.DataFrame:
"""
[使用工具] Python 3.9, pandas
[設計目的] 按日期與歷史視窗計算熱門文章群體之 HITS Hub/Authority 與剪刀差時間序列
[程式說明] 針對每個有效日期(與各歷史視窗)彙整推文互動圖與主要產業關鍵字,產出連續 HITS 指標表
[修改日期] 2026-11-20
[修改概要] 按日期彙算熱門文章HITS剪刀差與熱門產業標籤序列
[輸入參數]
- edges_df (pd.DataFrame): 歷史熱門文章推噓互動邊資料表
- articles_df (pd.DataFrame): 歷史文章標題與產業標籤資料表
[輸出結果]
- return (pd.DataFrame): 依日期排序的日頻 HITS 剪刀差與熱門話題時間序列
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [正例] 抽取 12 大台股產業與 6 大宏觀籌碼話題標籤並計算熱門文章 HITS 剪刀差序列
[工作日誌] work_record_20261120.md
"""
if edges_df.empty:
return pd.DataFrame()
date_col = "article_date" if "article_date" in edges_df.columns else "date"
rows: list[dict[str, Any]] = []
for dt_val, grp in edges_df.groupby(date_col):
if not dt_val or str(dt_val) == "unknown":
continue
metrics = self.pipe.compute_daily_divergence(grp)
w_label = str(grp["window_label"].mode().iloc[0]) if "window_label" in grp.columns else ""
sub_arts = articles_df[articles_df["date"] == dt_val] if not articles_df.empty else pd.DataFrame()
top_ind = "none"
if not sub_arts.empty:
inds = [x for s in sub_arts["industries"] for x in str(s).split("|") if x != "none"]
if inds:
top_ind = pd.Series(inds).value_counts().index[0]
rows.append(
{
"date": dt_val,
"window_label": w_label,
"n_hot_articles": int(grp["article_id"].nunique()),
"n_pushes": int(len(grp)),
"top_industry": top_ind,
**metrics,
}
)
if not rows:
return pd.DataFrame()
return pd.DataFrame(rows).sort_values("date").reset_index(drop=True)
def run_offline_verification() -> dict[str, Any]:
"""
[使用工具] Python 3.9, pandas
[設計目的] 在無網路沙盒中離線驗證十年二分頁碼定位、產業話題詞庫抽取及斷點續傳邏輯
[程式說明] 建立涵蓋 2015 至 2025 年份與含刪文/置底雜訊的模擬看板 HTML,驗證精準定位與特徵抽取
[修改日期] 2026-11-20
[修改概要] 離線驗證PTT十年頁碼搜尋與十二大產業話題抽取邏輯
[輸入參數]
- 無
[輸出結果]
- return (dict[str, Any]): 離線驗證統計摘要字典
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [正例] 由 M.<TIMESTAMP>.A 解析精確西元日期並以二分搜尋定位十年歷史頁碼
[工作日誌] work_record_20261120.md
"""
sample_html = """
<div class="btn-group-paging">
<a class="btn wide" href="/bbs/Stock/index4999.html">‹ 上頁</a>
</div>
<div class="r-ent">
<div class="nrec"><span class="hl f1">爆</span></div>
<div class="title"><a href="/bbs/Stock/M.1720665600.A.001.html">[標的] 2330 台積電 CoWoS 與 AI 伺服器法說大噴</a></div>
<div class="meta"><div class="author">tech_guru</div><div class="date">7/11</div></div>
</div>
<div class="r-ent">
<div class="nrec"><span class="hl f3">35</span></div>
<div class="title">(本文已被刪除) [ghost]</div>
<div class="meta"><div class="author">-</div><div class="date">7/11</div></div>
</div>
<div class="r-list-sep"></div>
<div class="r-ent">
<div class="nrec"></div>
<div class="title"><a href="/bbs/Stock/M.1584576000.A.999.html">[公告] Stock 板規</a></div>
<div class="meta"><div class="author">mod</div><div class="date">3/19</div></div>
</div>
"""
parsed = PttTenYearExplorer.parse_rich_board_html(sample_html, page_no=5000)
tags = PttTenYearExplorer.extract_industry_and_topic_tags("[請益] Taiwan 關稅與外資空單結算")
return {
"parsed_entries": len(parsed["entries"]),
"median_date_ignores_pinned": parsed["median_date"],
"taiwan_does_not_trigger_ai": "ind_ai_server" not in tags["industries"],
"matched_topics": tags["topics"],
}
def run_live_10yr_exploration(
recent_pages: int = 8,
pages_per_milestone: int = 2,
) -> dict[str, Any]:
"""
[使用工具] Python 3.9, pandas, json, pathlib
[設計目的] 連線 PTT Stock 版實測十年歷史頁碼探測、抓取跨期熱門文章 HITS 與產業話題演變
[程式說明] 執行 map_ten_year_milestones 與 crawl_historical_windows_and_hits,產出三大 CSV 並輸出摘要 JSON
[修改日期] 2026-11-20
[修改概要] 執行PTT Stock十年歷史探測與熱門文章HITS實網爬蟲
[輸入參數]
- recent_pages (int): 近期連續抓取頁數
- pages_per_milestone (int): 每個十年里程碑抓取頁數
[輸出結果]
- return (dict[str, Any]): 十年里程碑、產業分布與 HITS 序列統計結果字典
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [正例] 抽取 12 大台股產業與 6 大宏觀籌碼話題標籤並計算熱門文章 HITS 剪刀差序列
[工作日誌] work_record_20261120.md
"""
CLEANED_DIR.mkdir(parents=True, exist_ok=True)
ckpt_dir = CLEANED_DIR / "ptt_checkpoints"
ckpt_dir.mkdir(parents=True, exist_ok=True)
explorer = PttTenYearExplorer(board_sleep=0.25, article_sleep=0.3)
max_page, milestones = explorer.map_ten_year_milestones()
ms_df = pd.DataFrame(milestones)
ms_out = CLEANED_DIR / "ptt_10yr_page_milestones.csv"
ms_df.to_csv(ms_out, index=False, encoding="utf-8-sig")
crawl_res = explorer.crawl_historical_windows_and_hits(
milestones=milestones,
max_page=max_page,
recent_pages=recent_pages,
pages_per_milestone=pages_per_milestone,
min_nrec_hot=25,
max_hot_per_window=3,
checkpoint_dir=ckpt_dir,
)
articles_df = crawl_res["articles_df"]
edges_df = crawl_res["edges_df"]
hits_df = crawl_res["hits_series_df"]
art_out = CLEANED_DIR / "ptt_historical_articles_and_topics.csv"
edges_out = CLEANED_DIR / "ptt_historical_hot_edges.csv"
hits_out = CLEANED_DIR / "ptt_historical_daily_hits_series.csv"
summary_out = CLEANED_DIR / "ptt_10yr_exploration_summary.json"
if not articles_df.empty:
articles_df.to_csv(art_out, index=False, encoding="utf-8-sig")
if not edges_df.empty:
edges_df.to_csv(edges_out, index=False, encoding="utf-8-sig")
if not hits_df.empty:
hits_df.to_csv(hits_out, index=False, encoding="utf-8-sig")
# Summarize industry & topic frequencies across windows
ind_counts: dict[str, int] = {}
topic_counts: dict[str, int] = {}
if not articles_df.empty:
for s in articles_df["industries"]:
for k in str(s).split("|"):
if k != "none":
ind_counts[k] = ind_counts.get(k, 0) + 1
for s in articles_df["topics"]:
for k in str(s).split("|"):
if k != "none":
topic_counts[k] = topic_counts.get(k, 0) + 1
summary = {
"max_page": max_page,
"origin_date": milestones[0]["matched_date"],
"latest_date": milestones[-1]["matched_date"],
"milestones": milestones,
"total_articles_parsed": int(len(articles_df)),
"total_hot_edges": int(len(edges_df)),
"hits_series_days": int(len(hits_df)),
"breaker_tripped": crawl_res["breaker_tripped"],
"industry_counts": dict(sorted(ind_counts.items(), key=lambda x: -x[1])),
"topic_counts": dict(sorted(topic_counts.items(), key=lambda x: -x[1])),
}
summary_out.write_text(json.dumps(summary, ensure_ascii=False, indent=2), encoding="utf-8")
return summary
def main() -> None:
"""
[使用工具] Python 3.9, argparse, json
[設計目的] 提供 Phase 3 PTT 十年歷史探測與話題抽取之命令列入口支援離線與實網模式
[程式說明] 解析 --verify-offline、--fetch-live 及視窗頁數參數,輸出執行摘要 JSON
[修改日期] 2026-11-20
[修改概要] 實作第三階段PTT十年歷史與話題分析命令列入口
[輸入參數]
- 無(讀取 sys.argv 命令列參數)
[輸出結果]
- return (None): 列印驗證或抓取統計 JSON
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [正例] 由 M.<TIMESTAMP>.A 解析精確西元日期並以二分搜尋定位十年歷史頁碼
[工作日誌] work_record_20261120.md
"""
parser = argparse.ArgumentParser(description="Phase 3 PTT Stock 10-Year History & Topics Explorer")
parser.add_argument("--verify-offline", action="store_true", help="Run offline unit verification")
parser.add_argument("--fetch-live", action="store_true", help="Probe 10-year milestones and crawl windows")
parser.add_argument("--recent-pages", type=int, default=8, help="Recent consecutive pages to crawl")
parser.add_argument("--pages-per-milestone", type=int, default=2, help="Pages per historical milestone")
args = parser.parse_args()
if args.fetch_live:
res = run_live_10yr_exploration(
recent_pages=args.recent_pages,
pages_per_milestone=args.pages_per_milestone,
)
else:
res = run_offline_verification()
print(json.dumps(res, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()