Initial public release

This commit is contained in:
kwyvern-gitea
2026-08-12 16:40:47 -07:00
commit e7877e6be2
34 changed files with 7906 additions and 0 deletions
View File
+178
View File
@@ -0,0 +1,178 @@
"""Build data/processed/global_daily_returns.parquet from the EODHD cache.
Reads the latest global universe parquet (from build_global_universe.py),
iterates each ticker's cached `data/raw/eodhd/eod/{ticker}.json`, concatenates
into a long-format daily-returns panel, and persists.
Schema (matches the US data/processed/daily_returns.parquet for compatibility
with existing hygiene detectors at src/data/data_hygiene.py):
date, ticker, open, high, low, close, adjusted_close, volume, ret_d
Reasonable to re-run any time the universe parquet is rebuilt or OHLCV cache
is refreshed via scripts/live/warm_ohlcv_cache.py.
Usage:
.venv/Scripts/python.exe scripts/data/build_global_daily_returns.py
.venv/Scripts/python.exe scripts/data/build_global_daily_returns.py --from 2020-01-01
"""
from __future__ import annotations
import argparse
import json
import logging
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
import pandas as pd
from src.data.hard_excluded_tickers import apply_hard_exclusion_mask
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_daily_returns")
_UNIVERSE_DIR = Path("data/universe")
_CACHE_DIR = Path("data/raw/eodhd/eod")
_OUT_PATH = Path("data/processed/global_daily_returns.parquet")
def _latest_universe_parquet() -> Path:
files = sorted(_UNIVERSE_DIR.glob("global_msci_world_imi_*.parquet"))
if not files:
raise FileNotFoundError(
f"No universe parquet in {_UNIVERSE_DIR} — run build_global_universe.py first"
)
return files[-1]
def _load_one_ticker(ticker: str) -> pd.DataFrame | None:
cache_path = _CACHE_DIR / f"{ticker}.json"
if not cache_path.is_file():
return None
try:
raw = json.loads(cache_path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError) as exc:
logger.warning("Bad cache for %s: %s", ticker, exc)
return None
if not raw:
return None
df = pd.DataFrame(raw)
if df.empty or "date" not in df.columns:
return None
rename = {"adjustedClose": "adjusted_close"}
df = df.rename(columns=rename)
required = {"date", "close", "adjusted_close", "volume"}
missing = required - set(df.columns)
if missing:
logger.warning("%s missing required columns %s — skipping", ticker, missing)
return None
df["date"] = pd.to_datetime(df["date"])
df = df.sort_values("date").reset_index(drop=True)
df["ticker"] = ticker
# Remove manually verified bad-data `(ticker, date)` rows before the code
# calculates `ret_d`.
# This order prevents false returns across two ticker eras for a reused symbol.
# The first retained row from the second era therefore has a NaN `pct_change`.
# For example, see the first GMIN.TO era through 2024-04-04 in
# `src/data/hard_excluded_tickers.py`.
#
# With `bounded_ranges_only=True`, the live path applies only finite
# historical ranges.
# The live path skips permanent, date-bounded, and open-ended exclusions.
# Those exclusions block a current index member when that member reuses an old symbol.
# A finite manual range removes rows only within its start and end dates.
# The backtest path in `src/universe.py` applies the full registry.
excl = apply_hard_exclusion_mask(df, bounded_ranges_only=True)
if excl.any():
df = df[~excl].reset_index(drop=True)
if df.empty:
return None
df["ret_d"] = df["adjusted_close"].pct_change()
# The output uses the standard column order and includes `open`, `high`, and
# `low` when those columns exist in the input.
cols = ["date", "ticker", "open", "high", "low", "close", "adjusted_close", "volume", "ret_d"]
out = df[[c for c in cols if c in df.columns]]
return out
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--from-date", dest="from_date", default=None,
help="Filter rows to date >= from_date (YYYY-MM-DD)")
parser.add_argument("--to-date", dest="to_date", default=None,
help="Filter rows to date <= to_date (YYYY-MM-DD)")
parser.add_argument("--out", default=str(_OUT_PATH),
help=f"Output parquet path (default: {_OUT_PATH})")
args = parser.parse_args()
universe_path = _latest_universe_parquet()
universe = pd.read_parquet(universe_path)
tickers = sorted(universe["eodhd_ticker"].dropna().unique().tolist())
logger.info("Universe %s: %d tickers", universe_path.name, len(tickers))
frames: list[pd.DataFrame] = []
n_loaded = 0
n_missing = 0
start = time.monotonic()
for i, ticker in enumerate(tickers, 1):
df = _load_one_ticker(ticker)
if df is None:
n_missing += 1
continue
frames.append(df)
n_loaded += 1
if i % 500 == 0:
elapsed = time.monotonic() - start
logger.info("[%d/%d] loaded=%d missing=%d (%.1f s)",
i, len(tickers), n_loaded, n_missing, elapsed)
if not frames:
logger.error("No frames loaded — refusing to write empty panel")
sys.exit(1)
logger.info("Concatenating %d frames ...", len(frames))
panel = pd.concat(frames, ignore_index=True)
if args.from_date:
panel = panel[panel["date"] >= args.from_date]
if args.to_date:
panel = panel[panel["date"] <= args.to_date]
out_path = Path(args.out)
out_path.parent.mkdir(parents=True, exist_ok=True)
tmp = out_path.with_suffix(".tmp")
panel.to_parquet(tmp, index=False)
tmp.replace(out_path)
elapsed = time.monotonic() - start
logger.info("=" * 72)
logger.info("Saved %d rows × %d tickers to %s in %.1f s",
len(panel), panel["ticker"].nunique(), out_path, elapsed)
logger.info(
"Date range: %s -> %s | first ret_d: %s | tickers missing from cache: %d",
panel["date"].min().date(), panel["date"].max().date(),
panel["ret_d"].first_valid_index() is not None, n_missing,
)
by_region_top = (
universe.merge(
pd.DataFrame({"eodhd_ticker": panel["ticker"].unique()}),
on="eodhd_ticker",
)
.groupby("region_bucket")
.size()
.sort_index()
)
logger.info("Panel tickers per region: %s", by_region_top.to_dict())
if __name__ == "__main__":
main()
@@ -0,0 +1,110 @@
"""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()
+76
View File
@@ -0,0 +1,76 @@
"""Build data/processed/regional_benchmarks_daily.parquet.
For each gated region, loads the benchmark price series from the EODHD cache
and computes daily returns. The benchmark per region is used downstream as:
- input to Goulding turning-point weight (monthly resampled benchmark returns)
- market series for BAB beta regression (daily benchmark returns)
- market series for CMR residual-momentum (daily benchmark returns)
Output schema (long format):
[date, region, benchmark_symbol, close, ret_d]
Regions and benchmarks (per cross-geography live push plan):
US -> GSPC.INDX (S&P 500)
EU -> SXXP.INDX (STOXX Europe 600)
JP -> N225.INDX (Nikkei 225)
CA -> GSPTSE.INDX (S&P/TSX Composite) -- informational only, not gated
"""
from __future__ import annotations
import logging
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
import pandas as pd
from src.data.eodhd_client import EODHDClient
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_regional_benchmarks")
_REGION_BENCHMARKS = {
"US": "GSPC.INDX",
"EU": "SXXP.INDX",
"JP": "N225.INDX",
"CA": "GSPTSE.INDX",
}
_OUT_PATH = Path("data/processed/regional_benchmarks_daily.parquet")
def main() -> None:
client = EODHDClient()
frames: list[pd.DataFrame] = []
for region, symbol in _REGION_BENCHMARKS.items():
df = client.get_eod_prices(symbol)
if df.empty:
logger.error("No EOD data for %s — aborting", symbol)
sys.exit(1)
df = df.sort_values("date").reset_index(drop=True)
df["region"] = region
df["benchmark_symbol"] = symbol
df["ret_d"] = df["adjusted_close"].pct_change()
out = df[["date", "region", "benchmark_symbol", "adjusted_close", "ret_d"]].rename(
columns={"adjusted_close": "close"}
)
frames.append(out)
logger.info(
"%s (%s): %d rows, %s -> %s",
region, symbol, len(out), out["date"].min().date(), out["date"].max().date(),
)
panel = pd.concat(frames, ignore_index=True)
_OUT_PATH.parent.mkdir(parents=True, exist_ok=True)
tmp = _OUT_PATH.with_suffix(".tmp")
panel.to_parquet(tmp, index=False)
tmp.replace(_OUT_PATH)
logger.info("Saved %d rows -> %s", len(panel), _OUT_PATH)
if __name__ == "__main__":
main()
@@ -0,0 +1,89 @@
"""Live QMJ fundamentals fetch — rebuild-pipeline step (resumable, incremental).
Fetches EODHD fundamentals JSON for every ticker in the live global universe
(the scored cross-section in data/processed/global_daily_returns.parquet) that
is NOT already cached. Becomes step ~3.5 of the signal_long_global rebuild so
each monthly cycle only pays for newly-added names.
Behaviour:
- cache-skip: a name with an existing data/raw/eodhd/fundamentals/{t}.json is skipped.
- 4xx / not-found: an empty-dict sentinel is written so the call is never re-paid.
- transient (429/5xx): left uncached so the next run retries it.
Run: python scripts/data/fetch_live_qmj_fundamentals.py
"""
from __future__ import annotations
import logging
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2])) # Add the repository root so Python imports `src`.
import pandas as pd # noqa: E402
from src.data.eodhd_client import EODHDClient, EODHDError # noqa: E402
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
stream=sys.stderr,
)
logger = logging.getLogger("fetch_live_qmj_fundamentals")
_UNIVERSE_PATH = Path("data/processed/global_daily_returns.parquet")
_CACHE_DIR = Path("data/raw/eodhd/fundamentals")
def _live_universe() -> list[str]:
if not _UNIVERSE_PATH.is_file():
logger.error("Missing %s — run the global rebuild pipeline first.", _UNIVERSE_PATH)
sys.exit(2)
tickers = pd.read_parquet(_UNIVERSE_PATH, columns=["ticker"])["ticker"].astype(str)
return sorted(tickers.unique())
def main() -> None:
universe = _live_universe()
_CACHE_DIR.mkdir(parents=True, exist_ok=True)
to_fetch = [t for t in universe if not (_CACHE_DIR / f"{t}.json").is_file()]
n = len(to_fetch)
logger.info(
"Live QMJ fundamentals: %d universe tickers, %d already cached, %d to fetch (~%d credits)",
len(universe), len(universe) - n, n, n * 10,
)
if n == 0:
logger.info("Nothing to fetch — fundamentals cache is current.")
return
client = EODHDClient()
fetched = empty = errors = 0
for i, ticker in enumerate(to_fetch, 1):
cache_file = _CACHE_DIR / f"{ticker}.json"
try:
data = client.get_fundamentals(ticker, use_cache=True)
if data:
fetched += 1
else:
empty += 1
except EODHDError as exc:
if exc.status_code is not None and 400 <= exc.status_code < 500:
cache_file.write_text("{}", encoding="utf-8") # Store an empty-response sentinel for an HTTP 4xx error.
empty += 1
else:
errors += 1
logger.warning("Transient error for %s: %s (will retry next run)", ticker, exc)
if i % 100 == 0:
logger.info("progress %d/%d fetched=%d empty=%d err=%d", i, n, fetched, empty, errors)
logger.info(
"DONE %d tickers: fetched=%d empty/sentinel=%d errors=%d",
n, fetched, empty, errors,
)
if __name__ == "__main__":
main()
+55
View File
@@ -0,0 +1,55 @@
"""Force-refresh per-exchange EODHD symbol-list cache.
The TickerResolver and USD-returns builder both read from
``data/raw/eodhd/symbols/{EX}_active.json`` to map (a) BR tickers -> EODHD
codes and (b) tickers -> trading currency. ``EODHDClient.get_exchange_symbols``
uses ``use_cache=True`` in every production call site, which means once those
JSONs are on disk they are NEVER refetched — a new index constituent (IPO,
listing change) that postdates the cache silently drops out of the universe
and/or the USD panel.
This script bypasses the cache and refetches every gated exchange. Cheap:
19 exchanges × 1 API call each, ~10 s wall-clock and a trivial quota hit.
Invoked as step 1/9 of the monthly orchestrator so the cache is always
current at signal time.
Output: ``data/raw/eodhd/symbols/{EX}_active.json`` (overwritten in place).
"""
from __future__ import annotations
import logging
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent)) # noqa: E402
from src.data import GATED_EXCHANGES
from src.data.eodhd_client import EODHDClient, EODHDError
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s — %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S",
)
logger = logging.getLogger("refresh_symbol_cache")
def main() -> None:
client = EODHDClient()
total = 0
for ex in GATED_EXCHANGES:
try:
df = client.get_exchange_symbols(ex, delisted=False, use_cache=False)
except EODHDError as exc:
logger.error("Refresh failed for %s: %s", ex, exc)
sys.exit(1)
n = len(df)
total += n
logger.info("Refreshed %s: %d symbols", ex, n)
logger.info(
"Refreshed %d exchanges, %d total symbol rows", len(GATED_EXCHANGES), total
)
if __name__ == "__main__":
main()
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python
"""Build the configured global-equity universe from BlackRock holdings.
Usage:
python scripts/live/build_global_universe.py
python scripts/live/build_global_universe.py --use-cached # skip live BlackRock fetch
"""
import argparse
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2])) # noqa: E402
from src.data.global_universe import build_global_universe
def main() -> None:
parser = argparse.ArgumentParser(
description="Build the configured global-equity universe from BlackRock holdings."
)
parser.add_argument(
"--use-cached",
action="store_true",
help="Use cached BlackRock fixtures instead of live fetch",
)
args = parser.parse_args()
build_global_universe(use_cached_fixtures=args.use_cached)
if __name__ == "__main__":
main()
+153
View File
@@ -0,0 +1,153 @@
"""Pre-warm EODHD OHLCV cache for every ticker in the latest global universe.
Run once per monthly cycle (or whenever the universe parquet is rebuilt) to
ensure the signal-generation pipeline reads from cache exclusively (no live
fetches during scoring). Tickers already cached are skipped.
Usage:
python scripts/live/warm_ohlcv_cache.py # actually fetch
python scripts/live/warm_ohlcv_cache.py --dry-run # show scope, don't fetch
python scripts/live/warm_ohlcv_cache.py --extend-to-today
"""
from __future__ import annotations
import argparse
import logging
import sys
import time
from datetime import date
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
import pandas as pd
from src.data.eodhd_client import EODHDClient, EODHDError
logger = logging.getLogger(__name__)
def _latest_universe_parquet(universe_dir: Path) -> Path:
files = sorted(universe_dir.glob("global_msci_world_imi_*.parquet"))
if not files:
raise FileNotFoundError(
f"No universe parquet in {universe_dir} — run build_global_universe.py first"
)
return files[-1]
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--dry-run", action="store_true",
help="Report what would be fetched without making any API calls",
)
parser.add_argument(
"--extend-to-today", action="store_true",
help="Force re-fetch for cached tickers whose cache max-date is before today",
)
parser.add_argument(
"--max-tickers", type=int, default=None,
help="Stop after N tickers (testing/throttling)",
)
parser.add_argument(
"--universe-dir", default="data/universe",
help="Directory containing global_msci_world_imi_*.parquet (default: data/universe)",
)
args = parser.parse_args()
logging.basicConfig(level=logging.WARNING, format="%(asctime)s %(levelname)s %(message)s")
universe_path = _latest_universe_parquet(Path(args.universe_dir))
universe = pd.read_parquet(universe_path)
tickers = sorted(universe["eodhd_ticker"].dropna().unique().tolist())
cache_dir = Path("data/raw/eodhd/eod")
cached = {p.stem for p in cache_dir.glob("*.json")} if cache_dir.is_dir() else set()
to_fetch = [t for t in tickers if t not in cached]
today_iso = date.today().isoformat()
print("=" * 80)
print(f"OHLCV cache warmer — {today_iso}")
print("=" * 80)
print(f"Universe parquet: {universe_path.name}")
print(f"Universe size: {len(tickers):,}")
print(f"Already cached: {len(cached & set(tickers)):,}")
print(f"To fetch: {len(to_fetch):,}")
if args.extend_to_today:
print(f"Extend-to-today: enabled (cached tickers will refresh to {today_iso})")
if args.max_tickers is not None:
print(f"Max tickers cap: {args.max_tickers:,}")
to_fetch = to_fetch[: args.max_tickers]
estimated_minutes = len(to_fetch) / 15 / 60
print(f"Estimated runtime (at ~15/sec rate limit): {estimated_minutes:.1f} min")
print(f"API quota cost: ~{len(to_fetch):,} calls "
f"({len(to_fetch) / 1000:.1f}% of 100k monthly quota)")
if args.dry_run:
print("\n[DRY RUN] — exiting without fetching")
return
if not to_fetch and not args.extend_to_today:
print("\nNothing to do — cache is up to date.")
return
client = EODHDClient()
n_ok = 0
n_fail = 0
failed: list[tuple[str, str]] = []
start = time.monotonic()
# This loop fetches data for new tickers.
for i, ticker in enumerate(to_fetch, 1):
try:
df = client.get_eod_prices(ticker)
if len(df) == 0:
logger.warning("Empty EOD for %s — kept cache slot but no data", ticker)
n_ok += 1
except EODHDError as exc:
n_fail += 1
failed.append((ticker, f"{exc.status_code} {exc.reason[:60]}"))
logger.warning("Failed %s: %s", ticker, exc)
if i % 100 == 0:
elapsed = time.monotonic() - start
rate = i / elapsed
eta = (len(to_fetch) - i) / rate / 60
print(f" [{i:>5}/{len(to_fetch):>5}] {rate:.1f}/sec ETA {eta:.1f} min")
# This loop refreshes cached tickers through today's date.
n_extended = 0
if args.extend_to_today:
already = sorted(cached & set(tickers))
if args.max_tickers is not None:
already = already[: args.max_tickers]
print(f"\nExtending {len(already):,} cached tickers to {today_iso} ...")
for i, ticker in enumerate(already, 1):
try:
client.get_eod_prices(ticker, extend_cache_to=today_iso)
n_extended += 1
except EODHDError as exc:
n_fail += 1
failed.append((ticker, f"extend: {exc.status_code} {exc.reason[:60]}"))
if i % 200 == 0:
print(f" [{i:>5}/{len(already):>5}] extended")
total_elapsed = time.monotonic() - start
print()
print(f"Done in {total_elapsed/60:.1f} min")
print(f" Newly fetched: {n_ok:,}")
print(f" Extended: {n_extended:,}")
print(f" Failed: {n_fail:,}")
if failed:
print("\nFirst 20 failures:")
for t, reason in failed[:20]:
print(f" {t:<15} {reason}")
# Save the complete failure list for review.
fail_path = Path("data/universe") / f"ohlcv_fetch_failures_{date.today().strftime('%Y%m%d')}.csv"
pd.DataFrame(failed, columns=["eodhd_ticker", "failure_reason"]).to_csv(fail_path, index=False)
print(f"Full failure list: {fail_path}")
if __name__ == "__main__":
main()
+132
View File
@@ -0,0 +1,132 @@
"""Create the global live stock-selection signal."""
from __future__ import annotations
import argparse
import subprocess
import sys
import time
from pathlib import Path
_PROJECT_ROOT = Path(__file__).resolve().parents[2]
if str(_PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(_PROJECT_ROOT))
import pandas as pd # noqa: E402
from src.signals.multi_region_orchestrator import run_multi_region_signal # noqa: E402
_OUTPUT_DIR = _PROJECT_ROOT / "data" / "signal"
_REBUILD_PIPELINE: tuple[tuple[str, tuple[str, ...]], ...] = (
("1/7 Refresh EODHD symbol lists", ("scripts/data/refresh_symbol_cache.py",)),
("2/7 Rebuild the configured equity universe", ("scripts/live/build_global_universe.py",)),
(
"3/7 Warm the OHLCV cache",
("scripts/live/warm_ohlcv_cache.py", "--extend-to-today"),
),
("4/7 Build local-currency returns", ("scripts/data/build_global_daily_returns.py",)),
(
"5/7 Fetch QMJ fundamentals",
("scripts/data/fetch_live_qmj_fundamentals.py",),
),
("6/7 Build regional benchmarks", ("scripts/data/build_regional_benchmarks.py",)),
(
"7/7 Build the data-hygiene table",
("scripts/data/build_global_exclusion_table.py",),
),
)
def _last_weekday() -> pd.Timestamp:
decision_date = pd.Timestamp.today().normalize()
while decision_date.weekday() >= 5:
decision_date -= pd.Timedelta(days=1)
return decision_date
def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--date", metavar="YYYY-MM-DD", help="Decision date")
parser.add_argument("--quota", type=int, default=25, metavar="N")
parser.add_argument("--workers", type=int, default=8, metavar="N")
parser.add_argument(
"--use-cached",
action="store_true",
help="Reuse existing panels instead of rebuilding data",
)
parser.add_argument(
"--veto",
choices=("bab", "qmj"),
default="qmj",
help="Select the QMJ live veto or BAB diagnostic veto",
)
return parser.parse_args()
def _run_rebuild_pipeline() -> None:
pipeline_started = time.monotonic()
for label, script_arguments in _REBUILD_PIPELINE:
step_started = time.monotonic()
print(label)
command = [sys.executable, *script_arguments]
try:
subprocess.run(command, cwd=_PROJECT_ROOT, check=True)
except subprocess.CalledProcessError as exc:
raise SystemExit(
f"The rebuild stopped at {label!r} with exit code {exc.returncode}."
) from exc
print(f"Completed in {time.monotonic() - step_started:.1f} seconds")
print(f"Rebuild completed in {(time.monotonic() - pipeline_started) / 60.0:.1f} minutes")
def _add_target_weights(csv_path: Path, picks: pd.DataFrame) -> None:
"""Add the public target-weight contract to the generated signal CSV."""
required_columns = {"position_pct_tc", "region", "traded_flag"}
missing_columns = required_columns - set(picks.columns)
if missing_columns:
raise ValueError(f"Signal output is missing required columns: {sorted(missing_columns)}")
public_signal = pd.read_csv(csv_path)
if len(public_signal) != len(picks):
raise ValueError("Signal CSV and target-weight rows have different lengths")
traded = picks["traded_flag"].astype(bool)
regional_weights = picks.loc[traded, "position_pct_tc"].astype(float)
regional_totals = regional_weights.groupby(picks.loc[traded, "region"]).transform("sum")
if regional_totals.isna().any() or (regional_totals <= 0.0).any():
raise ValueError("Each traded region must have a positive target-weight total")
target_weights = pd.Series(0.0, index=picks.index)
target_weights.loc[traded] = regional_weights / regional_totals
public_signal["target_weight"] = target_weights.to_numpy(dtype=float)
public_signal.to_csv(csv_path, index=False)
def main() -> None:
"""Build data when required, then create the global signal."""
args = _parse_args()
if not args.use_cached:
_run_rebuild_pipeline()
decision_date = pd.Timestamp(args.date) if args.date else _last_weekday()
picks = run_multi_region_signal(
decision_date=decision_date,
per_region_quota=args.quota,
output_dir=_OUTPUT_DIR,
n_workers=args.workers,
veto=args.veto,
apply_gate=False,
)
csv_path = _OUTPUT_DIR / f"signal_long_global_{decision_date:%Y%m%d}.csv"
_add_target_weights(csv_path, picks)
counts = picks["region"].value_counts().to_dict()
print(f"Saved {len(picks)} picks to {csv_path}")
print(
f"US: {counts.get('US', 0)} EU: {counts.get('EU', 0)} "
f"JP: {counts.get('JP', 0)} CA: {counts.get('CA', 0)}"
)
if __name__ == "__main__":
main()