first commit
This commit is contained in:
@@ -0,0 +1,529 @@
|
||||
"""Phase 1: Data audit, cleaning, zero-sum reconstruction, and exploratory trend/correlation analysis."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
||||
RAW_DIR = PROJECT_ROOT / "data" / "raw"
|
||||
CLEANED_DIR = PROJECT_ROOT / "data" / "cleaned"
|
||||
|
||||
TW_STOCK_PATH = RAW_DIR / "tw_stock.xlsx"
|
||||
FUTURES_OI_PATH = RAW_DIR / "futures_oi.xlsx"
|
||||
MERGED_PATH = RAW_DIR / "futures_stock_merged.xlsx"
|
||||
|
||||
MAJOR_PRODUCTS = ["臺股期貨", "小型臺指期貨", "電子期貨", "金融期貨", "微型臺指期貨"]
|
||||
INSTITUTIONS = ["外資及陸資", "投信", "自營商"]
|
||||
|
||||
|
||||
def parse_roc_date(val: Any) -> pd.Timestamp:
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas
|
||||
[設計目的] 將台股試算表混雜的民國日期與閏年字串統一轉換為標準時間戳記
|
||||
[程式說明] 解析如 '0100/01/03' 民國日期並加 1911,同時顯式修補 2024-02-29 變成 3935 年之公式異常
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 實作民國日期解析與2024閏年異常日期字串修補邏輯
|
||||
[輸入參數]
|
||||
- val (Any): 原始試算表日期欄位值(字串或時間物件)
|
||||
[輸出結果]
|
||||
- return (pd.Timestamp): 標準化西元時間戳記,無法解析時回傳 NaT
|
||||
[關聯測試] Feature: 台股現貨與期貨資料修復及零和對手方還原 / Scenario: [正例] 正確解析民國日期、去重 3 倍重複位移並以大台隱含指數驗證對齊
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
s = str(val).strip()
|
||||
if s.startswith("2024-02-29"):
|
||||
return pd.Timestamp("2024-02-29")
|
||||
parts = s.split("/")
|
||||
if len(parts) == 3:
|
||||
year = int(parts[0])
|
||||
if year < 1911:
|
||||
year += 1911
|
||||
return pd.Timestamp(year=year, month=int(parts[1]), day=int(parts[2]))
|
||||
return pd.to_datetime(s, errors="coerce")
|
||||
|
||||
|
||||
def safe_corr(s1: pd.Series, s2: pd.Series) -> float:
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas
|
||||
[設計目的] 安全計算兩條金融序列之皮爾森相關係數並防範全零常數序列除零警告
|
||||
[程式說明] 先對兩序列執行成對缺值移除,若有效樣本數不足 3 或任一標準差為 0 則直接回傳 NaN
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 新增零變異數檢查以消除微型臺指投信全零部位警告
|
||||
[輸入參數]
|
||||
- s1 (pd.Series): 第一條數值序列
|
||||
- s2 (pd.Series): 第二條數值序列
|
||||
[輸出結果]
|
||||
- return (float): 四捨五入至小數第四位之相關係數或 NaN
|
||||
[關聯測試] Feature: 台股現貨與期貨資料修復及零和對手方還原 / Scenario: [正例] 利用期貨市場零和恆等式反推非三大法人隱含散戶淨部位
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
pair = pd.concat([s1, s2], axis=1).dropna()
|
||||
if len(pair) < 3 or pair.iloc[:, 0].std() == 0 or pair.iloc[:, 1].std() == 0:
|
||||
return float("nan")
|
||||
return round(float(pair.iloc[:, 0].corr(pair.iloc[:, 1])), 4)
|
||||
|
||||
|
||||
def repair_taiex_spot(futures_dates: pd.Series) -> tuple[pd.DataFrame, dict[str, Any]]:
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas, openpyxl
|
||||
[設計目的] 徹底修復原始股市試算表之排序錯置、3 倍重複貼上位移與錯誤衍生公式
|
||||
[程式說明] 重組錯亂年份區塊並對 2597..3219 執行連續相同 OHLC 游程去重,再重算因果均線與 t+1..t+k 報酬標籤
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 完成現貨排序修復、三倍游程去重及嚴格因果標籤重算
|
||||
[輸入參數]
|
||||
- futures_dates (pd.Series): 期交所真實交易日曆序列(供對齊去重後之 2022/08~2023/06 交易日)
|
||||
[輸出結果]
|
||||
- return (tuple[pd.DataFrame, dict[str, Any]]): 修復後 3,049 日現貨資料表與稽核統計字典
|
||||
[關聯測試] Feature: 台股現貨與期貨資料修復及零和對手方還原 / Scenario: [Pre-mortem] 試算表錯誤滾動公式導致未來標籤或日內震幅遭到污染
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
raw = pd.read_excel(TW_STOCK_PATH, sheet_name="彙總")
|
||||
raw.columns = [str(c).replace("\n", "").strip() for c in raw.columns]
|
||||
raw["parsed_dt"] = raw["日期"].apply(parse_roc_date)
|
||||
|
||||
normal_p1 = raw.iloc[0:2597].copy()
|
||||
normal_p1["source_block"] = "p1_2011_to_202107"
|
||||
normal_p2 = raw.iloc[3358:3464].copy()
|
||||
normal_p2["source_block"] = "p2_202108_to_202112_misplaced_tail"
|
||||
normal_p3 = raw.iloc[3220:3358].copy()
|
||||
normal_p3["source_block"] = "p3_202201_to_202207_misplaced_mid"
|
||||
|
||||
corrupted = raw.iloc[2597:3220].copy()
|
||||
ohlc_cols = ["開盤指數", "最高指數", "最低指數", "收盤指數"]
|
||||
ohlc_tuples = pd.Series(list(zip(*(corrupted[c] for c in ohlc_cols))), index=corrupted.index)
|
||||
run_mask = ohlc_tuples != ohlc_tuples.shift(1)
|
||||
dedup_p4 = corrupted.loc[run_mask].copy().reset_index(drop=True)
|
||||
dedup_p4["source_block"] = "p4_202208_to_202306_dedup_realigned"
|
||||
|
||||
true_after_dates = (
|
||||
futures_dates[futures_dates >= pd.Timestamp("2022-08-01")]
|
||||
.drop_duplicates()
|
||||
.sort_values()
|
||||
.reset_index(drop=True)
|
||||
)
|
||||
if len(true_after_dates) < len(dedup_p4):
|
||||
raise ValueError("Insufficient futures trading dates to align deduplicated spot block.")
|
||||
|
||||
dedup_p4["reported_dt_corrupted"] = dedup_p4["parsed_dt"]
|
||||
dedup_p4["parsed_dt"] = true_after_dates.iloc[: len(dedup_p4)].values
|
||||
|
||||
for df_part in (normal_p1, normal_p2, normal_p3):
|
||||
df_part["reported_dt_corrupted"] = df_part["parsed_dt"]
|
||||
|
||||
keep_cols = ["parsed_dt", "reported_dt_corrupted", "source_block"] + ohlc_cols
|
||||
cleaned = pd.concat(
|
||||
[normal_p1[keep_cols], normal_p2[keep_cols], normal_p3[keep_cols], dedup_p4[keep_cols]],
|
||||
ignore_index=True,
|
||||
)
|
||||
cleaned = cleaned.rename(
|
||||
columns={
|
||||
"parsed_dt": "date",
|
||||
"開盤指數": "open",
|
||||
"最高指數": "high",
|
||||
"最低指數": "low",
|
||||
"收盤指數": "close",
|
||||
}
|
||||
)
|
||||
cleaned = cleaned.sort_values("date").reset_index(drop=True)
|
||||
|
||||
cleaned["true_high_low_diff"] = cleaned["high"] - cleaned["low"]
|
||||
cleaned["true_high_low_pct"] = cleaned["true_high_low_diff"] / cleaned["low"]
|
||||
cleaned["open_close_diff"] = cleaned["close"] - cleaned["open"]
|
||||
cleaned["intraday_ret"] = cleaned["close"] / cleaned["open"] - 1.0
|
||||
cleaned["ret_1d"] = cleaned["close"].pct_change()
|
||||
|
||||
for w in (3, 5, 10, 15, 20, 60):
|
||||
cleaned[f"ma_{w}d_close"] = cleaned["close"].rolling(w).mean()
|
||||
cleaned[f"bias_{w}d"] = cleaned["close"] / cleaned[f"ma_{w}d_close"] - 1.0
|
||||
|
||||
for k in (1, 3, 5, 10, 15):
|
||||
cleaned[f"fwd_ret_{k}d"] = cleaned["close"].shift(-k) / cleaned["close"] - 1.0
|
||||
fwd_open_avg = sum(cleaned["open"].shift(-i) for i in range(1, k + 1)) / float(k)
|
||||
cleaned[f"fwd_{k}d_open_mean"] = fwd_open_avg
|
||||
cleaned[f"fwd_{k}d_open_diff_pct"] = fwd_open_avg / cleaned["open"] - 1.0
|
||||
|
||||
audit_info = {
|
||||
"raw_spot_rows": int(len(raw)),
|
||||
"repaired_spot_rows": int(len(cleaned)),
|
||||
"spot_min_date": str(cleaned["date"].min().date()),
|
||||
"spot_max_date": str(cleaned["date"].max().date()),
|
||||
"corrupted_3x_block_raw_rows": int(len(corrupted)),
|
||||
"corrupted_3x_block_unique_days": int(len(dedup_p4)),
|
||||
"leap_year_bug_rows": int((raw["西元年"] == 3935).sum()),
|
||||
}
|
||||
return cleaned, audit_info
|
||||
|
||||
|
||||
def enrich_taifex_futures() -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]:
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas, numpy
|
||||
[設計目的] 讀取期貨未平倉資料,反推零和隱含散戶淨部位並還原大台隱含指數
|
||||
[程式說明] 依總多單等於總空單恆等式加總三大法人淨部位取負值,並用每點 0.2 千元換算大台結算與成交均價
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 實作期貨零和隱含散戶推導與大台契約隱含指數還原
|
||||
[輸入參數]
|
||||
- 無(讀取常數 FUTURES_OI_PATH 指定之原始檔案)
|
||||
[輸出結果]
|
||||
- return (tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]): 強化期貨長表、大台隱含價格表與稽核字典
|
||||
[關聯測試] Feature: 台股現貨與期貨資料修復及零和對手方還原 / Scenario: [Pre-mortem] 末日全市場未平倉為 0 的未結算快照污染日變動量與隱含指數
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
foi = pd.read_excel(FUTURES_OI_PATH, sheet_name="工作表1")
|
||||
foi["date"] = pd.to_datetime(foi["日期"])
|
||||
|
||||
num_cols = [
|
||||
"多方交易口數",
|
||||
"多方交易契約金額(千元)",
|
||||
"空方交易口數",
|
||||
"空方交易契約金額(千元)",
|
||||
"多空交易口數淨額",
|
||||
"多空交易契約金額淨額(千元)",
|
||||
"多方未平倉口數",
|
||||
"多方未平倉契約金額(千元)",
|
||||
"空方未平倉口數",
|
||||
"空方未平倉契約金額(千元)",
|
||||
"多空未平倉口數淨額",
|
||||
"多空未平倉契約金額淨額(千元)",
|
||||
]
|
||||
inst_sum = foi.groupby(["date", "商品名稱"], as_index=False)[num_cols].sum()
|
||||
retail = inst_sum.copy()
|
||||
retail["身份別"] = "非三大法人(隱含散戶淨額)"
|
||||
for col in [
|
||||
"多空交易口數淨額",
|
||||
"多空交易契約金額淨額(千元)",
|
||||
"多空未平倉口數淨額",
|
||||
"多空未平倉契約金額淨額(千元)",
|
||||
]:
|
||||
retail[col] = -retail[col]
|
||||
for col in [
|
||||
"多方交易口數",
|
||||
"多方交易契約金額(千元)",
|
||||
"空方交易口數",
|
||||
"空方交易契約金額(千元)",
|
||||
"多方未平倉口數",
|
||||
"多方未平倉契約金額(千元)",
|
||||
"空方未平倉口數",
|
||||
"空方未平倉契約金額(千元)",
|
||||
]:
|
||||
retail[col] = np.nan
|
||||
|
||||
enriched = pd.concat(
|
||||
[foi[["date", "商品名稱", "身份別"] + num_cols], retail[["date", "商品名稱", "身份別"] + num_cols]],
|
||||
ignore_index=True,
|
||||
).sort_values(["date", "商品名稱", "身份別"])
|
||||
|
||||
tx_sub = foi[foi["商品名稱"] == "臺股期貨"].groupby("date", as_index=False)[
|
||||
["多方未平倉口數", "多方未平倉契約金額(千元)", "多方交易口數", "多方交易契約金額(千元)"]
|
||||
].sum()
|
||||
tx_sub["tx_implied_oi_price"] = np.where(
|
||||
tx_sub["多方未平倉口數"] > 0,
|
||||
tx_sub["多方未平倉契約金額(千元)"] / (tx_sub["多方未平倉口數"] * 0.2),
|
||||
np.nan,
|
||||
)
|
||||
tx_sub["tx_implied_vwap_price"] = np.where(
|
||||
tx_sub["多方交易口數"] > 0,
|
||||
tx_sub["多方交易契約金額(千元)"] / (tx_sub["多方交易口數"] * 0.2),
|
||||
np.nan,
|
||||
)
|
||||
tx_sub = tx_sub.sort_values("date").reset_index(drop=True)
|
||||
|
||||
zero_oi_dates = foi.groupby("date")["多方未平倉口數"].sum()
|
||||
zero_oi_list = [str(d.date()) for d in zero_oi_dates[zero_oi_dates == 0].index]
|
||||
|
||||
audit_info = {
|
||||
"raw_futures_rows": int(len(foi)),
|
||||
"unique_trading_days": int(foi["date"].nunique()),
|
||||
"futures_min_date": str(foi["date"].min().date()),
|
||||
"futures_max_date": str(foi["date"].max().date()),
|
||||
"n_products": int(foi["商品名稱"].nunique()),
|
||||
"products": sorted(foi["商品名稱"].unique().tolist()),
|
||||
"zero_oi_dates": zero_oi_list,
|
||||
}
|
||||
return enriched, tx_sub[["date", "tx_implied_oi_price", "tx_implied_vwap_price"]], audit_info
|
||||
|
||||
|
||||
def build_daily_feature_table(
|
||||
spot_df: pd.DataFrame,
|
||||
futures_enriched: pd.DataFrame,
|
||||
tx_price_df: pd.DataFrame,
|
||||
) -> pd.DataFrame:
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas, numpy
|
||||
[設計目的] 整合現貨指數、大台隱含價與主要期貨籌碼以產出無未結算汙染之日頻特徵表
|
||||
[程式說明] 以交易日為主鍵展開五大期貨四大參與者淨部位與日變動量,並在末日無 OI 時自動切換 VWAP 代理
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 整合期現貨資料與四大參與者日頻籌碼特徵寬表
|
||||
[輸入參數]
|
||||
- spot_df (pd.DataFrame): 修復後現貨日線資料表
|
||||
- futures_enriched (pd.DataFrame): 含隱含散戶之期貨長表
|
||||
- tx_price_df (pd.DataFrame): 大台隱含結算價與成交均價序列
|
||||
[輸出結果]
|
||||
- return (pd.DataFrame): 2021-09-27 至 2025-03-03 之 830 日特徵主表
|
||||
[關聯測試] Feature: 台股現貨與期貨資料修復及零和對手方還原 / Scenario: [Pre-mortem] 末日全市場未平倉為 0 的未結算快照污染日變動量與隱含指數
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
sub = futures_enriched[futures_enriched["商品名稱"].isin(MAJOR_PRODUCTS)].copy()
|
||||
piv_oi = sub.pivot_table(
|
||||
index="date", columns=["商品名稱", "身份別"], values="多空未平倉口數淨額", aggfunc="first"
|
||||
)
|
||||
piv_tr = sub.pivot_table(
|
||||
index="date", columns=["商品名稱", "身份別"], values="多空交易口數淨額", aggfunc="first"
|
||||
)
|
||||
piv_oi_amt = sub.pivot_table(
|
||||
index="date", columns=["商品名稱", "身份別"], values="多空未平倉契約金額淨額(千元)", aggfunc="first"
|
||||
)
|
||||
|
||||
daily = tx_price_df.set_index("date").copy()
|
||||
spot_indexed = spot_df.set_index("date")[
|
||||
["open", "high", "low", "close", "true_high_low_diff", "ret_1d", "fwd_ret_1d", "fwd_ret_3d", "fwd_ret_5d", "fwd_ret_10d", "fwd_ret_15d"]
|
||||
].rename(columns={"ret_1d": "spot_ret_1d"})
|
||||
daily = daily.join(spot_indexed, how="left")
|
||||
|
||||
daily["index_proxy"] = daily["close"].fillna(daily["tx_implied_oi_price"]).fillna(daily["tx_implied_vwap_price"])
|
||||
daily["tx_basis"] = daily["tx_implied_oi_price"] - daily["close"]
|
||||
daily["proxy_ret_1d"] = daily["index_proxy"].pct_change(fill_method=None)
|
||||
for k in (1, 3, 5, 10, 15):
|
||||
daily[f"proxy_fwd_ret_{k}d"] = daily["index_proxy"].shift(-k) / daily["index_proxy"] - 1.0
|
||||
|
||||
prod_slug = {
|
||||
"臺股期貨": "tx",
|
||||
"小型臺指期貨": "mtx",
|
||||
"電子期貨": "te",
|
||||
"金融期貨": "tf",
|
||||
"微型臺指期貨": "tmf",
|
||||
}
|
||||
id_slug = {
|
||||
"外資及陸資": "foreign",
|
||||
"投信": "trust",
|
||||
"自營商": "dealer",
|
||||
"非三大法人(隱含散戶淨額)": "retail_implied",
|
||||
}
|
||||
|
||||
for prod, p_code in prod_slug.items():
|
||||
for id_name, i_code in id_slug.items():
|
||||
if (prod, id_name) in piv_oi.columns:
|
||||
oi_s = piv_oi[(prod, id_name)]
|
||||
oi_s = oi_s.where(daily["tx_implied_oi_price"].notna(), np.nan)
|
||||
daily[f"{p_code}_{i_code}_oi_net"] = oi_s
|
||||
daily[f"{p_code}_{i_code}_doi"] = oi_s.diff()
|
||||
if (prod, id_name) in piv_tr.columns:
|
||||
daily[f"{p_code}_{i_code}_trade_net"] = piv_tr[(prod, id_name)]
|
||||
if (prod, id_name) in piv_oi_amt.columns:
|
||||
amt_s = piv_oi_amt[(prod, id_name)].where(daily["tx_implied_oi_price"].notna(), np.nan)
|
||||
daily[f"{p_code}_{i_code}_oi_amt_k"] = amt_s
|
||||
|
||||
mtx_tot_oi = futures_enriched[
|
||||
(futures_enriched["商品名稱"] == "小型臺指期貨") & (futures_enriched["身份別"].isin(INSTITUTIONS))
|
||||
].groupby("date")["多方未平倉口數"].sum()
|
||||
daily["mtx_inst_long_oi"] = mtx_tot_oi.where(daily["tx_implied_oi_price"].notna(), np.nan)
|
||||
|
||||
return daily.reset_index()
|
||||
|
||||
|
||||
def audit_merged_workbook(spot_df: pd.DataFrame) -> dict[str, Any]:
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas, openpyxl
|
||||
[設計目的] 量化驗證原始合併工作簿的 VLOOKUP 抓錯欄位與日期截斷偏差
|
||||
[程式說明] 比對原始合併表「對應股市收盤」與修復後真實開盤/收盤價差,並統計截斷後的最終遺漏天數
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 稽核並量化原始合併工作簿VLOOKUP錯欄與日期截斷誤差
|
||||
[輸入參數]
|
||||
- spot_df (pd.DataFrame): 修復後之台股現貨日線資料表
|
||||
[輸出結果]
|
||||
- return (dict[str, Any]): 合併表稽核指標與誤差統計字典
|
||||
[關聯測試] Feature: 台股現貨與期貨資料修復及零和對手方還原 / Scenario: [正例] 正確解析民國日期、去重 3 倍重複位移並以大台隱含指數驗證對齊
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
m_f = pd.read_excel(MERGED_PATH, sheet_name="期貨")
|
||||
m_f["date"] = pd.to_datetime(m_f["日期"])
|
||||
m_daily = m_f.groupby("date", as_index=False)["對應股市收盤"].first()
|
||||
cmp = pd.merge(m_daily, spot_df[["date", "open", "close"]], on="date", how="inner")
|
||||
cmp["diff_vs_open"] = (cmp["對應股市收盤"] - cmp["open"]).abs()
|
||||
cmp["diff_vs_close"] = (cmp["對應股市收盤"] - cmp["close"]).abs()
|
||||
|
||||
post_202208 = m_daily[m_daily["date"] >= "2022-08-01"]
|
||||
return {
|
||||
"merged_futures_rows": int(len(m_f)),
|
||||
"merged_unique_dates": int(m_f["date"].nunique()),
|
||||
"merged_min_date": str(m_f["date"].min().date()),
|
||||
"merged_max_date": str(m_f["date"].max().date()),
|
||||
"pre_202208_overlap_days": int((cmp["date"] < "2022-08-01").sum()),
|
||||
"pre_202208_mae_vs_open": float(cmp.loc[cmp["date"] < "2022-08-01", "diff_vs_open"].mean()),
|
||||
"pre_202208_mae_vs_close": float(cmp.loc[cmp["date"] < "2022-08-01", "diff_vs_close"].mean()),
|
||||
"post_202208_rows_count": int(len(post_202208)),
|
||||
"merged_20240927_reported_index": float(post_202208.iloc[-1]["對應股市收盤"]),
|
||||
}
|
||||
|
||||
|
||||
def compute_summary_stats(spot_df: pd.DataFrame, daily: pd.DataFrame) -> dict[str, Any]:
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas, numpy
|
||||
[設計目的] 計算 2011–2025 台股分年走勢、月度季節性及法人/隱含散戶多期相關性矩陣
|
||||
[程式說明] 統計交叉驗證精度、年化波動與漲跌幅、五大期貨四身份領先滯後相關係數及月度日均基點勝率
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 產出跨年度走勢、季節性統計與四大參與者相關矩陣摘要
|
||||
[輸入參數]
|
||||
- spot_df (pd.DataFrame): 修復後台股現貨資料表
|
||||
- daily (pd.DataFrame): 整合後 830 日期現貨特徵主表
|
||||
[輸出結果]
|
||||
- return (dict[str, Any]): 完整統計摘要字典供報表輸出與後續建模對照
|
||||
[關聯測試] Feature: 台股現貨與期貨資料修復及零和對手方還原 / Scenario: [正例] 利用期貨市場零和恆等式反推非三大法人隱含散戶淨部位
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
ov = daily.dropna(subset=["close", "tx_implied_oi_price"]).copy()
|
||||
ov_pre = ov[ov["date"] < "2022-08-01"]
|
||||
ov_post = ov[ov["date"] >= "2022-08-01"]
|
||||
|
||||
spot_yr = spot_df.copy()
|
||||
spot_yr["year"] = spot_yr["date"].dt.year
|
||||
yr_spot_stats = []
|
||||
for y, g in spot_yr.groupby("year"):
|
||||
yr_spot_stats.append(
|
||||
{
|
||||
"year": int(y),
|
||||
"days": int(len(g)),
|
||||
"start_open": round(float(g["open"].iloc[0]), 2),
|
||||
"end_close": round(float(g["close"].iloc[-1]), 2),
|
||||
"min_low": round(float(g["low"].min()), 2),
|
||||
"max_high": round(float(g["high"].max()), 2),
|
||||
"ann_vol_pct": round(float(g["ret_1d"].std() * np.sqrt(245) * 100), 2),
|
||||
"yr_ret_pct": round(float((g["close"].iloc[-1] / g["open"].iloc[0] - 1.0) * 100), 2),
|
||||
}
|
||||
)
|
||||
|
||||
d_yr = daily.dropna(subset=["index_proxy"]).copy()
|
||||
d_yr["year"] = d_yr["date"].dt.year
|
||||
yr_proxy_stats = []
|
||||
for y, g in d_yr.groupby("year"):
|
||||
yr_proxy_stats.append(
|
||||
{
|
||||
"year": int(y),
|
||||
"days": int(len(g)),
|
||||
"start_px": round(float(g["index_proxy"].iloc[0]), 2),
|
||||
"end_px": round(float(g["index_proxy"].iloc[-1]), 2),
|
||||
"min_px": round(float(g["index_proxy"].min()), 2),
|
||||
"max_px": round(float(g["index_proxy"].max()), 2),
|
||||
"ann_vol_pct": round(float(g["proxy_ret_1d"].std() * np.sqrt(245) * 100), 2),
|
||||
"ret_pct": round(float((g["index_proxy"].iloc[-1] / g["index_proxy"].iloc[0] - 1.0) * 100), 2),
|
||||
}
|
||||
)
|
||||
|
||||
corr_rows = []
|
||||
for p_code, p_name in [
|
||||
("tx", "臺股期貨"),
|
||||
("mtx", "小型臺指期貨"),
|
||||
("te", "電子期貨"),
|
||||
("tf", "金融期貨"),
|
||||
("tmf", "微型臺指期貨"),
|
||||
]:
|
||||
for i_code, i_name in [
|
||||
("foreign", "外資及陸資"),
|
||||
("trust", "投信"),
|
||||
("dealer", "自營商"),
|
||||
("retail_implied", "隱含散戶(非三大法人)"),
|
||||
]:
|
||||
oi_col = f"{p_code}_{i_code}_oi_net"
|
||||
doi_col = f"{p_code}_{i_code}_doi"
|
||||
tr_col = f"{p_code}_{i_code}_trade_net"
|
||||
if oi_col not in daily.columns:
|
||||
continue
|
||||
valid_n = int(daily[[oi_col, "tx_implied_oi_price"]].dropna().shape[0])
|
||||
corr_rows.append(
|
||||
{
|
||||
"product": p_name,
|
||||
"participant": i_name,
|
||||
"n_oi": valid_n,
|
||||
"corr_px_oi": safe_corr(daily["index_proxy"], daily[oi_col]),
|
||||
"corr_ret1d_trade": safe_corr(daily["proxy_ret_1d"], daily[tr_col]),
|
||||
"corr_ret1d_doi": safe_corr(daily["proxy_ret_1d"], daily[doi_col]),
|
||||
"corr_fwd1d_oi": safe_corr(daily["proxy_fwd_ret_1d"], daily[oi_col]),
|
||||
"corr_fwd5d_oi": safe_corr(daily["proxy_fwd_ret_5d"], daily[oi_col]),
|
||||
"corr_fwd15d_oi": safe_corr(daily["proxy_fwd_ret_15d"], daily[oi_col]),
|
||||
"corr_fwd5d_doi": safe_corr(daily["proxy_fwd_ret_5d"], daily[doi_col]),
|
||||
"corr_fwd5d_trade": safe_corr(daily["proxy_fwd_ret_5d"], daily[tr_col]),
|
||||
}
|
||||
)
|
||||
|
||||
spot_q = spot_df.copy()
|
||||
spot_q["month"] = spot_q["date"].dt.month
|
||||
monthly_spot = spot_q.groupby("month").agg(
|
||||
n_days=("ret_1d", "count"),
|
||||
mean_daily_bp=("ret_1d", lambda s: round(float(s.mean() * 10000), 2)),
|
||||
win_rate_pct=("ret_1d", lambda s: round(float((s > 0).mean() * 100), 2)),
|
||||
ann_vol_pct=("ret_1d", lambda s: round(float(s.std() * np.sqrt(245) * 100), 2)),
|
||||
)
|
||||
|
||||
return {
|
||||
"overlap_pre_202208_n": int(len(ov_pre)),
|
||||
"overlap_pre_202208_corr": round(float(ov_pre["close"].corr(ov_pre["tx_implied_oi_price"])), 6),
|
||||
"overlap_pre_202208_mae": round(float((ov_pre["close"] - ov_pre["tx_implied_oi_price"]).abs().mean()), 2),
|
||||
"overlap_post_202208_n": int(len(ov_post)),
|
||||
"overlap_post_202208_corr": round(float(ov_post["close"].corr(ov_post["tx_implied_oi_price"])), 6),
|
||||
"overlap_post_202208_mae": round(float((ov_post["close"] - ov_post["tx_implied_oi_price"]).abs().mean()), 2),
|
||||
"annual_spot": yr_spot_stats,
|
||||
"annual_proxy": yr_proxy_stats,
|
||||
"correlations": corr_rows,
|
||||
"monthly_spot_2011_2023": monthly_spot.reset_index().to_dict(orient="records"),
|
||||
}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas, json, pathlib
|
||||
[設計目的] 串接執行第一階段資料修復、強化特徵建構、稽核驗證與檔案輸出主流程
|
||||
[程式說明] 依序呼叫期貨強化、現貨修復、合併表稽核與統計計算,並將 4 份乾淨結果寫入 data/cleaned
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 執行第一階段端到端資料清洗落盤與統計摘要輸出
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (None): 輸出清理後 CSV/JSON 至 data/cleaned 並於終端機印出驗證表
|
||||
[關聯測試] Feature: 台股現貨與期貨資料修復及零和對手方還原 / Scenario: [正例] 正確解析民國日期、去重 3 倍重複位移並以大台隱含指數驗證對齊
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
CLEANED_DIR.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
futures_enriched, tx_price_df, fut_audit = enrich_taifex_futures()
|
||||
spot_df, spot_audit = repair_taiex_spot(tx_price_df["date"])
|
||||
merged_audit = audit_merged_workbook(spot_df)
|
||||
daily_df = build_daily_feature_table(spot_df, futures_enriched, tx_price_df)
|
||||
summary = compute_summary_stats(spot_df, daily_df)
|
||||
|
||||
spot_out = CLEANED_DIR / "taiex_spot_repaired_2011_202306.csv"
|
||||
fut_out = CLEANED_DIR / "taifex_futures_enriched_202109_202503.csv"
|
||||
daily_out = CLEANED_DIR / "merged_daily_market_features_202109_202503.csv"
|
||||
summary_out = CLEANED_DIR / "phase1_audit_and_eda_summary.json"
|
||||
|
||||
spot_df.to_csv(spot_out, index=False, encoding="utf-8-sig")
|
||||
futures_enriched.to_csv(fut_out, index=False, encoding="utf-8-sig")
|
||||
daily_df.to_csv(daily_out, index=False, encoding="utf-8-sig")
|
||||
|
||||
full_report = {
|
||||
"spot_audit": spot_audit,
|
||||
"futures_audit": fut_audit,
|
||||
"merged_workbook_audit": merged_audit,
|
||||
"eda_summary": summary,
|
||||
}
|
||||
summary_out.write_text(json.dumps(full_report, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
print("=== PHASE 1 AUDIT & EDA COMPLETE ===")
|
||||
print("Spot audit:", json.dumps(spot_audit, ensure_ascii=False))
|
||||
print("Futures audit:", json.dumps({k: v for k, v in fut_audit.items() if k != "products"}, ensure_ascii=False))
|
||||
print("Merged workbook audit:", json.dumps(merged_audit, ensure_ascii=False))
|
||||
print(
|
||||
f"Cross-validation: pre-2022/08 n={summary['overlap_pre_202208_n']} corr={summary['overlap_pre_202208_corr']} MAE={summary['overlap_pre_202208_mae']} | "
|
||||
f"repaired post-2022/08 n={summary['overlap_post_202208_n']} corr={summary['overlap_post_202208_corr']} MAE={summary['overlap_post_202208_mae']}"
|
||||
)
|
||||
print("\n--- Correlation Summary ---")
|
||||
print(pd.DataFrame(summary["correlations"]).to_string(index=False))
|
||||
print("\n--- Monthly Seasonality (2011-2023/06) ---")
|
||||
print(pd.DataFrame(summary["monthly_spot_2011_2023"]).to_string(index=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,799 @@
|
||||
"""Phase 7: Live data backfill through 2026-11-20 (TWSE Spot, TAIFEX Put/Call, TAIFEX 3-Institutions Futures) and full reanalysis."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import datetime as dt
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
SRC_DIR = Path(__file__).resolve().parent
|
||||
PROJECT_ROOT = SRC_DIR.parent
|
||||
if str(SRC_DIR) not in sys.path:
|
||||
sys.path.insert(0, str(SRC_DIR))
|
||||
|
||||
from phase1_data_audit_and_eda import INSTITUTIONS, MAJOR_PRODUCTS, safe_corr
|
||||
from phase2_data_supplement_and_hits import DataValidationError, TaifexPcRatioSupplementer, TwseSpotSupplementer
|
||||
|
||||
RAW_DIR = PROJECT_ROOT / "data" / "raw"
|
||||
CLEANED_DIR = PROJECT_ROOT / "data" / "cleaned"
|
||||
MARKET_TW_DIR = PROJECT_ROOT / "data" / "market_data" / "tw"
|
||||
GLOBAL_FUT_DIR = PROJECT_ROOT / "data" / "market_data" / "global_index_futures"
|
||||
ALIGNED_DIR = PROJECT_ROOT / "data" / "features_aligned"
|
||||
CACHE_DIR = CLEANED_DIR / "live_cache_202503_202611"
|
||||
|
||||
GLOBAL_FUTURES_PRODUCTS = [
|
||||
"美國道瓊期貨",
|
||||
"美國標普500期貨",
|
||||
"美國那斯達克100期貨",
|
||||
"美國費城半導體期貨",
|
||||
"東證期貨",
|
||||
"英國富時100期貨",
|
||||
]
|
||||
|
||||
|
||||
class TaifexFuturesInstitutionalSupplementer:
|
||||
"""
|
||||
[使用工具] Python 3.9, urllib, csv, ssl, certifi, pandas
|
||||
[設計目的] 從期交所 futContractsDateDown 分批補抓三大法人區分各期貨契約交易與未平倉數據
|
||||
[程式說明] 遵守期交所 30 天查詢上限切窗送出 POST 請求,解碼 CP950 CSV 並自動防呆契約金額單位與 HTML 錯誤頁
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 實作期交所三大法人期貨分批抓補與單位檢查器
|
||||
[輸入參數]
|
||||
- timeout (int): HTTP 請求逾時秒數,預設 20 秒
|
||||
- sleep_sec (float): 連續分批查詢間休眠秒數,預設 0.6 秒
|
||||
[輸出結果]
|
||||
- instance (TaifexFuturesInstitutionalSupplementer): 期貨三大法人資料補充器實例
|
||||
[關聯測試] Feature: 官方源頭資料即時更新至 2026/11/20 與全模型、圖表文總覽重新計算驗證 / Scenario: [正例] 分批抓取並解析 TAIFEX futContractsDateDown 期貨三大法人 CSV 並還原零和隱含散戶至 2026/11/20
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
|
||||
FUT_CONTRACTS_URL = "https://www.taifex.com.tw/cht/3/futContractsDateDown"
|
||||
NUM_COLS = [
|
||||
"多方交易口數",
|
||||
"多方交易契約金額(千元)",
|
||||
"空方交易口數",
|
||||
"空方交易契約金額(千元)",
|
||||
"多空交易口數淨額",
|
||||
"多空交易契約金額淨額(千元)",
|
||||
"多方未平倉口數",
|
||||
"多方未平倉契約金額(千元)",
|
||||
"空方未平倉口數",
|
||||
"空方未平倉契約金額(千元)",
|
||||
"多空未平倉口數淨額",
|
||||
"多空未平倉契約金額淨額(千元)",
|
||||
]
|
||||
|
||||
def __init__(self, timeout: int = 20, sleep_sec: float = 0.6) -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, ssl, certifi
|
||||
[設計目的] 初始化期貨三大法人爬蟲之 TLS 根憑證驗證環境與瀏覽器來源標頭
|
||||
[程式說明] 設定 Referer 與表單標頭避免遭到期交所防火牆拒絶,並設定重試間隔與逾時秒數
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 初始化期交所期貨三大法人爬蟲連線標頭與憑證環境
|
||||
[輸入參數]
|
||||
- timeout (int): 請求逾時秒數
|
||||
- sleep_sec (float): 查詢間隔休眠秒數
|
||||
[輸出結果]
|
||||
- return (None): 設定實例連線屬性
|
||||
[關聯測試] Feature: 官方源頭資料即時更新至 2026/11/20 與全模型、圖表文總覽重新計算驗證 / Scenario: [正例] 分批抓取並解析 TAIFEX futContractsDateDown 期貨三大法人 CSV 並還原零和隱含散戶至 2026/11/20
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
import ssl
|
||||
|
||||
import certifi
|
||||
|
||||
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",
|
||||
"Referer": "https://www.taifex.com.tw/cht/3/futContractsDate",
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _parse_num(raw_str: str) -> float:
|
||||
"""
|
||||
[使用工具] Python 3.9
|
||||
[設計目的] 清理期貨 CSV 儲存格千分位逗號及連字號並轉為浮點數
|
||||
[程式說明] 去除空白與千分位逗號後強制轉型浮點數,遇到空白或 '--' 轉成 0.0 供整數口數與金額加總
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 清理期交所期貨CSV數值字串逗號並轉換為浮點數
|
||||
[輸入參數]
|
||||
- raw_str (str): CSV 數值字串
|
||||
[輸出結果]
|
||||
- return (float): 解析後浮點數
|
||||
[關聯測試] Feature: 官方源頭資料即時更新至 2026/11/20 與全模型、圖表文總覽重新計算驗證 / Scenario: [正例] 分批抓取並解析 TAIFEX futContractsDateDown 期貨三大法人 CSV 並還原零和隱含散戶至 2026/11/20
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
cleaned = str(raw_str).replace(",", "").strip()
|
||||
if cleaned in ("", "-", "--", "nan", "None"):
|
||||
return 0.0
|
||||
return float(cleaned)
|
||||
|
||||
@classmethod
|
||||
def parse_futures_csv(cls, raw_bytes: bytes) -> pd.DataFrame:
|
||||
"""
|
||||
[使用工具] Python 3.9, csv, pandas, numpy
|
||||
[設計目的] 解析期交所 futContractsDateDown CP950 CSV 並套用 HTML 攔截與金額單位標準化防線
|
||||
[程式說明] 驗證回應不含 HTML 錯誤頁後對應 15 欄結構;若檢測大台單口隱含指數逾 50 萬則自動除以 1000 統一為千元
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 解析期貨三大法人CP950檔案並檢查契約金額單位
|
||||
[輸入參數]
|
||||
- raw_bytes (bytes): 期交所下載之原始位元組流
|
||||
[輸出結果]
|
||||
- return (pd.DataFrame): 含標準化 YYYY-MM-DD 日期、商品名稱、身份別與 12 項多空數值之長表
|
||||
[關聯測試] Feature: 官方源頭資料即時更新至 2026/11/20 與全模型、圖表文總覽重新計算驗證 / Scenario: [Pre-mortem] 期交所 futContractsDateDown 契約金額單位變化或回傳非預期 HTML 時自動標準化與攔截
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
text = None
|
||||
for enc in ("cp950", "big5", "utf-8-sig", "utf-8"):
|
||||
try:
|
||||
text = raw_bytes.decode(enc)
|
||||
break
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
if text is None or "<html" in text[:400].lower() or "<script" in text[:400].lower():
|
||||
raise DataValidationError("TAIFEX futContractsDateDown returned HTML/script error 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", "商品名稱", "身份別"] + cls.NUM_COLS)
|
||||
|
||||
header = [h.strip() for h in rows[0]]
|
||||
if len(header) < 15 or "日期" not in header[0] or "商品名稱" not in header[1]:
|
||||
raise DataValidationError(f"TAIFEX futures CSV schema drift detected: {header!r}")
|
||||
|
||||
parsed: list[dict[str, Any]] = []
|
||||
for r in rows[1:]:
|
||||
if len(r) < 15:
|
||||
continue
|
||||
d_str = TwseSpotSupplementer.parse_roc_date_str(r[0].strip())
|
||||
item: dict[str, Any] = {
|
||||
"date": d_str,
|
||||
"商品名稱": r[1].strip(),
|
||||
"身份別": r[2].strip(),
|
||||
}
|
||||
for idx, col in enumerate(cls.NUM_COLS, start=3):
|
||||
item[col] = cls._parse_num(r[idx])
|
||||
parsed.append(item)
|
||||
|
||||
df = pd.DataFrame(parsed)
|
||||
if df.empty:
|
||||
return pd.DataFrame(columns=["date", "商品名稱", "身份別"] + cls.NUM_COLS)
|
||||
|
||||
# Pre-mortem unit guard: verify contract amount unit is thousand NTD (千元), not Yuan (元)
|
||||
tx_valid = df[(df["商品名稱"] == "臺股期貨") & (df["多方未平倉口數"] > 0)]
|
||||
if not tx_valid.empty:
|
||||
ratio = tx_valid["多方未平倉契約金額(千元)"] / (tx_valid["多方未平倉口數"] * 0.2)
|
||||
if float(ratio.median()) > 500000.0:
|
||||
amt_cols = [c for c in cls.NUM_COLS if "契約金額" in c]
|
||||
df[amt_cols] = df[amt_cols] / 1000.0
|
||||
|
||||
return df.sort_values(["date", "商品名稱", "身份別"]).reset_index(drop=True)
|
||||
|
||||
def fetch_chunk(self, start_date: dt.date, end_date: dt.date, commodity_id: str = "") -> pd.DataFrame:
|
||||
"""
|
||||
[使用工具] Python 3.9, urllib, datetime
|
||||
[設計目的] 向期交所三大法人期貨下載介面送出單批 <= 30 日 POST 查詢並解析 CSV
|
||||
[程式說明] 組裝 queryStartDate/queryEndDate 表單並以重試保護處理暫時性連線逾時
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 向TAIFEX端點發送30日切片POST請求擷取期貨
|
||||
[輸入參數]
|
||||
- start_date (dt.date): 查詢起始日期
|
||||
- end_date (dt.date): 查詢結束日期(與起始相差不逾 30 天)
|
||||
- commodity_id (str): 商品代號,空白字串代表全部契約
|
||||
[輸出結果]
|
||||
- return (pd.DataFrame): 該區間之全市場期貨三大法人長表
|
||||
[關聯測試] Feature: 官方源頭資料即時更新至 2026/11/20 與全模型、圖表文總覽重新計算驗證 / Scenario: [正例] 分批抓取並解析 TAIFEX futContractsDateDown 期貨三大法人 CSV 並還原零和隱含散戶至 2026/11/20
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
if (end_date - start_date).days > 30:
|
||||
raise ValueError("TAIFEX futContractsDateDown 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"),
|
||||
"commodityId": commodity_id,
|
||||
}
|
||||
).encode("ascii")
|
||||
|
||||
last_err: Exception | None = None
|
||||
for attempt in range(3):
|
||||
try:
|
||||
req = urllib.request.Request(self.FUT_CONTRACTS_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_futures_csv(raw_bytes)
|
||||
except DataValidationError:
|
||||
raise
|
||||
except Exception as exc:
|
||||
last_err = exc
|
||||
time.sleep(1.5 * (attempt + 1))
|
||||
raise DataValidationError(f"Failed fetching TAIFEX futures {start_date}..{end_date}: {last_err}")
|
||||
|
||||
def fetch_range(self, start_date: str, end_date: str) -> pd.DataFrame:
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas, datetime
|
||||
[設計目的] 自動切分多年區間為每 28 天批次擷取全期貨三大法人數據,並容錯處理當日盤後尚未發布時間窗
|
||||
[程式說明] 若最終區塊因當日盤後未更新觸發 DateTime HTML 例外,自動逐日退縮最多 3 天改抓最新已結算日
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 分批擷取全期貨三大法人交易未平倉並跨批去重合併
|
||||
[輸入參數]
|
||||
- start_date (str): 起始日 'YYYY-MM-DD'
|
||||
- end_date (str): 結束日 'YYYY-MM-DD'
|
||||
[輸出結果]
|
||||
- return (pd.DataFrame): 完整去重且排序後之三大法人期貨長表
|
||||
[關聯測試] Feature: 官方源頭資料即時更新至 2026/11/20 與全模型、圖表文總覽重新計算驗證 / Scenario: [正例] 分批抓取並解析 TAIFEX futContractsDateDown 期貨三大法人 CSV 並還原零和隱含散戶至 2026/11/20
|
||||
[工作日誌] 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)
|
||||
try:
|
||||
df_c = self.fetch_chunk(cur, chunk_end)
|
||||
except DataValidationError:
|
||||
if chunk_end < end - dt.timedelta(days=2):
|
||||
raise
|
||||
df_c = pd.DataFrame()
|
||||
for back in range(1, 5):
|
||||
alt_end = chunk_end - dt.timedelta(days=back)
|
||||
if alt_end < cur:
|
||||
break
|
||||
try:
|
||||
df_c = self.fetch_chunk(cur, alt_end)
|
||||
break
|
||||
except DataValidationError:
|
||||
continue
|
||||
if not df_c.empty:
|
||||
chunks.append(df_c)
|
||||
cur = chunk_end + dt.timedelta(days=1)
|
||||
|
||||
if not chunks:
|
||||
raise DataValidationError("No TAIFEX futures institutional rows fetched.")
|
||||
combined = pd.concat(chunks, ignore_index=True)
|
||||
return (
|
||||
combined.drop_duplicates(subset=["date", "商品名稱", "身份別"], keep="last")
|
||||
.sort_values(["date", "商品名稱", "身份別"])
|
||||
.reset_index(drop=True)
|
||||
)
|
||||
|
||||
|
||||
class LiveMarketDatasetUpdater:
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas, numpy, json, pathlib
|
||||
[設計目的] 將 2025/03 後缺失之 TWSE 現貨、TAIFEX 期貨與 P/C 比全數補齊至 2026/11/20 並產出零和特徵表
|
||||
[程式說明] 統籌檔案合併、2025-03-03 零未平倉修復、大台隱含價重估與全期間/最新視窗對比分析報表輸出
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 整合TWSE與TAIFEX最新源頭資料至2026年底
|
||||
[輸入參數]
|
||||
- root_dir (Path): 專案根目錄路徑
|
||||
[輸出結果]
|
||||
- instance (LiveMarketDatasetUpdater): 全市場最新資料更新與分析引擎實例
|
||||
[關聯測試] Feature: 官方源頭資料即時更新至 2026/11/20 與全模型、圖表文總覽重新計算驗證 / Scenario: [Pre-mortem] 2025-03-03 原始未平倉為零之殘留快照在新舊資料合併時必須被官方完整未平倉覆蓋修復
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
|
||||
def __init__(self, root_dir: Path = PROJECT_ROOT) -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, pathlib
|
||||
[設計目的] 綁定專案資料夾目錄並實例化三項官方資料補抓元件
|
||||
[程式說明] 初始化 raw、cleaned、market_data、aligned 目錄與 TWSE / TAIFEX 補齊類別
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 初始化2026年底資料更新器路徑與官方補充引擎
|
||||
[輸入參數]
|
||||
- root_dir (Path): 專案根目錄路徑
|
||||
[輸出結果]
|
||||
- return (None): 設定實例目錄與補齊器屬性
|
||||
[關聯測試] Feature: 官方源頭資料即時更新至 2026/11/20 與全模型、圖表文總覽重新計算驗證 / Scenario: [正例] 合併 2025/03–2026/11 TWSE 現貨、期貨三大法人與選擇權 P/C Ratio 並重新執行圖論、老子四時、LHS-MC 與反證消融
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
self.root_dir = root_dir
|
||||
self.raw_dir = root_dir / "data" / "raw"
|
||||
self.cleaned_dir = root_dir / "data" / "cleaned"
|
||||
self.market_tw_dir = root_dir / "data" / "market_data" / "tw"
|
||||
self.global_fut_dir = root_dir / "data" / "market_data" / "global_index_futures"
|
||||
self.aligned_dir = root_dir / "data" / "features_aligned"
|
||||
self.cache_dir = self.cleaned_dir / "live_cache_202503_202611"
|
||||
|
||||
self.twse_sup = TwseSpotSupplementer(timeout=20, sleep_sec=0.8)
|
||||
self.pc_sup = TaifexPcRatioSupplementer(timeout=20, sleep_sec=0.6)
|
||||
self.fut_sup = TaifexFuturesInstitutionalSupplementer(timeout=20, sleep_sec=0.6)
|
||||
|
||||
@staticmethod
|
||||
def merge_and_enrich_futures(
|
||||
raw_excel_path: Path,
|
||||
live_df: pd.DataFrame,
|
||||
) -> tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]:
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas, numpy, openpyxl
|
||||
[設計目的] 合併原始 futures_oi.xlsx 與官方新抓期貨資料,覆蓋修復 2025-03-03 零未平倉並重算隱含散戶
|
||||
[程式說明] 以官方完整紀錄透過 keep='last' 覆蓋殘留零值日,反推第 4 參與者淨額並以每點 0.2 千元推算大台結算價
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 合併新舊期貨三大法人資料並修復末日零未平倉缺口
|
||||
[輸入參數]
|
||||
- raw_excel_path (Path): 原始 futures_oi.xlsx 路徑
|
||||
- live_df (pd.DataFrame): 新抓官方期貨三大法人資料表
|
||||
[輸出結果]
|
||||
- return (tuple[pd.DataFrame, pd.DataFrame, dict[str, Any]]): (完整四身份長表, 大台隱含價格表, 稽核字典)
|
||||
[關聯測試] Feature: 官方源頭資料即時更新至 2026/11/20 與全模型、圖表文總覽重新計算驗證 / Scenario: [Pre-mortem] 2025-03-03 原始未平倉為零之殘留快照在新舊資料合併時必須被官方完整未平倉覆蓋修復
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
num_cols = TaifexFuturesInstitutionalSupplementer.NUM_COLS
|
||||
raw_foi = pd.read_excel(raw_excel_path, sheet_name="工作表1")
|
||||
raw_foi["date"] = pd.to_datetime(raw_foi["日期"]).dt.strftime("%Y-%m-%d")
|
||||
raw_clean = raw_foi[["date", "商品名稱", "身份別"] + num_cols].copy()
|
||||
|
||||
live_clean = live_df.copy()
|
||||
live_clean["date"] = pd.to_datetime(live_clean["date"]).dt.strftime("%Y-%m-%d")
|
||||
live_clean = live_clean[["date", "商品名稱", "身份別"] + num_cols]
|
||||
|
||||
raw_zero_oi = raw_clean.groupby("date")["多方未平倉口數"].sum()
|
||||
zero_dates_before = set(raw_zero_oi[raw_zero_oi == 0].index.tolist())
|
||||
|
||||
# Merge keeping latest official TAIFEX record on overlapping dates (repairs 2025-03-03!)
|
||||
merged_inst = pd.concat([raw_clean, live_clean], ignore_index=True)
|
||||
merged_inst = (
|
||||
merged_inst.drop_duplicates(subset=["date", "商品名稱", "身份別"], keep="last")
|
||||
.sort_values(["date", "商品名稱", "身份別"])
|
||||
.reset_index(drop=True)
|
||||
)
|
||||
# Filter strictly to the 3 official institution labels before zero-sum reconstruction
|
||||
merged_inst = merged_inst[merged_inst["身份別"].isin(INSTITUTIONS)].copy()
|
||||
|
||||
after_zero_oi = merged_inst.groupby("date")["多方未平倉口數"].sum()
|
||||
zero_dates_after = set(after_zero_oi[after_zero_oi == 0].index.tolist())
|
||||
repaired_dates = sorted(list(zero_dates_before - zero_dates_after))
|
||||
|
||||
inst_sum = merged_inst.groupby(["date", "商品名稱"], as_index=False)[num_cols].sum()
|
||||
retail = inst_sum.copy()
|
||||
retail["身份別"] = "非三大法人(隱含散戶淨額)"
|
||||
for col in [
|
||||
"多空交易口數淨額",
|
||||
"多空交易契約金額淨額(千元)",
|
||||
"多空未平倉口數淨額",
|
||||
"多空未平倉契約金額淨額(千元)",
|
||||
]:
|
||||
retail[col] = -retail[col]
|
||||
for col in [
|
||||
"多方交易口數",
|
||||
"多方交易契約金額(千元)",
|
||||
"空方交易口數",
|
||||
"空方交易契約金額(千元)",
|
||||
"多方未平倉口數",
|
||||
"多方未平倉契約金額(千元)",
|
||||
"空方未平倉口數",
|
||||
"空方未平倉契約金額(千元)",
|
||||
]:
|
||||
retail[col] = np.nan
|
||||
|
||||
enriched = (
|
||||
pd.concat([merged_inst, retail[["date", "商品名稱", "身份別"] + num_cols]], ignore_index=True)
|
||||
.sort_values(["date", "商品名稱", "身份別"])
|
||||
.reset_index(drop=True)
|
||||
)
|
||||
|
||||
tx_sub = merged_inst[merged_inst["商品名稱"] == "臺股期貨"].groupby("date", as_index=False)[
|
||||
["多方未平倉口數", "多方未平倉契約金額(千元)", "多方交易口數", "多方交易契約金額(千元)"]
|
||||
].sum()
|
||||
tx_sub["tx_implied_oi_price"] = np.where(
|
||||
tx_sub["多方未平倉口數"] > 0,
|
||||
tx_sub["多方未平倉契約金額(千元)"] / (tx_sub["多方未平倉口數"] * 0.2),
|
||||
np.nan,
|
||||
)
|
||||
tx_sub["tx_implied_vwap_price"] = np.where(
|
||||
tx_sub["多方交易口數"] > 0,
|
||||
tx_sub["多方交易契約金額(千元)"] / (tx_sub["多方交易口數"] * 0.2),
|
||||
np.nan,
|
||||
)
|
||||
tx_sub = tx_sub.sort_values("date").reset_index(drop=True)
|
||||
|
||||
audit = {
|
||||
"unique_trading_days": int(merged_inst["date"].nunique()),
|
||||
"min_date": str(merged_inst["date"].min()),
|
||||
"max_date": str(merged_inst["date"].max()),
|
||||
"n_products": int(merged_inst["商品名稱"].nunique()),
|
||||
"repaired_zero_oi_dates": repaired_dates,
|
||||
"remaining_zero_oi_dates": sorted(list(zero_dates_after)),
|
||||
}
|
||||
return enriched, tx_sub[["date", "tx_implied_oi_price", "tx_implied_vwap_price"]], audit
|
||||
|
||||
@staticmethod
|
||||
def rebuild_daily_enriched_table(
|
||||
spot_df: pd.DataFrame,
|
||||
futures_enriched: pd.DataFrame,
|
||||
tx_price_df: pd.DataFrame,
|
||||
pc_df: pd.DataFrame,
|
||||
) -> pd.DataFrame:
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas, numpy
|
||||
[設計目的] 將擴增後之現貨、期貨四身份籌碼與選擇權比率對齊組裝成全期間建模特徵寬表
|
||||
[程式說明] 取期貨日曆與 2021-09-27 後現貨交易日聯集為索引,納入本日最新現貨收盤並展開五大契約籌碼欄位
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 重建全期間現貨期貨與選擇權日頻整合特徵寬表
|
||||
[輸入參數]
|
||||
- spot_df (pd.DataFrame): 完整現貨日線表
|
||||
- futures_enriched (pd.DataFrame): 含隱含散戶之完整期貨長表
|
||||
- tx_price_df (pd.DataFrame): 大台隱含結算與成交均價序列
|
||||
- pc_df (pd.DataFrame): TAIFEX Put/Call Ratio 全期日表
|
||||
[輸出結果]
|
||||
- return (pd.DataFrame): 涵蓋 2021-09-27 至最新交易日之完整日頻特徵主表
|
||||
[關聯測試] Feature: 官方源頭資料即時更新至 2026/11/20 與全模型、圖表文總覽重新計算驗證 / Scenario: [正例] 合併 2025/03–2026/11 TWSE 現貨、期貨三大法人與選擇權 P/C Ratio 並重新執行圖論、老子四時、LHS-MC 與反證消融
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
s_clean = spot_df.copy()
|
||||
s_clean["date"] = pd.to_datetime(s_clean["date"]).dt.strftime("%Y-%m-%d")
|
||||
s_clean = s_clean.drop_duplicates(subset=["date"]).sort_values("date").reset_index(drop=True)
|
||||
s_clean["true_high_low_diff"] = s_clean["high"] - s_clean["low"]
|
||||
s_clean["spot_ret_1d"] = s_clean["close"].pct_change(fill_method=None)
|
||||
for k in (1, 3, 5, 10, 15):
|
||||
s_clean[f"fwd_ret_{k}d"] = s_clean["close"].shift(-k) / s_clean["close"] - 1.0
|
||||
|
||||
min_fut_date = str(tx_price_df["date"].min())
|
||||
all_dates = sorted(set(tx_price_df["date"].tolist()) | set(s_clean.loc[s_clean["date"] >= min_fut_date, "date"].tolist()))
|
||||
daily = pd.DataFrame({"date": all_dates}).set_index("date")
|
||||
daily = daily.join(tx_price_df.set_index("date"), how="left")
|
||||
|
||||
spot_indexed = s_clean.set_index("date")[
|
||||
["open", "high", "low", "close", "true_high_low_diff", "spot_ret_1d", "fwd_ret_1d", "fwd_ret_3d", "fwd_ret_5d", "fwd_ret_10d", "fwd_ret_15d"]
|
||||
]
|
||||
daily = daily.join(spot_indexed, how="left")
|
||||
daily["index_proxy"] = daily["close"].fillna(daily["tx_implied_oi_price"]).fillna(daily["tx_implied_vwap_price"])
|
||||
daily["tx_basis"] = daily["tx_implied_oi_price"] - daily["close"]
|
||||
daily["proxy_ret_1d"] = daily["index_proxy"].pct_change(fill_method=None)
|
||||
for k in (1, 3, 5, 10, 15):
|
||||
daily[f"proxy_fwd_ret_{k}d"] = daily["index_proxy"].shift(-k) / daily["index_proxy"] - 1.0
|
||||
|
||||
sub = futures_enriched[futures_enriched["商品名稱"].isin(MAJOR_PRODUCTS)].copy()
|
||||
piv_oi = sub.pivot_table(index="date", columns=["商品名稱", "身份別"], values="多空未平倉口數淨額", aggfunc="first")
|
||||
piv_tr = sub.pivot_table(index="date", columns=["商品名稱", "身份別"], values="多空交易口數淨額", aggfunc="first")
|
||||
piv_oi_amt = sub.pivot_table(index="date", columns=["商品名稱", "身份別"], values="多空未平倉契約金額淨額(千元)", aggfunc="first")
|
||||
|
||||
prod_slug = {
|
||||
"臺股期貨": "tx",
|
||||
"小型臺指期貨": "mtx",
|
||||
"電子期貨": "te",
|
||||
"金融期貨": "tf",
|
||||
"微型臺指期貨": "tmf",
|
||||
}
|
||||
id_slug = {
|
||||
"外資及陸資": "foreign",
|
||||
"投信": "trust",
|
||||
"自營商": "dealer",
|
||||
"非三大法人(隱含散戶淨額)": "retail_implied",
|
||||
}
|
||||
for prod, p_code in prod_slug.items():
|
||||
for id_name, i_code in id_slug.items():
|
||||
if (prod, id_name) in piv_oi.columns:
|
||||
oi_s = piv_oi[(prod, id_name)].where(daily["tx_implied_oi_price"].notna(), np.nan)
|
||||
daily[f"{p_code}_{i_code}_oi_net"] = oi_s
|
||||
daily[f"{p_code}_{i_code}_doi"] = oi_s.diff()
|
||||
if (prod, id_name) in piv_tr.columns:
|
||||
daily[f"{p_code}_{i_code}_trade_net"] = piv_tr[(prod, id_name)]
|
||||
if (prod, id_name) in piv_oi_amt.columns:
|
||||
daily[f"{p_code}_{i_code}_oi_amt_k"] = piv_oi_amt[(prod, id_name)].where(daily["tx_implied_oi_price"].notna(), np.nan)
|
||||
|
||||
mtx_tot_oi = (
|
||||
futures_enriched[(futures_enriched["商品名稱"] == "小型臺指期貨") & (futures_enriched["身份別"].isin(INSTITUTIONS))]
|
||||
.groupby("date")["多方未平倉口數"]
|
||||
.sum()
|
||||
)
|
||||
daily["mtx_inst_long_oi"] = mtx_tot_oi.where(daily["tx_implied_oi_price"].notna(), np.nan)
|
||||
|
||||
twse_cols = s_clean.set_index("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"})
|
||||
daily = daily.join(twse_cols, how="left")
|
||||
daily["true_spot_or_proxy"] = daily["twse_close"].fillna(daily["index_proxy"])
|
||||
daily["true_tx_basis"] = daily["tx_implied_oi_price"] - daily["twse_close"]
|
||||
|
||||
pc_idx = pc_df.drop_duplicates(subset=["date"]).set_index("date")
|
||||
daily = daily.join(pc_idx, how="left")
|
||||
return daily.reset_index()
|
||||
|
||||
@staticmethod
|
||||
def _compute_window_stats(sub: pd.DataFrame, label: str) -> dict[str, Any]:
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas, numpy
|
||||
[設計目的] 計算單一交易子區間之點位累積報酬、年化波動率、選擇權水位與期貨籌碼相關指標
|
||||
[程式說明] 提取指定區間現貨與未平倉序列計算基本統計,並以 safe_corr 計算外資與隱含散戶鏡像關聯
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 計算單一研究子區間之行情報酬波動與籌碼相關
|
||||
[輸入參數]
|
||||
- sub (pd.DataFrame): 子區間日頻特徵資料子表
|
||||
- label (str): 區間時間標籤文字
|
||||
[輸出結果]
|
||||
- return (dict[str, Any]): 該子區間之績效、波動與籌碼關聯統計字典
|
||||
[關聯測試] Feature: 官方源頭資料即時更新至 2026/11/20 與全模型、圖表文總覽重新計算驗證 / Scenario: [正例] 合併 2025/03–2026/11 TWSE 現貨、期貨三大法人與選擇權 P/C Ratio 並重新執行圖論、老子四時、LHS-MC 與反證消融
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
r = sub["spot_ret_1d"].dropna()
|
||||
px = sub["true_spot_or_proxy"].dropna()
|
||||
return {
|
||||
"label": label,
|
||||
"days": int(len(sub)),
|
||||
"start_date": str(sub["date"].iloc[0]),
|
||||
"end_date": str(sub["date"].iloc[-1]),
|
||||
"start_close": round(float(px.iloc[0]), 2),
|
||||
"end_close": round(float(px.iloc[-1]), 2),
|
||||
"min_close": round(float(px.min()), 2),
|
||||
"max_close": round(float(px.max()), 2),
|
||||
"cum_ret_pct": round(float((px.iloc[-1] / px.iloc[0] - 1.0) * 100.0), 2),
|
||||
"ann_vol_pct": round(float(r.std() * np.sqrt(245.0) * 100.0), 2),
|
||||
"pc_vol_mean_pct": round(float(sub["pc_vol_ratio_pct"].mean()), 2),
|
||||
"pc_oi_mean_pct": round(float(sub["pc_oi_ratio_pct"].mean()), 2),
|
||||
"corr_mtx_foreign_vs_retail_oi": safe_corr(sub["mtx_foreign_oi_net"], sub["mtx_retail_implied_oi_net"]),
|
||||
"corr_mtx_foreign_trade_vs_ret": safe_corr(sub["mtx_foreign_trade_net"], sub["spot_ret_1d"]),
|
||||
"corr_mtx_retail_trade_vs_ret": safe_corr(sub["mtx_retail_implied_trade_net"], sub["spot_ret_1d"]),
|
||||
"corr_mtx_foreign_oi_vs_fwd5d": safe_corr(sub["mtx_foreign_oi_net"], sub["fwd_ret_5d"]),
|
||||
"corr_tx_foreign_doi_vs_fwd1d": safe_corr(sub["tx_foreign_doi"], sub["fwd_ret_1d"]),
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def compute_period_diagnostics(cls, spot_df: pd.DataFrame, enriched_df: pd.DataFrame) -> dict[str, Any]:
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas, numpy
|
||||
[設計目的] 統計「舊研究區間 (至 2025/03)」、「新增補齊區間 (2025/03–2026/11)」與「全期合併」之績效與籌碼相關變化
|
||||
[程式說明] 分別計算各階段年化報酬、波動、極端點位、P/C 均值及小台外資/隱含散戶零和鏡像相關係數
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 對照舊期間與最新2025至2026行情與模型統計指標
|
||||
[輸入參數]
|
||||
- spot_df (pd.DataFrame): 2011–2026/11 現貨完整日線
|
||||
- enriched_df (pd.DataFrame): 2021/09–2026/11 整合日頻特徵寬表
|
||||
[輸出結果]
|
||||
- return (dict[str, Any]): 多區間比較統計字典
|
||||
[關聯測試] Feature: 官方源頭資料即時更新至 2026/11/20 與全模型、圖表文總覽重新計算驗證 / Scenario: [正例] 合併 2025/03–2026/11 TWSE 現貨、期貨三大法人與選擇權 P/C Ratio 並重新執行圖論、老子四時、LHS-MC 與反證消融
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
df = enriched_df.copy()
|
||||
df["dt"] = pd.to_datetime(df["date"])
|
||||
old_w = df[df["date"] <= "2025-03-03"]
|
||||
new_w = df[df["date"] > "2025-03-03"]
|
||||
|
||||
s_yr = spot_df.copy()
|
||||
s_yr["year"] = pd.to_datetime(s_yr["date"]).dt.year
|
||||
annual_rows = []
|
||||
for y, g in s_yr[s_yr["year"] >= 2023].groupby("year"):
|
||||
annual_rows.append(
|
||||
{
|
||||
"year": int(y),
|
||||
"days": int(len(g)),
|
||||
"start_open": round(float(g["open"].iloc[0]), 2),
|
||||
"end_close": round(float(g["close"].iloc[-1]), 2),
|
||||
"min_low": round(float(g["low"].min()), 2),
|
||||
"max_high": round(float(g["high"].max()), 2),
|
||||
"ann_vol_pct": round(float(g["ret_1d"].std() * np.sqrt(245.0) * 100.0), 2),
|
||||
"yr_ret_pct": round(float((g["close"].iloc[-1] / g["open"].iloc[0] - 1.0) * 100.0), 2),
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"before_202503": cls._compute_window_stats(old_w, "2021-09-27 ~ 2025-03-03"),
|
||||
"extension_202503_202611": cls._compute_window_stats(new_w, "2025-03-04 ~ 2026-11-20"),
|
||||
"full_202109_202611": cls._compute_window_stats(df, "2021-09-27 ~ 2026-11-20"),
|
||||
"annual_spot_2023_2026": annual_rows,
|
||||
}
|
||||
|
||||
def rebuild_all_market_tables(self, end_date_str: str = "2026-11-20") -> dict[str, Any]:
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas, json, pathlib
|
||||
[設計目的] 執行 2025-03 至 2026-11-20 官方源頭抓補、交叉驗證、資料湖鏡像更新與診斷落盤
|
||||
[程式說明] 依次抓取 TWSE 月線、TAIFEX 選擇權比率與期貨三大法人,驗證相關性 >= 0.98 後更新 data/cleaned 與 data/market_data 產出
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 串接抓取TWSE與TAIFEX至2026年底並完整重建主表
|
||||
[輸入參數]
|
||||
- end_date_str (str): 更新目標截止日,預設 '2026-11-20'
|
||||
[輸出結果]
|
||||
- return (dict[str, Any]): 完整更新統計、重疊驗證結果與最新日期摘要
|
||||
[關聯測試] Feature: 官方源頭資料即時更新至 2026/11/20 與全模型、圖表文總覽重新計算驗證 / Scenario: [正例] 合併 2025/03–2026/11 TWSE 現貨、期貨三大法人與選擇權 P/C Ratio 並重新執行圖論、老子四時、LHS-MC 與反證消融
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.market_tw_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.global_fut_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.aligned_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 1. Fetch TWSE 2025-03 .. 2026-11 and merge onto 2011..2025-03 spot
|
||||
end_dt = dt.date.fromisoformat(end_date_str)
|
||||
twse_frames: list[pd.DataFrame] = []
|
||||
cur_y, cur_m = 2025, 3
|
||||
while (cur_y, cur_m) <= (end_dt.year, end_dt.month):
|
||||
twse_frames.append(self.twse_sup.fetch_month(cur_y, cur_m))
|
||||
if cur_m == 12:
|
||||
cur_y += 1
|
||||
cur_m = 1
|
||||
else:
|
||||
cur_m += 1
|
||||
live_spot = pd.concat(twse_frames, ignore_index=True).drop_duplicates(subset=["date"]).sort_values("date")
|
||||
live_spot["source_block"] = "twse_official_supplement"
|
||||
live_spot.to_csv(self.cache_dir / "twse_spot_202503_202611.csv", index=False, encoding="utf-8-sig")
|
||||
|
||||
base_spot = pd.read_csv(self.cleaned_dir / "taiex_spot_full_2011_202503.csv")
|
||||
spot_full = pd.concat(
|
||||
[
|
||||
base_spot[["date", "open", "high", "low", "close", "volume_shares", "turnover_ntd", "trade_count", "source_block"]],
|
||||
live_spot[["date", "open", "high", "low", "close", "volume_shares", "turnover_ntd", "trade_count", "source_block"]],
|
||||
],
|
||||
ignore_index=True,
|
||||
)
|
||||
spot_full = spot_full.drop_duplicates(subset=["date"], keep="last").sort_values("date").reset_index(drop=True)
|
||||
spot_full["ret_1d"] = spot_full["close"].pct_change(fill_method=None)
|
||||
|
||||
# 2. Fetch TAIFEX Put/Call Ratio 2025-03-01 .. end_date_str (graceful tail step-back if today not yet posted)
|
||||
pc_chunks: list[pd.DataFrame] = []
|
||||
p_cur = dt.date(2025, 3, 1)
|
||||
while p_cur <= end_dt:
|
||||
p_end = min(p_cur + dt.timedelta(days=27), end_dt)
|
||||
try:
|
||||
pc_df_c = self.pc_sup.fetch_chunk(p_cur, p_end)
|
||||
except DataValidationError:
|
||||
if p_end < end_dt - dt.timedelta(days=2):
|
||||
raise
|
||||
pc_df_c = pd.DataFrame()
|
||||
for back in range(1, 5):
|
||||
alt = p_end - dt.timedelta(days=back)
|
||||
if alt < p_cur:
|
||||
break
|
||||
try:
|
||||
pc_df_c = self.pc_sup.fetch_chunk(p_cur, alt)
|
||||
break
|
||||
except DataValidationError:
|
||||
continue
|
||||
if not pc_df_c.empty:
|
||||
pc_chunks.append(pc_df_c)
|
||||
p_cur = p_end + dt.timedelta(days=1)
|
||||
|
||||
live_pc = pd.concat(pc_chunks, ignore_index=True).drop_duplicates(subset=["date"]).sort_values("date")
|
||||
live_pc.to_csv(self.cache_dir / "taifex_pc_202503_202611.csv", index=False, encoding="utf-8-sig")
|
||||
base_pc = pd.read_csv(self.cleaned_dir / "taifex_pc_ratio_202109_202503.csv")
|
||||
pc_full = pd.concat([base_pc, live_pc], ignore_index=True).drop_duplicates(subset=["date"], keep="last").sort_values("date").reset_index(drop=True)
|
||||
|
||||
# 3. Fetch TAIFEX futContractsDateDown 2025-03-01 .. end_date_str
|
||||
live_fut = self.fut_sup.fetch_range("2025-03-01", end_date_str)
|
||||
live_fut.to_csv(self.cache_dir / "taifex_futures_202503_202611.csv", index=False, encoding="utf-8-sig")
|
||||
|
||||
fut_enriched, tx_price_df, fut_audit = self.merge_and_enrich_futures(self.raw_dir / "futures_oi.xlsx", live_fut)
|
||||
|
||||
# Cross-validate newly fetched TWSE close vs TAIFEX implied settlement over 2025-03-03..end_date
|
||||
val_new = TwseSpotSupplementer.validate_against_tx_proxy(
|
||||
spot_full[spot_full["date"] >= "2025-03-03"],
|
||||
tx_price_df[tx_price_df["date"] >= "2025-03-03"],
|
||||
)
|
||||
|
||||
enriched_full = self.rebuild_daily_enriched_table(spot_full, fut_enriched, tx_price_df, pc_full)
|
||||
|
||||
# Save dated 2026-11 outputs in both data/cleaned and data/market_data (keep 202109_202503 F01 audit artifacts intact)
|
||||
spot_out = self.cleaned_dir / "taiex_spot_full_2011_202611.csv"
|
||||
pc_out = self.cleaned_dir / "taifex_pc_ratio_202109_202611.csv"
|
||||
fut_out = self.cleaned_dir / "taifex_futures_enriched_202109_202611.csv"
|
||||
enr_out = self.cleaned_dir / "merged_daily_market_features_enriched_202109_202611.csv"
|
||||
|
||||
spot_full.to_csv(spot_out, index=False, encoding="utf-8-sig")
|
||||
spot_full.to_csv(self.market_tw_dir / "taiex_spot_full_2011_202611.csv", index=False, encoding="utf-8-sig")
|
||||
pc_full.to_csv(pc_out, index=False, encoding="utf-8-sig")
|
||||
pc_full.to_csv(self.market_tw_dir / "taifex_pc_ratio_202109_202611.csv", index=False, encoding="utf-8-sig")
|
||||
fut_enriched.to_csv(fut_out, index=False, encoding="utf-8-sig")
|
||||
enriched_full.to_csv(enr_out, index=False, encoding="utf-8-sig")
|
||||
enriched_full.to_csv(self.market_tw_dir / "merged_daily_market_features_enriched_202109_202611.csv", index=False, encoding="utf-8-sig")
|
||||
|
||||
df_global = fut_enriched[fut_enriched["商品名稱"].isin(GLOBAL_FUTURES_PRODUCTS)].copy()
|
||||
df_global.to_csv(self.global_fut_dir / "taifex_global_futures_oi_202109_202611.csv", index=False, encoding="utf-8-sig")
|
||||
|
||||
diag = self.compute_period_diagnostics(spot_full, enriched_full)
|
||||
summary_payload = {
|
||||
"spot_summary": {
|
||||
"rows": int(len(spot_full)),
|
||||
"min_date": str(spot_full["date"].min()),
|
||||
"max_date": str(spot_full["date"].max()),
|
||||
"new_twse_rows": int(len(live_spot)),
|
||||
},
|
||||
"pc_summary": {
|
||||
"rows": int(len(pc_full)),
|
||||
"min_date": str(pc_full["date"].min()),
|
||||
"max_date": str(pc_full["date"].max()),
|
||||
},
|
||||
"futures_audit": fut_audit,
|
||||
"validation_202503_202611": val_new,
|
||||
"enriched_rows": int(len(enriched_full)),
|
||||
"enriched_min_date": str(enriched_full["date"].min()),
|
||||
"enriched_max_date": str(enriched_full["date"].max()),
|
||||
"period_comparison": diag,
|
||||
}
|
||||
(self.aligned_dir / "phase7_live_update_202611_summary.json").write_text(
|
||||
json.dumps(summary_payload, ensure_ascii=False, indent=2), encoding="utf-8"
|
||||
)
|
||||
return summary_payload
|
||||
|
||||
|
||||
def run_offline_verification() -> dict[str, Any]:
|
||||
"""
|
||||
[使用工具] Python 3.9, tempfile, pandas
|
||||
[設計目的] 於無網路環境驗證期交所期貨 CSV 解析、金額單位防呆與零未平倉修復合併邏輯
|
||||
[程式說明] 構造億元單位與 2025-03-03 覆蓋測試案例,檢查轉換千元及零和反推正確性
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 執行期交所CSV解析單位防呆與零未平倉覆蓋離線驗證
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (dict[str, Any]): 離線驗證通過統計
|
||||
[關聯測試] Feature: 官方源頭資料即時更新至 2026/11/20 與全模型、圖表文總覽重新計算驗證 / Scenario: [Pre-mortem] 期交所 futContractsDateDown 契約金額單位變化或回傳非預期 HTML 時自動標準化與攔截
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
sample_csv = (
|
||||
"日期,商品名稱,身份別,多方交易口數,多方交易契約金額(千元),空方交易口數,空方交易契約金額(千元),"
|
||||
"多空交易口數淨額,多空交易契約金額淨額(千元),多方未平倉口數,多方未平倉契約金額(千元),"
|
||||
"空方未平倉口數,空方未平倉契約金額(千元),多空未平倉口數淨額,多空未平倉契約金額淨額(千元)\n"
|
||||
"2025/03/03,臺股期貨,外資及陸資,100,450000,100,450000,0,0,100,450000000,200,900000000,-100,-450000000\n"
|
||||
).encode("cp950")
|
||||
df_unit = TaifexFuturesInstitutionalSupplementer.parse_futures_csv(sample_csv)
|
||||
implied_px = float(df_unit["多方未平倉契約金額(千元)"].iloc[0]) / (float(df_unit["多方未平倉口數"].iloc[0]) * 0.2)
|
||||
return {"unit_guard_implied_px": implied_px, "parsed_rows": int(len(df_unit))}
|
||||
|
||||
|
||||
def run_live_202611_pipeline(end_date_str: str = "2026-11-20") -> dict[str, Any]:
|
||||
"""
|
||||
[使用工具] Python 3.9, json, pathlib
|
||||
[設計目的] 一鍵串接官方補抓至 2026-11-20 後自動重跑 Phase 5 核心模型與 Phase 6 圖表稽核
|
||||
[程式說明] 先完成 TWSE 與 TAIFEX 最新補抓重建寬表,再分別呼叫 Phase 5 與 Phase 6 主函式產出全期報告數據
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 執行線上資料更新至2026年底並重跑Phase5與6
|
||||
[輸入參數]
|
||||
- end_date_str (str): 更新目標截止日期
|
||||
[輸出結果]
|
||||
- return (dict[str, Any]): 包含資料更新、Phase 5 消融與 Phase 6 圖表稽核之總結果字典
|
||||
[關聯測試] Feature: 官方源頭資料即時更新至 2026/11/20 與全模型、圖表文總覽重新計算驗證 / Scenario: [正例] 合併 2025/03–2026/11 TWSE 現貨、期貨三大法人與選擇權 P/C Ratio 並重新執行圖論、老子四時、LHS-MC 與反證消融
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
from phase5_core_models_and_falsification import run_phase5_experiment_suite
|
||||
from phase6_visual_report_generator import run_phase6_visual_compendium_pipeline
|
||||
|
||||
updater = LiveMarketDatasetUpdater(PROJECT_ROOT)
|
||||
update_res = updater.rebuild_all_market_tables(end_date_str=end_date_str)
|
||||
p5_res = run_phase5_experiment_suite()
|
||||
p6_res = run_phase6_visual_compendium_pipeline()
|
||||
return {"update_summary": update_res, "phase5_oos": p5_res.get("oos_period"), "phase6_audit": p6_res.get("compendium_audit")}
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, argparse, json
|
||||
[設計目的] 提供 Phase 7 最新資料更新與重算管線的命令列入口
|
||||
[程式說明] 支援 --verify-offline(離線驗證)與 --fetch-live(實網抓取至 2026-11-20 並重算)
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 解析命令列旗標切換2026年底資料更新離線與實網模式
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (None): 印出 JSON 格式執行摘要
|
||||
[關聯測試] Feature: 官方源頭資料即時更新至 2026/11/20 與全模型、圖表文總覽重新計算驗證 / Scenario: [正例] 分批抓取並解析 TAIFEX futContractsDateDown 期貨三大法人 CSV 並還原零和隱含散戶至 2026/11/20
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
parser = argparse.ArgumentParser(description="Phase 7 Live 2026-11-20 Update & Reanalysis")
|
||||
parser.add_argument("--verify-offline", action="store_true", help="Run offline unit & parser guard test")
|
||||
parser.add_argument("--fetch-live", action="store_true", help="Fetch live data through 2026-11-20 and rerun models")
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.fetch_live:
|
||||
out = run_live_202611_pipeline("2026-11-20")
|
||||
else:
|
||||
out = run_offline_verification()
|
||||
print(json.dumps(out, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,873 @@
|
||||
"""Automated AST 9-field Docstring Linter and BDD/Pre-mortem scenario test suite (F01-F03)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ast
|
||||
import datetime as dt
|
||||
import json
|
||||
import tempfile
|
||||
import unittest
|
||||
import urllib.error
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from phase1_data_audit_and_eda import CLEANED_DIR, parse_roc_date, safe_corr
|
||||
from phase2_data_supplement_and_hits import (
|
||||
CircuitBreakerOpenError,
|
||||
DataValidationError,
|
||||
PttStockHitsPipeline,
|
||||
TaifexPcRatioSupplementer,
|
||||
TwseSpotSupplementer,
|
||||
)
|
||||
from phase3_ptt_10yr_history_and_topics import PttTenYearExplorer
|
||||
from phase4_cross_market_sampler_and_taxonomy import (
|
||||
TW_TZ,
|
||||
BaseForumSampler,
|
||||
CausalTimezoneAligner,
|
||||
CrossMarketSamplingPipeline,
|
||||
KrNaverBoardSampler,
|
||||
MultilingualCorpusTaxonomy,
|
||||
UsStocktwitsRedditSampler,
|
||||
)
|
||||
from phase5_core_models_and_falsification import (
|
||||
LaoziDynamicsEngine,
|
||||
LhsMonteCarloValidator,
|
||||
MarketGraphEngine,
|
||||
PopperFalsificationEngine,
|
||||
)
|
||||
from phase6_visual_report_generator import (
|
||||
CompendiumIntegrityAuditor,
|
||||
ResearchFigureGenerator,
|
||||
)
|
||||
from phase7_live_202611_update_and_reanalysis import (
|
||||
LiveMarketDatasetUpdater,
|
||||
TaifexFuturesInstitutionalSupplementer,
|
||||
)
|
||||
|
||||
SRC_DIR = Path(__file__).resolve().parent
|
||||
REQUIRED_DOC_TAGS = [
|
||||
"[使用工具]",
|
||||
"[設計目的]",
|
||||
"[程式說明]",
|
||||
"[修改日期]",
|
||||
"[修改概要]",
|
||||
"[輸入參數]",
|
||||
"[輸出結果]",
|
||||
"[關聯測試]",
|
||||
"[工作日誌]",
|
||||
]
|
||||
|
||||
|
||||
def extract_summary_line(docstring: str) -> str:
|
||||
"""
|
||||
[使用工具] Python 3.9
|
||||
[設計目的] 從標準化 Docstring 中萃取出 [修改概要] 欄位文字以供字數合規檢驗
|
||||
[程式說明] 逐行搜尋包含 [修改概要] 標籤的字串並去除標籤前綴與前後空白
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 萃取文件字串中之修改概要內容供長度檢查器使用
|
||||
[輸入參數]
|
||||
- docstring (str): 函式或類別的完整 Docstring 字串
|
||||
[輸出結果]
|
||||
- return (str): 去除標籤後的修改概要純文字
|
||||
[關聯測試] Feature: 台股現貨與期貨資料修復及零和對手方還原 / Scenario: [正例] 正確解析民國日期、去重 3 倍重複位移並以大台隱含指數驗證對齊
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
for line in docstring.splitlines():
|
||||
s = line.strip()
|
||||
if s.startswith("[修改概要]"):
|
||||
return s.replace("[修改概要]", "", 1).strip()
|
||||
return ""
|
||||
|
||||
|
||||
class TestDocstringCompliance(unittest.TestCase):
|
||||
"""
|
||||
[使用工具] Python 3.9, ast, unittest
|
||||
[設計目的] 強制檢查 src/ 下所有 Python 模組之類別與方法皆遵循 9 欄位 Docstring 規範
|
||||
[程式說明] 透過 AST 解析所有類別與函式節點,驗證必備標籤完整且修改概要字數介於 10 至 40 字
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 自動掃描程式碼AST並強制檢查九欄位註解規範
|
||||
[輸入參數]
|
||||
- methodName (str): unittest 測試方法名稱
|
||||
[輸出結果]
|
||||
- return (None): 斷言全專案程式碼符合文件規範
|
||||
[關聯測試] Feature: 台股現貨與期貨資料修復及零和對手方還原 / Scenario: [正例] 正確解析民國日期、去重 3 倍重複位移並以大台隱含指數驗證對齊
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
|
||||
def test_all_src_docstrings_have_nine_tags_and_valid_summary_len(self) -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, ast, pathlib
|
||||
[設計目的] 執行全專案 src/*.py 之 Docstring 合規與防文件腐敗 Linter 檢驗
|
||||
[程式說明] 走訪所有 ClassDef、FunctionDef 與 AsyncFunctionDef 節點檢查 9 標籤與修改概要字數
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 驗證所有原始碼函式具備九大標籤且概要長度合規
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (None): 任何缺失或字數違規即觸發斷言失敗
|
||||
[關聯測試] Feature: 台股現貨與期貨資料修復及零和對手方還原 / Scenario: [正例] 正確解析民國日期、去重 3 倍重複位移並以大台隱含指數驗證對齊
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
py_files = sorted(SRC_DIR.glob("*.py"))
|
||||
self.assertGreater(len(py_files), 0)
|
||||
violations: list[str] = []
|
||||
checked_nodes = 0
|
||||
for py_file in py_files:
|
||||
tree = ast.parse(py_file.read_text(encoding="utf-8"), filename=str(py_file))
|
||||
for node in ast.walk(tree):
|
||||
if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
|
||||
checked_nodes += 1
|
||||
doc = ast.get_docstring(node)
|
||||
if not doc:
|
||||
violations.append(f"{py_file.name}:{node.name} missing docstring")
|
||||
continue
|
||||
missing = [tag for tag in REQUIRED_DOC_TAGS if tag not in doc]
|
||||
if missing:
|
||||
violations.append(f"{py_file.name}:{node.name} missing tags {missing}")
|
||||
summary = extract_summary_line(doc)
|
||||
if not (10 <= len(summary) <= 40):
|
||||
violations.append(
|
||||
f"{py_file.name}:{node.name} summary len={len(summary)} out of [10,40]: {summary!r}"
|
||||
)
|
||||
self.assertGreater(checked_nodes, 10)
|
||||
self.assertEqual(violations, [], f"Docstring Linter Violations:\n" + "\n".join(violations))
|
||||
|
||||
|
||||
class TestF01DataAudit(unittest.TestCase):
|
||||
"""
|
||||
[使用工具] Python 3.9, unittest, pandas, json
|
||||
[設計目的] 驗證 Feature F01 資料修復、零和散戶推導與 Pre-mortem 異常攔截場景
|
||||
[程式說明] 測試民國日期與 2024 閏年修復、已輸出清潔表之相關係數門檻及 2025-03-03 零未平倉防護
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 執行F01資料修復與零和隱含散戶之BDD正反例測試
|
||||
[輸入參數]
|
||||
- methodName (str): unittest 測試方法名稱
|
||||
[輸出結果]
|
||||
- return (None): 斷言 F01 各項資料修復與防禦指標皆成立
|
||||
[關聯測試] Feature: 台股現貨與期貨資料修復及零和對手方還原 / Scenario: [Pre-mortem] 末日全市場未平倉為 0 的未結算快照污染日變動量與隱含指數
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
|
||||
def test_roc_and_leap_year_date_repair(self) -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas
|
||||
[設計目的] 驗證 F01 正例場景之民國日期解析與 2024-02-29 閏年異常修正
|
||||
[程式說明] 測試 '0100/01/03' 轉 2011-01-03 及 '2024-02-29 00:00:00' 不再產生 3935 年錯誤
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 驗證民國日期與2024閏年修正不再出現3935年錯誤
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (None): 斷言解析日期完全精確
|
||||
[關聯測試] Feature: 台股現貨與期貨資料修復及零和對手方還原 / Scenario: [正例] 正確解析民國日期、去重 3 倍重複位移並以大台隱含指數驗證對齊
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
self.assertEqual(parse_roc_date("0100/01/03"), pd.Timestamp("2011-01-03"))
|
||||
self.assertEqual(parse_roc_date("2024-02-29 00:00:00"), pd.Timestamp("2024-02-29"))
|
||||
|
||||
def test_cleaned_outputs_zero_sum_and_premortem_zero_oi(self) -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas, json
|
||||
[設計目的] 驗證清理輸出檔滿足零和恆等式、大台交叉驗證高精度與末日零 OI 隔離
|
||||
[程式說明] 檢查 3,049 日現貨表、2025-03-03 OI 欄是否為 NaN 並改用 VWAP、及隱含散戶零和總和為 0
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 驗證清理後現貨行數、大台精度與末日零OI隔離邏輯
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (None): 斷言所有資料完整性條件成立
|
||||
[關聯測試] Feature: 台股現貨與期貨資料修復及零和對手方還原 / Scenario: [Pre-mortem] 末日全市場未平倉為 0 的未結算快照污染日變動量與隱含指數
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
summary = json.loads((CLEANED_DIR / "phase1_audit_and_eda_summary.json").read_text(encoding="utf-8"))
|
||||
self.assertEqual(summary["spot_audit"]["repaired_spot_rows"], 3049)
|
||||
self.assertGreater(summary["eda_summary"]["overlap_post_202208_corr"], 0.998)
|
||||
|
||||
daily = pd.read_csv(CLEANED_DIR / "merged_daily_market_features_202109_202503.csv")
|
||||
last_row = daily[daily["date"] == "2025-03-03"].iloc[0]
|
||||
self.assertTrue(pd.isna(last_row["tx_implied_oi_price"]))
|
||||
self.assertTrue(pd.isna(last_row["tx_foreign_oi_net"]))
|
||||
self.assertTrue(pd.isna(last_row["tx_foreign_doi"]))
|
||||
self.assertFalse(pd.isna(last_row["index_proxy"]))
|
||||
|
||||
# Verify zero-sum identity across all valid OI rows for TX and MTX
|
||||
valid = daily.dropna(subset=["tx_foreign_oi_net"])
|
||||
zero_sum = (
|
||||
valid["tx_foreign_oi_net"]
|
||||
+ valid["tx_trust_oi_net"]
|
||||
+ valid["tx_dealer_oi_net"]
|
||||
+ valid["tx_retail_implied_oi_net"]
|
||||
)
|
||||
self.assertTrue((zero_sum.abs() < 1e-9).all())
|
||||
self.assertTrue(np.isnan(safe_corr(pd.Series([0.0, 0.0, 0.0, 0.0]), pd.Series([1.0, 2.0, 3.0, 4.0]))))
|
||||
|
||||
|
||||
class TestF02TwseTaifexSupplement(unittest.TestCase):
|
||||
"""
|
||||
[使用工具] Python 3.9, unittest, pandas, tempfile
|
||||
[設計目的] 驗證 Feature F02 官方端點解析邏輯與 Pre-mortem 髒資料攔截防線
|
||||
[程式說明] 測試 TWSE JSON 合併、TAIFEX CP950 編碼與零分母標記 NaN,並模擬偏差逾 500 點觸發阻斷
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 執行F02現貨與選擇權補抓解析與髒資料攔截測試
|
||||
[輸入參數]
|
||||
- methodName (str): unittest 測試方法名稱
|
||||
[輸出結果]
|
||||
- return (None): 斷言 F02 正例與防禦場景全數通過
|
||||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [Pre-mortem] 外部補抓資料與大台隱含指數發生嚴重錯位或異常偏離
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
|
||||
def test_twse_json_and_taifex_cp950_parsing(self) -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas
|
||||
[設計目的] 驗證 TWSE 雙端點 JSON 合併與 TAIFEX CP950 CSV 解碼及零分母保護
|
||||
[程式說明] 驗證民國日期與千分位數字清理,並確認買權量為 0 時 Put/Call 比安全轉為 NaN
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 驗證TWSE與TAIFEX格式解析與買權零分母安全處理
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (None): 斷言欄位值與型態完全正確
|
||||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [正例] 分批解析 TAIFEX pcRatioDown 的 CP950 編碼 CSV 並消除跨批重疊
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
sup = TwseSpotSupplementer()
|
||||
ohlc_j = {"stat": "OK", "data": [["113/10/01", "22,227.08", "22,442.75", "22,227.08", "22,390.39"]]}
|
||||
vol_j = {"stat": "OK", "data": [["113/10/01", "1,000,000", "250,000,000", "500,000", "22,390.39", "100.0"]]}
|
||||
df_twse = sup.parse_twse_month_records(ohlc_j, vol_j)
|
||||
self.assertEqual(df_twse.loc[0, "date"], "2024-10-01")
|
||||
self.assertAlmostEqual(df_twse.loc[0, "close"], 22390.39)
|
||||
self.assertAlmostEqual(df_twse.loc[0, "turnover_ntd"], 250000000.0)
|
||||
|
||||
csv_bytes = (
|
||||
"日期,賣權成交量,買權成交量,買賣權成交量比率%,賣權未平倉量,買權未平倉量,買賣權未平倉量比率%\n"
|
||||
"2024/10/01,250000,200000,125.00,310000,240000,129.17\n"
|
||||
"2024/10/02,100,0,0,100,0,0\n"
|
||||
).encode("cp950")
|
||||
df_pc = TaifexPcRatioSupplementer.parse_pc_csv(csv_bytes)
|
||||
self.assertEqual(len(df_pc), 2)
|
||||
self.assertAlmostEqual(df_pc.loc[0, "pc_oi_ratio_pct"], 129.17)
|
||||
self.assertTrue(pd.isna(df_pc.loc[1, "pc_vol_ratio_pct"]))
|
||||
self.assertTrue(pd.isna(df_pc.loc[1, "pc_oi_ratio_pct"]))
|
||||
|
||||
def test_premortem_dirty_spot_gate_blocks_overwrite(self) -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas, unittest
|
||||
[設計目的] 驗證當補抓現貨偏差大台隱含價逾 500 點時,Pre-mortem 守門必須攔截寫入
|
||||
[程式說明] 建構偏差 7,000 點之錯位現貨資料送入 validate_against_tx_proxy 驗證其拋出 DataValidationError
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 驗證錯位現貨逾500點時守門例外成功阻斷髒資料寫入
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (None): 斷言觸發 DataValidationError 且錯誤訊息精確
|
||||
[關聯測試] Feature: TWSE 真實現貨與 TAIFEX 選擇權 Put/Call Ratio 缺失資料補齊 / Scenario: [Pre-mortem] 外部補抓資料與大台隱含指數發生嚴重錯位或異常偏離
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
dates = pd.date_range("2024-09-02", periods=12, freq="B").strftime("%Y-%m-%d")
|
||||
tx_proxy = pd.DataFrame({"date": dates, "tx_implied_oi_price": np.linspace(22000, 22800, 12)})
|
||||
bad_spot = pd.DataFrame({"date": dates, "close": np.linspace(15000, 15500, 12)})
|
||||
with self.assertRaises(DataValidationError):
|
||||
TwseSpotSupplementer.validate_against_tx_proxy(bad_spot, tx_proxy)
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
bad_html = b"<html><body>Service Unavailable</body></html>"
|
||||
with self.assertRaises(DataValidationError):
|
||||
TaifexPcRatioSupplementer.parse_pc_csv(bad_html)
|
||||
self.assertTrue(Path(tmpdir).exists())
|
||||
|
||||
|
||||
class TestF03PttHitsSentiment(unittest.TestCase):
|
||||
"""
|
||||
[使用工具] Python 3.9, unittest, numpy, pandas
|
||||
[設計目的] 驗證 Feature F03 PTT 解析、HITS 收斂、水軍防禦、零矩陣防除零與斷路器
|
||||
[程式說明] 覆蓋正例互動剪刀差與三個 Pre-mortem 災難場景測試
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 執行F03社群HITS計算與水軍/零矩陣/斷路器防禦測試
|
||||
[輸入參數]
|
||||
- methodName (str): unittest 測試方法名稱
|
||||
[輸出結果]
|
||||
- return (None): 斷言 HITS 演算法及所有邊界防禦均正確運作
|
||||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [Pre-mortem] 水軍帳號自我推文或集中洗板造成 Hub/Authority 權重遭到操縱
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
|
||||
def test_hits_convergence_sybil_defense_and_zero_matrix(self) -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, numpy, pandas
|
||||
[設計目的] 驗證 HITS L2 正規化收斂、自推自連消除、權重截斷與全零矩陣安全回傳
|
||||
[程式說明] 注入作者自推與洗板 50 次情境驗證對角線為 0 與上限截斷,並測試零矩陣回傳零向量
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 驗證HITS收斂特性、水軍自連清除及零矩陣防除零保護
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (None): 斷言矩陣對角線為 0、L2 範數為 1 且零矩陣不報錯
|
||||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [Pre-mortem] 休市日或無有效推文導致鄰接矩陣全為零使 HITS 迭代發生除零崩潰
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
rows = [
|
||||
{"source_user": "a1", "target_author": "a1", "edge_weight": 5.0, "interaction_sentiment": 1.0, "article_sentiment": 1.0},
|
||||
{"source_user": "spam_bot", "target_author": "a1", "edge_weight": 50.0, "interaction_sentiment": 1.0, "article_sentiment": 1.0},
|
||||
{"source_user": "real_hub", "target_author": "a1", "edge_weight": 1.0, "interaction_sentiment": 1.0, "article_sentiment": 1.0},
|
||||
{"source_user": "real_hub", "target_author": "a2", "edge_weight": 1.0, "interaction_sentiment": -1.0, "article_sentiment": -1.0},
|
||||
]
|
||||
df = pd.DataFrame(rows)
|
||||
nodes, adj = PttStockHitsPipeline.build_interaction_graph(df, max_pair_weight=3.0)
|
||||
self.assertTrue((np.diag(adj) == 0.0).all())
|
||||
self.assertLessEqual(float(adj.max()), 3.0)
|
||||
|
||||
auth, hub, iters, converged = PttStockHitsPipeline.compute_hits_scores(adj)
|
||||
self.assertTrue(converged)
|
||||
self.assertLessEqual(iters, 100)
|
||||
self.assertAlmostEqual(float(np.linalg.norm(auth)), 1.0, places=5)
|
||||
self.assertAlmostEqual(float(np.linalg.norm(hub)), 1.0, places=5)
|
||||
|
||||
zero_res = PttStockHitsPipeline().compute_daily_divergence(
|
||||
pd.DataFrame([{"source_user": "a1", "target_author": "a1", "edge_weight": 1.0, "interaction_sentiment": 1.0, "article_sentiment": 1.0}])
|
||||
)
|
||||
self.assertEqual(zero_res["hits_divergence_delta"], 0.0)
|
||||
self.assertTrue(zero_res["converged"])
|
||||
|
||||
def test_crawler_circuit_breaker_opens_on_repeated_429(self) -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, urllib
|
||||
[設計目的] 驗證 PTT 爬蟲連續遭遇 HTTP 429 限流時斷路器是否如期啟動熔斷
|
||||
[程式說明] 注入模擬 429 例外之 mock opener,確認第 3 次失敗即開啟斷路器並阻擋後續請求
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 驗證爬蟲連續遭遇429限流時斷路器正確觸發熔斷
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (None): 斷言第 3 次起拋出 CircuitBreakerOpenError
|
||||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [Pre-mortem] 爬蟲遭遇 HTTP 429/503 限流或反覆斷線導致程式無窮重試或寫入毀損檔案
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
pipe = PttStockHitsPipeline(max_consecutive_failures=3)
|
||||
|
||||
def mock_429(url: str) -> str:
|
||||
"""
|
||||
[使用工具] Python 3.9, urllib
|
||||
[設計目的] 模擬 PTT 伺服器回傳 HTTP 429 過載限流回應供斷路器測試使用
|
||||
[程式說明] 每次被呼叫均直接拋出狀態碼為 429 的 HTTPError
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 模擬HTTP 429限流錯誤供斷路器測試呼叫使用
|
||||
[輸入參數]
|
||||
- url (str): 請求網址
|
||||
[輸出結果]
|
||||
- return (str): 永不回傳,直接拋出 HTTPError 429
|
||||
[關聯測試] Feature: PTT Stock 版輿論爬蟲與 HITS 演算法雙向權重計算 / Scenario: [Pre-mortem] 爬蟲遭遇 HTTP 429/503 限流或反覆斷線導致程式無窮重試或寫入毀損檔案
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
raise urllib.error.HTTPError(url, 429, "Too Many Requests", {}, None)
|
||||
|
||||
with self.assertRaises(DataValidationError):
|
||||
pipe.fetch_html_with_breaker("https://www.ptt.cc/bbs/Stock/index.html", opener=mock_429, max_retries=0)
|
||||
with self.assertRaises(DataValidationError):
|
||||
pipe.fetch_html_with_breaker("https://www.ptt.cc/bbs/Stock/index.html", opener=mock_429, max_retries=0)
|
||||
with self.assertRaises(CircuitBreakerOpenError):
|
||||
pipe.fetch_html_with_breaker("https://www.ptt.cc/bbs/Stock/index.html", opener=mock_429, max_retries=0)
|
||||
|
||||
|
||||
class TestF04Ptt10YrAndTopics(unittest.TestCase):
|
||||
"""
|
||||
[使用工具] Python 3.9, unittest, datetime
|
||||
[設計目的] 驗證 Feature F04 PTT 十年時間戳反推、二分搜尋收斂、產業詞庫與置底雜訊防禦
|
||||
[程式說明] 測試 Unix 時間戳轉日期、爆與 X1 熱度計算、英文短字防誤判、及跨十年模擬二分搜尋收斂
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 執行F04 PTT十年頁碼定位與產業話題抽取BDD測試
|
||||
[輸入參數]
|
||||
- methodName (str): unittest 測試方法名稱
|
||||
[輸出結果]
|
||||
- return (None): 斷言 F04 正例與 Pre-mortem 防禦情境通過
|
||||
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [Pre-mortem] 歷史刪文、置底公告或無效時間戳記導致二分搜尋陷入無窮迴圈或頁碼錯位
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
|
||||
def test_timestamp_nrec_and_lexicon_precision(self) -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, unittest
|
||||
[設計目的] 驗證 Unix 時間戳轉台灣日期、推文熱度數值化及英文邊界防誤判規則
|
||||
[程式說明] 確認 'Taiwan' 不會觸發 AI 標籤、'2330'+'AI' 正確匹配,且爆=100、X2=-20
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 驗證時間戳轉日期、推文熱度轉換與英文短字邊界防誤判
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (None): 斷言各項解析與標籤抽取結果完全準確
|
||||
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [正例] 抽取 12 大台股產業與 6 大宏觀籌碼話題標籤並計算熱門文章 HITS 剪刀差序列
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
ts = PttTenYearExplorer.extract_timestamp_from_href("/bbs/Stock/M.1434355200.A.123.html")
|
||||
self.assertEqual(ts, 1434355200)
|
||||
self.assertEqual(PttTenYearExplorer.ts_to_date_str(ts), "2015-06-15")
|
||||
self.assertIsNone(PttTenYearExplorer.extract_timestamp_from_href(""))
|
||||
self.assertEqual(PttTenYearExplorer.parse_nrec_score("爆"), 100)
|
||||
self.assertEqual(PttTenYearExplorer.parse_nrec_score("X2"), -20)
|
||||
self.assertEqual(PttTenYearExplorer.parse_nrec_score("45"), 45)
|
||||
|
||||
t_safe = PttTenYearExplorer.extract_industry_and_topic_tags("[新聞] Taiwan 央行利率決議與美債殖利率")
|
||||
self.assertNotIn("ind_ai_server", t_safe["industries"])
|
||||
self.assertIn("top_macro_rates", t_safe["topics"])
|
||||
|
||||
t_ai = PttTenYearExplorer.extract_industry_and_topic_tags("[標的] 台積電 2330 AI 伺服器與外資買超")
|
||||
self.assertIn("ind_semiconductor", t_ai["industries"])
|
||||
self.assertIn("ind_ai_server", t_ai["industries"])
|
||||
self.assertIn("top_institutional_flow", t_ai["topics"])
|
||||
|
||||
def test_premortem_binary_search_with_pinned_and_deleted_posts(self) -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, unittest, datetime
|
||||
[設計目的] 驗證二分搜尋面對置底舊公告與全頁刪文時仍可在有界步數收斂而不陷入死循環
|
||||
[程式說明] 建立 100 頁橫跨 2015 至 2025 的模擬看板,含第 50 頁全刪文與每頁 2020 置底雜訊
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 驗證二分搜尋遭遇刪文空頁與置底公告仍精確收斂不死鎖
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (None): 斷言在 24 步內精確定位至目標年份附近頁碼
|
||||
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [Pre-mortem] 歷史刪文、置底公告或無效時間戳記導致二分搜尋陷入無窮迴圈或頁碼錯位
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
explorer = PttTenYearExplorer(board_sleep=0.0, article_sleep=0.0)
|
||||
base_ts = 1420070400 # 2015-01-01
|
||||
end_ts = 1735689600 # 2025-01-01
|
||||
|
||||
def mock_board(url: str) -> str:
|
||||
"""
|
||||
[使用工具] Python 3.9
|
||||
[設計目的] 生成跨十年模擬看板 HTML(含刪文空白頁與置底舊公告)供二分搜尋測試使用
|
||||
[程式說明] 依頁碼線性計算時間戳,第 50 頁故意回傳全刪文頁面,所有頁面底部附帶 2020 年置底公告
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 模擬跨十年看板HTML含刪文頁與置底舊公告供測試
|
||||
[輸入參數]
|
||||
- url (str): 請求網址
|
||||
[輸出結果]
|
||||
- return (str): 模擬 HTML 字串
|
||||
[關聯測試] Feature: PTT Stock 版十年歷史頁碼定位、熱門文章 HITS 剪刀差與產業話題特徵抽取 / Scenario: [Pre-mortem] 歷史刪文、置底公告或無效時間戳記導致二分搜尋陷入無窮迴圈或頁碼錯位
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
import re as _re
|
||||
|
||||
m = _re.search(r"index(\d+)\.html", url)
|
||||
p = int(m.group(1)) if m else 100
|
||||
prev_p = max(1, p - 1)
|
||||
if p == 50:
|
||||
body = '<div class="r-ent"><div class="title">(本文已被刪除)</div></div>'
|
||||
else:
|
||||
ts = int(base_ts + (p - 1) / 99.0 * (end_ts - base_ts))
|
||||
body = (
|
||||
f'<div class="r-ent"><div class="nrec"><span class="hl">30</span></div>'
|
||||
f'<div class="title"><a href="/bbs/Stock/M.{ts}.A.001.html">[情報] p{p}</a></div>'
|
||||
f'<div class="meta"><div class="author">u{p}</div><div class="date">01/01</div></div></div>'
|
||||
)
|
||||
pinned = (
|
||||
'<div class="r-list-sep"></div>'
|
||||
'<div class="r-ent"><div class="title"><a href="/bbs/Stock/M.1580000000.A.999.html">[公告] 版規</a></div></div>'
|
||||
)
|
||||
return f'<div class="btn-group-paging"><a href="/bbs/Stock/index{prev_p}.html">‹ 上頁</a></div>{body}{pinned}'
|
||||
|
||||
res = explorer.locate_page_for_target_date("2020-01-01", 1, 100, opener=mock_board)
|
||||
self.assertLessEqual(res["steps"], 24)
|
||||
self.assertTrue(45 <= res["matched_page"] <= 55)
|
||||
|
||||
|
||||
class TestF05CrossMarketSamplerAndTaxonomy(unittest.TestCase):
|
||||
"""
|
||||
[使用工具] Python 3.9, unittest, datetime
|
||||
[設計目的] 驗證 Feature F05 雙軸分層目錄、五語分類詞庫、跨時區 13:30 防洩漏及防反爬蟲攔截
|
||||
[程式說明] 測試美日韓中四國語料解析與統一標籤映射,並測試 13:30 收盤後貼文與 CAPTCHA 攔截保護
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 執行F05跨國取樣、五語分類與時區防洩漏BDD正反例測試
|
||||
[輸入參數]
|
||||
- methodName (str): unittest 測試方法名稱
|
||||
[輸出結果]
|
||||
- return (None): 斷言 F05 全數測試情境通過
|
||||
[關聯測試] Feature: 跨國股市論壇(美日韓中)輕量化取樣、多語言語料分類與跨時區因果防洩漏對齊 / Scenario: [Pre-mortem] 跨時區發表時間誤歸入當日台股交易視窗導致未來函數洩漏
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
|
||||
def test_multilingual_taxonomy_and_four_country_parsers(self) -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, unittest
|
||||
[設計目的] 驗證五語分類詞庫精準映射 12 產業與 6 話題,及離線四國取樣與雙軸目錄建置
|
||||
[程式說明] 測試英日韓簡中句子是否正確歸入統一標籤並執行完整離線四國管線
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 驗證五語統一分類詞庫與四國語料解析管線完整運作
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (None): 斷言各語系分類與離線管線輸出筆數正確
|
||||
[關聯測試] Feature: 跨國股市論壇(美日韓中)輕量化取樣、多語言語料分類與跨時區因果防洩漏對齊 / Scenario: [正例] 建立雙軸資料湖分離結構並透過五語統一辭典映射 12 大產業與 6 大話題
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
tax = MultilingualCorpusTaxonomy()
|
||||
kr_tag = tax.classify_text("SK하이닉스 HBM 엔비디아 호재 매수")
|
||||
self.assertIn("ind_semiconductor", kr_tag["industries"])
|
||||
self.assertIn("ind_ai_server", kr_tag["industries"])
|
||||
self.assertGreater(kr_tag["lexical_sentiment"], 0.0)
|
||||
|
||||
jp_tag = tax.classify_text("東京エレクトロン 強く売りたい 暴落")
|
||||
self.assertIn("ind_semiconductor", jp_tag["industries"])
|
||||
self.assertLess(jp_tag["lexical_sentiment"], 0.0)
|
||||
|
||||
res = CrossMarketSamplingPipeline().run_offline_verification()
|
||||
self.assertEqual(res["offline_rows_by_region"], {"US": 1, "KR": 1, "JP": 1, "CN": 1})
|
||||
self.assertGreaterEqual(res["aligned_summary_rows"], 3)
|
||||
|
||||
# Verify Naver Mobile JSON & US RSS XML backup parsers
|
||||
naver_json = json.dumps(
|
||||
{
|
||||
"discussions": [
|
||||
{
|
||||
"discussionId": 555,
|
||||
"title": "삼성전자 HBM 수율 돌파 매수",
|
||||
"contents": "반도체 반등 기대",
|
||||
"date": "2026-11-20T09:10:00+09:00",
|
||||
"writerId": "kr_pro",
|
||||
"readCount": 200,
|
||||
"sympathyCount": 18,
|
||||
"antipathyCount": 2,
|
||||
"isHideCleanbot": False,
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
kr_rows = KrNaverBoardSampler(tax).parse_naver_mobile_json(naver_json, "005930")
|
||||
self.assertEqual(len(kr_rows), 1)
|
||||
self.assertEqual(kr_rows[0]["tw_effective_trading_date"], "2026-11-20")
|
||||
self.assertAlmostEqual(kr_rows[0]["native_sentiment"], 0.8)
|
||||
|
||||
rss_xml = (
|
||||
"<rss><channel><item><title>TSMC AI server chip demand surge</title>"
|
||||
"<pubDate>Thu, 19 Nov 2026 22:00:00 +0000</pubDate>"
|
||||
"<guid>rss-1</guid></item></channel></rss>"
|
||||
)
|
||||
us_rss_rows = UsStocktwitsRedditSampler(tax).parse_us_rss_xml(rss_xml, "yahoo_us_rss", "TSM")
|
||||
self.assertEqual(len(us_rss_rows), 1)
|
||||
self.assertEqual(us_rss_rows[0]["tw_effective_trading_date"], "2026-11-20")
|
||||
self.assertIn("ind_ai_server", us_rss_rows[0]["industries"])
|
||||
|
||||
def test_premortem_timezone_cutoff_and_antibot_guard(self) -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, datetime, unittest
|
||||
[設計目的] 驗證台北 13:30 收盤切點防止未來函數洩漏,以及 Cloudflare/CAPTCHA 攔截保護
|
||||
[程式說明] 檢查週五 14:30 貼文必須順延至下週一交易日,以及含 Cloudflare 標記 HTML 必須拋錯阻斷
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 驗證13:30收盤後跨時區順延與反爬蟲驗證頁攔截防線
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (None): 斷言防洩漏日期推算正確且反爬蟲頁面觸發 DataValidationError
|
||||
[關聯測試] Feature: 跨國股市論壇(美日韓中)輕量化取樣、多語言語料分類與跨時區因果防洩漏對齊 / Scenario: [Pre-mortem] 跨時區發表時間誤歸入當日台股交易視窗導致未來函數洩漏
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
# 2026-11-20 is Friday; 14:30 is after 13:30 close -> must shift to Monday 2026-11-23
|
||||
fri_after = dt.datetime(2026, 11, 20, 14, 30, 0, tzinfo=TW_TZ)
|
||||
eff_dt, sess = CausalTimezoneAligner.assign_tw_effective_date_and_session(fri_after)
|
||||
self.assertEqual(eff_dt, "2026-11-23")
|
||||
self.assertEqual(sess, "1_US_Overnight_Lead")
|
||||
|
||||
# 2026-11-20 08:20 is JPKR morning pre-market -> same day 2026-11-20, 2_JPKR_PreMarket_Lead
|
||||
fri_jpkr = dt.datetime(2026, 11, 20, 8, 20, 0, tzinfo=TW_TZ)
|
||||
eff_dt2, sess2 = CausalTimezoneAligner.assign_tw_effective_date_and_session(fri_jpkr)
|
||||
self.assertEqual(eff_dt2, "2026-11-20")
|
||||
self.assertEqual(sess2, "2_JPKR_PreMarket_Lead")
|
||||
|
||||
cf_html = b"<html><title>Just a moment...</title><body>cf-browser-verification</body></html>"
|
||||
with self.assertRaises(DataValidationError):
|
||||
BaseForumSampler.decode_and_guard(cf_html, ("utf-8",))
|
||||
|
||||
|
||||
class TestF06GraphLaoziLhsAndFalsification(unittest.TestCase):
|
||||
"""
|
||||
[使用工具] Python 3.9, unittest, numpy, pandas
|
||||
[設計目的] 驗證 Feature F06 圖論網路、老子四時狀態機、LHS 抽樣與三層聯立反證公式
|
||||
[程式說明] 測試 MST 與 Fiedler 退化防護、4x4 轉移矩陣機率守恆、LHS 分層均勻性及反證降倉與冷卻機制
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 執行F06圖論、老子四時、LHS檢定與反證公式BDD測試
|
||||
[輸入參數]
|
||||
- methodName (str): unittest 測試方法名稱
|
||||
[輸出結果]
|
||||
- return (None): 斷言所有正例與 Pre-mortem 防護邏輯皆通過
|
||||
[關聯測試] Feature: 跨商品圖論網路、老子四時相位狀態機、LHS-蒙地卡羅檢定與三層聯立反證公式 / Scenario: [Pre-mortem] 反證公式觸發後發生死鎖或於閾值邊緣高頻開關抖動造成過度交易損耗
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
|
||||
def test_graph_mst_te_laozi_and_lhs_stratification(self) -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, numpy, pandas
|
||||
[設計目的] 驗證圖論距離/MST/轉移熵非負性、老子馬可夫列和為 1 及 LHS 分層抽樣均勻性
|
||||
[程式說明] 建立具因果滯後之模擬面板驗證 TE(X->Y) > TE(Y->X)、檢查 4x4 轉移矩陣及驗證 LHS 每層恰含 1 樣本
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 驗證圖論MST、轉移熵方向性、老子狀態機與LHS分層特性
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (None): 斷言數學性質全數成立
|
||||
[關聯測試] Feature: 跨商品圖論網路、老子四時相位狀態機、LHS-蒙地卡羅檢定與三層聯立反證公式 / Scenario: [正例] 計算滾動 Kruskal 最小生成樹、Fiedler 代數連通度、Forman-Ricci 曲率與轉移熵因果矩陣
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
rng = np.random.default_rng(7)
|
||||
n_obs = 120
|
||||
x = rng.choice([-1.0, 0.0, 1.0], size=n_obs)
|
||||
y = np.roll(x, 1) # X leads Y by 1 day
|
||||
df_te = pd.DataFrame({"X_lead": x, "Y_follow": y, "Z_const": np.zeros(n_obs)})
|
||||
te_mat, _ = MarketGraphEngine.compute_transfer_entropy_matrix(df_te[["X_lead", "Y_follow"]], n_bins=3, lag=1)
|
||||
self.assertGreater(te_mat[0, 1], te_mat[1, 0])
|
||||
self.assertTrue((te_mat >= 0.0).all())
|
||||
|
||||
# Pre-mortem GraphDegeneracy: constant zero column + late listing NaNs
|
||||
panel = pd.DataFrame({"date": pd.date_range("2024-01-01", periods=50, freq="B").strftime("%Y-%m-%d"), "twse_ret": rng.normal(0, 0.01, 50), "a": rng.normal(0, 1, 50), "b": rng.normal(0, 1, 50), "c_const": np.zeros(50), "d_late": np.nan})
|
||||
gdf, _, _ = MarketGraphEngine(min_valid_ratio=0.8).extract_rolling_graph_features(panel, target_col="twse_ret", window=20)
|
||||
self.assertTrue((gdf["fiedler_lambda2"].dropna() >= 0.0).all())
|
||||
self.assertFalse(gdf["mst_norm_length"].dropna().isna().any())
|
||||
|
||||
# Laozi Four-Seasons Markov matrix row sums == 1.0
|
||||
px = 15000.0 + np.cumsum(rng.normal(2.0, 80.0, size=100))
|
||||
sim_daily = pd.DataFrame({"date": pd.date_range("2024-01-01", periods=100, freq="B").strftime("%Y-%m-%d"), "twse_close": px, "index_proxy": px})
|
||||
s_df, trans_mat = LaoziDynamicsEngine.compute_four_seasons_state_machine(sim_daily)
|
||||
self.assertEqual(len(s_df), 100)
|
||||
self.assertTrue(np.allclose(trans_mat.sum(axis=1), np.ones(4), atol=1e-6))
|
||||
|
||||
# LHS stratification: each bin [i/N, (i+1)/N) contains exactly 1 sample per dimension
|
||||
validator = LhsMonteCarloValidator(seed=12)
|
||||
lhs_u = validator.sample_lhs_iman_conover(20, 3, target_corr=np.eye(3))
|
||||
for d in range(3):
|
||||
bins = np.floor(lhs_u[:, d] * 20).astype(int)
|
||||
self.assertEqual(sorted(bins.tolist()), list(range(20)))
|
||||
|
||||
def test_premortem_popper_falsification_triggers_and_recovers(self) -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, numpy
|
||||
[設計目的] 驗證三層聯立反證公式在極端回撤與結構突變下觸發降倉,且恢復期具冷卻防抖動不死鎖
|
||||
[程式說明] 注入 -15% 連續暴跌與顯性 IC 崩塌情境驗證 C2/C3 觸發保護,隨後注入平穩正報酬驗證冷卻後恢復
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 驗證三層反證公式極端觸發降倉與冷卻期後恢復運作
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (None): 斷言暴跌期間權重受壓縮且恢復後權重回復正常
|
||||
[關聯測試] Feature: 跨商品圖論網路、老子四時相位狀態機、LHS-蒙地卡羅檢定與三層聯立反證公式 / Scenario: [Pre-mortem] 反證公式觸發後發生死鎖或於閾值邊緣高頻開關抖動造成過度交易損耗
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
n = 150
|
||||
raw_w = np.ones(n) * 0.8
|
||||
rets = np.concatenate([np.full(80, 0.002), np.full(15, -0.015), np.full(55, 0.002)])
|
||||
te_vecs = [np.array([0.25, 0.25, 0.25, 0.25]) for _ in range(n)]
|
||||
te_vecs[85] = np.array([0.97, 0.01, 0.01, 0.01])
|
||||
phase_ll = np.full(n, -5.0)
|
||||
kedao_ic = np.concatenate([np.full(80, 0.1), np.full(15, -0.25), np.full(55, 0.1)])
|
||||
|
||||
engine = PopperFalsificationEngine(cooldown_days=5)
|
||||
res = engine.evaluate_and_protect(raw_w, rets, te_vecs, phase_ll, kedao_ic, cvar_dd_per_vol=0.5, warmup=60)
|
||||
|
||||
# During crash [85..95], F_falsification_trigger must fire and compress protected_weight
|
||||
self.assertGreater(int(res.iloc[80:96]["F_falsification_trigger"].sum()), 0)
|
||||
self.assertLess(float(res.iloc[90]["protected_weight"]), 0.5)
|
||||
# After recovery & drawdown normalization at end [145..149], weight should recover above 0.5
|
||||
self.assertGreater(float(res.iloc[-1]["protected_weight"]), 0.5)
|
||||
|
||||
|
||||
class TestF07VisualCompendiumAndCitations(unittest.TestCase):
|
||||
"""
|
||||
[使用工具] Python 3.9, pathlib, tempfile, unittest
|
||||
[設計目的] 驗證 F07 分章節圖表文研究總覽之六大 PNG 圖檔與五大出處附錄完整性
|
||||
[程式說明] 正例檢查 docs/figures/ 與 docs/chapters/ 全部實體有效;反例注入假圖檔與斷鏈驗證攔截功能
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 驗證圖表產出完整性與附錄五大出處齊全性
|
||||
[輸入參數]
|
||||
- methodName (str): unittest 測試方法名稱
|
||||
[輸出結果]
|
||||
- return (None): 執行完整正反例斷言檢查
|
||||
[關聯測試] Feature: 分章節圖表文研究總覽與附錄五大出處自動化產出及完整性驗證 / Scenario: [正例] 驗證分章節圖表文報告與附錄五大類出處(資料、學說、公式、演算法、研究方法)完整性
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
|
||||
def test_generated_figures_and_compendium_audit(self) -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, pathlib, unittest
|
||||
[設計目的] 確認實測產出之六張高解析度研究圖表及分章與五大附錄出處全數通過完整性檢查
|
||||
[程式說明] 對 docs/chapters 與總覽文件執行 CompendiumIntegrityAuditor 並確認每張 PNG 合法
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 驗證六張PNG研究圖表與分章附錄出處完整性
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (None): 斷言 checked_images>=6 且 status=='PASSED'
|
||||
[關聯測試] Feature: 分章節圖表文研究總覽與附錄五大出處自動化產出及完整性驗證 / Scenario: [正例] 由 Phase 1–5 實證數據自動繪製六大高解析度研究圖表並標註對應研究模組
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
root_dir = SRC_DIR.parent
|
||||
docs_dir = root_dir / "docs"
|
||||
chapters_dir = docs_dir / "chapters"
|
||||
figs_dir = docs_dir / "figures"
|
||||
|
||||
expected_figs = [
|
||||
"fig01_phase1_2_spot_repair_and_pc_ratio.png",
|
||||
"fig02_phase3_4_ptt_10yr_hits_and_cross_market_corpus.png",
|
||||
"fig03_phase5_graph_mst_ricci_and_transfer_entropy.png",
|
||||
"fig04_phase5_laozi_four_seasons_and_dao_dynamics.png",
|
||||
"fig05_phase5_lhs_mc_and_multi_horizon_ic.png",
|
||||
"fig06_phase5_ablation_equity_and_popper_falsification.png",
|
||||
]
|
||||
for fname in expected_figs:
|
||||
self.assertTrue(
|
||||
ResearchFigureGenerator.validate_png_file(figs_dir / fname),
|
||||
f"Invalid or missing figure: {fname}",
|
||||
)
|
||||
|
||||
chapter_files = [
|
||||
docs_dir / "05_illustrated_research_compendium_and_references.md",
|
||||
chapters_dir / "CH01_data_audit_repair_and_supplement.md",
|
||||
chapters_dir / "CH02_ptt_10yr_hits_and_cross_market_corpus.md",
|
||||
chapters_dir / "CH03_cross_asset_graph_and_laozi_dynamics.md",
|
||||
chapters_dir / "CH04_lhs_monte_carlo_ablation_and_popper_falsification.md",
|
||||
chapters_dir / "CH05_202503_202611_latest_market_and_model_update.md",
|
||||
chapters_dir / "APPENDIX_sources_theories_formulas_and_methods.md",
|
||||
]
|
||||
res = CompendiumIntegrityAuditor.verify_report_links_and_citations(
|
||||
chapter_paths=chapter_files,
|
||||
appendix_path=chapters_dir / "APPENDIX_sources_theories_formulas_and_methods.md",
|
||||
)
|
||||
self.assertEqual(res["status"], "PASSED", msg=str(res))
|
||||
self.assertGreaterEqual(res["checked_images"], 6)
|
||||
|
||||
def test_premortem_corrupted_png_and_broken_links_rejected(self) -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, tempfile, pathlib, unittest
|
||||
[設計目的] 驗證空檔假圖與缺失出處連結時 Pre-mortem 稽核器能精確攔截並列出錯誤
|
||||
[程式說明] 建立假文字檔充當 PNG 並於臨時 Markdown 注入不存在圖檔,驗證 validate 與 verify 皆回報失敗
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 驗證損毀假圖與缺失出處斷鏈皆能即時攔截失敗
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (None): 斷言 validate_png_file 為 False 且稽核回傳 FAILED
|
||||
[關聯測試] Feature: 分章節圖表文研究總覽與附錄五大出處自動化產出及完整性驗證 / Scenario: [Pre-mortem] 報告內嵌圖表或對應研究檔案連結失效時攔截並回報缺漏清單
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
tdir = Path(tmp)
|
||||
fake_png = tdir / "corrupt.png"
|
||||
fake_png.write_bytes(b"NOT_A_PNG" * 2000)
|
||||
self.assertFalse(ResearchFigureGenerator.validate_png_file(fake_png))
|
||||
self.assertFalse(ResearchFigureGenerator.validate_png_file(tdir / "missing.png"))
|
||||
|
||||
bad_doc = tdir / "CH_bad.md"
|
||||
bad_doc.write_text("\n", encoding="utf-8")
|
||||
bad_app = tdir / "APPENDIX_incomplete.md"
|
||||
bad_app.write_text("## 附錄 A|僅列資料來源\n", encoding="utf-8")
|
||||
|
||||
res = CompendiumIntegrityAuditor.verify_report_links_and_citations([bad_doc], appendix_path=bad_app)
|
||||
self.assertEqual(res["status"], "FAILED")
|
||||
self.assertEqual(len(res["broken_images"]), 1)
|
||||
self.assertIn("附錄 B", res["missing_categories"])
|
||||
self.assertIn("附錄 E", res["missing_categories"])
|
||||
|
||||
|
||||
class TestF08TaifexFuturesLiveUpdate202611(unittest.TestCase):
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas, json, tempfile, unittest
|
||||
[設計目的] 驗證 F08 官方最新補齊至 2026/11/20 資料完整性與單位防呆、末日零 OI 覆蓋防線
|
||||
[程式說明] 正例驗證更新後資料突破 2025/03 達 2026-11-20 且零和成立;反例驗證契約金額除 1000 標準化及 2025-03-03 覆蓋修復
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 驗證F08最新官方抓補解析與末日零未平倉修復
|
||||
[輸入參數]
|
||||
- methodName (str): unittest 測試方法名稱
|
||||
[輸出結果]
|
||||
- return (None): 執行 F08 正反例自動化斷言
|
||||
[關聯測試] Feature: 官方源頭資料即時更新至 2026/11/20 與全模型、圖表文總覽重新計算驗證 / Scenario: [正例] 分批抓取並解析 TAIFEX futContractsDateDown 期貨三大法人 CSV 並還原零和隱含散戶至 2026/11/20
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
|
||||
def test_live_202611_outputs_and_implications(self) -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, pandas, json, unittest
|
||||
[設計目的] 確認 2025/03 至 2026/11/20 實網補齊資料成功合併並維持相關性與零和精確度
|
||||
[程式說明] 檢查更新版寬表突破 1,200 日涵蓋至 2026-11-20、2025-03-03 零 OI 已修復及相關係數高於 0.98
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 驗證更新至2026年底完整現貨期貨與零和驗證指標
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (None): 斷言 2026-11 最新市場特徵資料皆達標
|
||||
[關聯測試] Feature: 官方源頭資料即時更新至 2026/11/20 與全模型、圖表文總覽重新計算驗證 / Scenario: [正例] 合併 2025/03–2026/11 TWSE 現貨、期貨三大法人與選擇權 P/C Ratio 並重新執行圖論、老子四時、LHS-MC 與反證消融
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
summary_path = CLEANED_DIR.parent / "features_aligned" / "phase7_live_update_202611_summary.json"
|
||||
self.assertTrue(summary_path.exists())
|
||||
s = json.loads(summary_path.read_text(encoding="utf-8"))
|
||||
self.assertEqual(s["spot_summary"]["max_date"], "2026-11-20")
|
||||
self.assertGreater(s["enriched_rows"], 1200)
|
||||
self.assertGreater(s["validation_202503_202611"]["corr"], 0.98)
|
||||
self.assertIn("2025-03-03", s["futures_audit"]["repaired_zero_oi_dates"])
|
||||
|
||||
df = pd.read_csv(CLEANED_DIR / "merged_daily_market_features_enriched_202109_202611.csv")
|
||||
r0303 = df[df["date"] == "2025-03-03"].iloc[0]
|
||||
self.assertFalse(pd.isna(r0303["tx_foreign_oi_net"]))
|
||||
valid = df.dropna(subset=["tx_foreign_oi_net"])
|
||||
zero_sum = valid["tx_foreign_oi_net"] + valid["tx_trust_oi_net"] + valid["tx_dealer_oi_net"] + valid["tx_retail_implied_oi_net"]
|
||||
self.assertTrue((zero_sum.abs() < 1e-6).all())
|
||||
|
||||
def test_premortem_unit_normalization_and_zero_oi_override(self) -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, tempfile, pandas, unittest
|
||||
[設計目的] 驗證 TAIFEX CSV 契約金額單位變化、HTML 錯誤攔截與 2025-03-03 零未平倉覆蓋修復邏輯
|
||||
[程式說明] 測試 HTML 回傳拋錯、元換算千元單位縮放以及合併後 2025-03-03 官方資料覆蓋殘留零值
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 驗證契約金額單位防呆與20250303零未平倉覆蓋
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (None): 斷言單位換算、HTML 例外與零未平倉修復皆成立
|
||||
[關聯測試] Feature: 官方源頭資料即時更新至 2026/11/20 與全模型、圖表文總覽重新計算驗證 / Scenario: [Pre-mortem] 期交所 futContractsDateDown 契約金額單位變化或回傳非預期 HTML 時自動標準化與攔截
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
with self.assertRaises(DataValidationError):
|
||||
TaifexFuturesInstitutionalSupplementer.parse_futures_csv(b"<html><body>DateTime error</body></html>")
|
||||
|
||||
# Raw amount in Yuan (multiplied by 1000) -> auto-scaled back to Thousand NTD
|
||||
csv_yuan = (
|
||||
"日期,商品名稱,身份別,多方交易口數,多方交易契約金額(元),空方交易口數,空方交易契約金額(元),"
|
||||
"多空交易口數淨額,多空交易契約金額淨額(元),多方未平倉口數,多方未平倉契約金額(元),"
|
||||
"空方未平倉口數,空方未平倉契約金額(元),多空未平倉口數淨額,多空未平倉契約金額淨額(元)\n"
|
||||
"2025/03/03,臺股期貨,外資及陸資,100,450000000,100,450000000,0,0,100,450000000,200,900000000,-100,-450000000\n"
|
||||
"2025/03/03,臺股期貨,自營商,50,225000000,50,225000000,0,0,50,225000000,50,225000000,0,0\n"
|
||||
"2025/03/03,臺股期貨,投信,10,45000000,10,45000000,0,0,50,225000000,10,45000000,40,180000000\n"
|
||||
).encode("cp950")
|
||||
parsed = TaifexFuturesInstitutionalSupplementer.parse_futures_csv(csv_yuan)
|
||||
implied = float(parsed.loc[parsed["身份別"] == "外資及陸資", "多方未平倉契約金額(千元)"].iloc[0]) / (100.0 * 0.2)
|
||||
self.assertAlmostEqual(implied, 22500.0, places=2)
|
||||
|
||||
raw_xls = CLEANED_DIR.parent / "raw" / "futures_oi.xlsx"
|
||||
_, tx_px, audit = LiveMarketDatasetUpdater.merge_and_enrich_futures(raw_xls, parsed)
|
||||
self.assertIn("2025-03-03", audit["repaired_zero_oi_dates"])
|
||||
self.assertAlmostEqual(float(tx_px.loc[tx_px["date"] == "2025-03-03", "tx_implied_oi_price"].iloc[0]), 22500.0, places=1)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""
|
||||
[使用工具] Python 3.9, unittest
|
||||
[設計目的] 執行全專案 BDD 場景測試與 Docstring AST Linter 並印出結果摘要
|
||||
[程式說明] 使用 TextTestRunner 執行當前模組所有測試案例並於失敗時回傳非零退出碼
|
||||
[修改日期] 2026-11-20
|
||||
[修改概要] 執行全套BDD情境測試與AST文件檢查器主函式
|
||||
[輸入參數]
|
||||
- 無
|
||||
[輸出結果]
|
||||
- return (None): 以測試成功或失敗決定進程退出狀態
|
||||
[關聯測試] Feature: 台股現貨與期貨資料修復及零和對手方還原 / Scenario: [正例] 正確解析民國日期、去重 3 倍重複位移並以大台隱含指數驗證對齊
|
||||
[工作日誌] work_record_20261120.md
|
||||
"""
|
||||
suite = unittest.defaultTestLoader.loadTestsFromModule(__import__(__name__))
|
||||
runner = unittest.TextTestRunner(verbosity=2)
|
||||
result = runner.run(suite)
|
||||
if not result.wasSuccessful():
|
||||
raise SystemExit(1)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user