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()
|
||||
Reference in New Issue
Block a user