"""Generate data/processed/global_excluded_ticker_dates.parquet. Runs the same three data-hygiene detectors as scripts/data/build_exclusion_table.py (US) but against the global daily-returns panel built by scripts/data/build_global_daily_returns.py. Detectors (parameters mirror US build for consistency; threshold sensitivity for non-US regimes — particularly Japan low-vol — may warrant review later): - detect_frozen_runs (min_length=5) - detect_combined_evidence_corruption (Tier 1) - detect_round_trip_spikes (Tier 2; up_threshold=5.0, down_threshold=-0.90, recovery_calendar_days=10) Output: data/processed/global_excluded_ticker_dates.parquet """ from __future__ import annotations import logging import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent.parent)) # noqa: E402 import pandas as pd from src.data.data_hygiene import ( # noqa: E402 detect_combined_evidence_corruption, detect_frozen_runs, detect_round_trip_spikes, save_exclusion_ranges, ) logging.basicConfig( level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s — %(message)s", datefmt="%Y-%m-%dT%H:%M:%S", ) logger = logging.getLogger("build_global_exclusion_table") _DAILY_PATH = Path("data/processed/global_daily_returns.parquet") _OUT_PATH = Path("data/processed/global_excluded_ticker_dates.parquet") # The detector window covers backtest and live dates from 2000 onward. # Momentum signals use pre-2000 data only for the warmup period. _FROM_DATE = "2000-01-01" _TO_DATE = pd.Timestamp.today().strftime("%Y-%m-%d") def main() -> None: logger.info("Loading %s ...", _DAILY_PATH) daily = pd.read_parquet( _DAILY_PATH, columns=["date", "ticker", "close", "adjusted_close", "volume", "ret_d"], ) daily["date"] = pd.to_datetime(daily["date"]) pre_window = len(daily) daily = daily[(daily["date"] >= _FROM_DATE) & (daily["date"] <= _TO_DATE)] logger.info( "Window %s..%s: %d rows (%d filtered out), %d tickers", _FROM_DATE, _TO_DATE, len(daily), pre_window - len(daily), daily["ticker"].nunique(), ) all_ranges: list[pd.DataFrame] = [] logger.info("Running detect_frozen_runs (min_length=5) ...") frozen = detect_frozen_runs(daily, min_length=5) all_ranges.append(frozen) logger.info(" -> %d frozen-run ranges", len(frozen)) logger.info("Running detect_combined_evidence_corruption (Tier 1) ...") combined = detect_combined_evidence_corruption(daily, frozen_runs=frozen) all_ranges.append(combined[["ticker", "start_date", "end_date", "reason"]]) logger.info(" -> %d combined-evidence ranges", len(combined)) logger.info("Running detect_round_trip_spikes (Tier 2) ...") round_trips = detect_round_trip_spikes( daily, up_threshold=5.0, down_threshold=-0.90, recovery_calendar_days=10, ) all_ranges.append(round_trips) logger.info(" -> %d round-trip-spike ranges", len(round_trips)) out = pd.concat(all_ranges, ignore_index=True) out["start_date"] = pd.to_datetime(out["start_date"]) out["end_date"] = pd.to_datetime(out["end_date"]) out = out.sort_values(["ticker", "start_date"]).reset_index(drop=True) logger.info("=" * 72) logger.info("Combined exclusion table: %d ranges across %d unique tickers", len(out), out["ticker"].nunique()) logger.info("By reason: %s", out["reason"].value_counts().to_dict()) # Join the latest universe table to summarize exclusion ranges by region. universe_files = sorted(Path("data/universe").glob("global_msci_world_imi_*.parquet")) if universe_files: universe = pd.read_parquet(universe_files[-1], columns=["eodhd_ticker", "region_bucket"]) out_with_region = out.merge( universe, left_on="ticker", right_on="eodhd_ticker", how="left", ) by_region = ( out_with_region.groupby("region_bucket").size().sort_index().to_dict() ) logger.info("Exclusion ranges by region: %s", by_region) save_exclusion_ranges(out, _OUT_PATH) logger.info("Saved global exclusion table -> %s", _OUT_PATH) if __name__ == "__main__": main()