#!/usr/bin/env python3 """Fetch latest two Quartr earnings-call transcript bundles for each company.""" from __future__ import annotations import argparse import json import os import re import sys import time from collections import defaultdict from datetime import datetime, timezone from pathlib import Path from typing import Any import requests def load_config(path: Path) -> dict[str, Any]: return json.loads(path.read_text()) def load_jsonl(path: Path) -> list[dict[str, Any]]: rows: list[dict[str, Any]] = [] with path.open("r", encoding="utf-8") as handle: for line in handle: line = line.strip() if line: rows.append(json.loads(line)) return rows class QuartrClient: def __init__(self, config: dict[str, Any]) -> None: self.base_url = config["quartr"]["base_url"].rstrip("/") self.timeout = int(config["quartr"]["timeout_seconds"]) self.max_retries = int(config["quartr"]["max_retries"]) self.pause = float(config["quartr"]["request_pause_seconds"]) self.session = requests.Session() api_key = os.getenv("QUARTR_API_KEY", "").strip() if not api_key: raise RuntimeError("QUARTR_API_KEY is required because it is a secret API credential.") self.session.headers.update({"x-api-key": api_key, "Accept": "application/json"}) def get(self, path: str, params: dict[str, Any]) -> dict[str, Any]: for attempt in range(1, self.max_retries + 1): try: response = self.session.get(f"{self.base_url}/{path}", params=params, timeout=self.timeout) response.raise_for_status() time.sleep(self.pause) payload = response.json() break except requests.RequestException: if attempt == self.max_retries: raise time.sleep(attempt * 2) if not isinstance(payload, dict): raise RuntimeError(f"Unexpected response for {path}: {type(payload)!r}") return payload def download_json(self, url: str) -> dict[str, Any] | None: for attempt in range(1, self.max_retries + 1): try: response = self.session.get(url, timeout=self.timeout) response.raise_for_status() time.sleep(self.pause) try: payload = response.json() except json.JSONDecodeError: return None break except requests.RequestException: if attempt == self.max_retries: raise time.sleep(attempt * 2) return payload if isinstance(payload, dict) else None def is_past_event(event: dict[str, Any]) -> bool: raw = event.get("date") if not isinstance(raw, str) or not raw.strip(): return True try: parsed = datetime.fromisoformat(raw.replace("Z", "+00:00")) except ValueError: return True return parsed <= datetime.now(timezone.utc) def slug_tokens(company_name: str) -> list[str]: stopwords = { "inc", "incorporated", "corp", "corporation", "company", "co", "plc", "limited", "ltd", "class", "the", } tokens = re_split_tokens(company_name) return [token for token in tokens if token not in stopwords] def re_split_tokens(value: str) -> list[str]: return [token for token in re_split_non_alnum(value.lower()) if token] def re_split_non_alnum(value: str) -> list[str]: return re.split(r"[^a-z0-9]+", value) def event_matches_company(event: dict[str, Any], company: dict[str, Any]) -> bool: backlink = str(event.get("backlinkUrl") or "").lower() tokens = slug_tokens(str(company.get("company_name") or "")) distinctive = [token for token in tokens if len(token) >= 3] or tokens[:1] return bool(distinctive) and any(token in backlink for token in distinctive) def fetch_events(client: QuartrClient, company: dict[str, Any], event_type_ids: list[int], limit: int) -> list[dict[str, Any]]: ticker = str(company["ticker"]).upper() payload = client.get( "events", { "tickers": ticker.upper(), "typeIds": ",".join(str(value) for value in event_type_ids), "limit": str(limit), "sortBy": "date", "direction": "desc", }, ) rows = payload.get("data") or [] return [ row for row in rows if isinstance(row, dict) and is_past_event(row) and event_matches_company(row, company) ] def fetch_transcript_meta(client: QuartrClient, event_id: int) -> dict[str, Any] | None: payload = client.get( "documents/transcripts", {"eventIds": str(event_id), "limit": "1", "direction": "desc"}, ) rows = payload.get("data") or [] for row in rows: if isinstance(row, dict) and row.get("fileUrl"): return row return None def extract_text(payload: dict[str, Any] | None) -> str | None: if not payload: return None transcript = payload.get("transcript") if isinstance(transcript, dict): text = transcript.get("text") if isinstance(text, str) and text.strip(): return text.strip() paragraphs = transcript.get("paragraphs") or transcript.get("segments") or [] if isinstance(paragraphs, list): parts = [] for paragraph in paragraphs: if not isinstance(paragraph, dict): continue speaker = paragraph.get("speaker") or paragraph.get("speakerName") raw = paragraph.get("text") or paragraph.get("body") if isinstance(raw, str) and raw.strip(): prefix = f"{speaker}: " if isinstance(speaker, str) and speaker.strip() else "" parts.append(prefix + raw.strip()) if parts: return "\n".join(parts) text = payload.get("text") if isinstance(text, str) and text.strip(): return text.strip() return None def build_bundle( ticker: str, company: dict[str, Any], event: dict[str, Any], transcript_meta: dict[str, Any], payload: dict[str, Any] | None, ) -> dict[str, Any]: return { "ticker": ticker.upper(), "company": { "name": company.get("company_name"), "gics_sector": company.get("gics_sector"), "gics_sub_industry": company.get("gics_sub_industry"), }, "event": { "id": event.get("id"), "title": event.get("title"), "date": event.get("date"), "fiscal_year": event.get("fiscalYear"), "fiscal_period": event.get("fiscalPeriod"), "type_id": event.get("typeId"), "company_id": event.get("companyId"), "backlink_url": event.get("backlinkUrl"), }, "transcript": { "document_id": transcript_meta.get("id"), "file_url": transcript_meta.get("fileUrl"), "text": extract_text(payload), }, } def append_jsonl(path: Path, row: dict[str, Any]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("a", encoding="utf-8") as handle: handle.write(json.dumps(row, ensure_ascii=True) + "\n") def iter_bundles( config: dict[str, Any], universe_rows: list[dict[str, Any]], max_companies: int | None, output_path: Path | None = None, ) -> list[dict[str, Any]]: client = QuartrClient(config) event_type_ids = config["scope"]["event_type_ids"] events_per_company = int(config["scope"]["events_per_company"]) rows: list[dict[str, Any]] = load_jsonl(output_path) if output_path and output_path.exists() else [] existing_counts: dict[str, int] = defaultdict(int) for row in rows: existing_counts[str(row.get("ticker") or "").upper()] += 1 selected = universe_rows[:max_companies] if max_companies else universe_rows for index, company in enumerate(selected, start=1): ticker = str(company["ticker"]).upper() if existing_counts[ticker] >= events_per_company: print(f"[{index}/{len(selected)}] {ticker} already complete", file=sys.stderr) continue print(f"[{index}/{len(selected)}] {ticker}", file=sys.stderr) events = fetch_events(client, company, event_type_ids, max(events_per_company + 6, 8)) kept = 0 for event in events: event_id = event.get("id") if not isinstance(event_id, int): continue transcript_meta = fetch_transcript_meta(client, event_id) if not transcript_meta: continue payload = client.download_json(str(transcript_meta["fileUrl"])) bundle = build_bundle(ticker, company, event, transcript_meta, payload) if bundle["transcript"]["text"]: rows.append(bundle) existing_counts[ticker] += 1 if output_path: append_jsonl(output_path, bundle) kept += 1 if kept >= events_per_company: break return rows def write_jsonl(path: Path, rows: list[dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as handle: for row in rows: handle.write(json.dumps(row, ensure_ascii=True) + "\n") def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser() parser.add_argument("--config", default="config/dataset.json") parser.add_argument("--universe", default=None) parser.add_argument("--output", default=None) parser.add_argument("--max-companies", type=int, default=None) return parser.parse_args() def main() -> int: args = parse_args() config = load_config(Path(args.config)) universe_path = Path(args.universe or config["outputs"]["universe_file"]) output = Path(args.output or config["outputs"]["raw_transcript_bundle"]) if output.exists(): print(f"Resuming from existing {output}", file=sys.stderr) rows = iter_bundles(config, load_jsonl(universe_path), args.max_companies, output) if not output.exists(): write_jsonl(output, rows) print(f"Wrote {len(rows)} transcript bundles to {output}") return 0 if __name__ == "__main__": sys.exit(main())