File size: 10,561 Bytes
5aa9aa2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#!/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())