Initial public release
This commit is contained in:
@@ -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()
|
||||
Reference in New Issue
Block a user