90 lines
3.0 KiB
Python
90 lines
3.0 KiB
Python
"""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()
|