| 1 | """Share-price window for a listed company, through ``yahoo-finance-pp-cli``. |
| 2 | |
| 3 | Not a search source: it returns no items and the planner never schedules it. |
| 4 | For a topic the company resolver tied to a listed company it fetches the daily |
| 5 | closes of the research window once and stores the numbers as the report's |
| 6 | ``yahoo_finance`` artifact, which the footer and the evidence block read. |
| 7 | |
| 8 | Activation gate: the ``yahoo-finance-pp-cli`` binary on PATH and a company |
| 9 | with a ticker. Without either, nothing happens and nothing is logged. |
| 10 | ``EXCLUDE_SOURCES=yahoo_finance`` switches it off the same way. ``--search`` |
| 11 | picks search sources and this is not one, so it does not switch it off. |
| 12 | |
| 13 | Which symbol is charted: |
| 14 | |
| 15 | - The resolver's certain ``ticker`` on a US exchange is used as it is. |
| 16 | - A certain ``ticker`` on any other exchange has a different Yahoo symbol |
| 17 | (Tokyo ``7203`` is ``7203.T``), so ``autocomplete`` is asked for the company |
| 18 | name and the first equity whose symbol is the ticker, or the ticker followed |
| 19 | by ``.`` and an exchange suffix, is used. |
| 20 | - With only ``ticker_candidates``, the first equity ``autocomplete`` returns |
| 21 | for the company name is used when its symbol, or the part of it before the |
| 22 | first ``.``, is one of the candidates. Only that first equity is looked at. |
| 23 | |
| 24 | All comparisons ignore case. ``autocomplete`` only ever confirms a symbol the |
| 25 | resolver supplied: on its own it returned a fund for "Stripe" and a Swedish |
| 26 | retailer for "Rust". A symbol that cannot be confirmed gives no line. |
| 27 | |
| 28 | The one exception is ``backup_company``, for a topic whose Wikidata lookup |
| 29 | failed (not one Wikidata answered with nothing). ``autocomplete`` is asked for |
| 30 | the topic itself and only its first equity is looked at. It is taken when its |
| 31 | symbol has no exchange suffix and its name is the topic once case, punctuation |
| 32 | and trailing corporate designators ("Tesla, Inc.", "NVIDIA Corporation") are |
| 33 | set aside. That result carries ``company_source`` of ``yahoo-backup`` and its |
| 34 | ticker is charted as it is. |
| 35 | |
| 36 | The host's ticker: ``--ticker "SYMBOL:Company"`` carries what the hosting |
| 37 | model found by web search, and then the resolver's ticker is not used at all. |
| 38 | A host claim is never taken alone. Yahoo has to agree twice: ``chart`` for the |
| 39 | symbol returns an equity with two daily closes (the same fetch the line is |
| 40 | built from), and the first equity ``autocomplete`` lists for the company name |
| 41 | is that symbol, or carries the same company name as the chart does ("GOOGL" |
| 42 | when "Alphabet" lists "GOOG" first). A pair that fails gives no line and no |
| 43 | other source is tried in its place: see ``attach_host_tickers``. |
| 44 | |
| 45 | Surface choice: ``--json``, never ``--agent``. ``--agent`` implies |
| 46 | ``--compact``, which empties records on older Printing Press binaries (see |
| 47 | ``lib/techmeme.py``). |
| 48 | |
| 49 | Window: bars are requested from a day before ``range_from`` to a day after |
| 50 | ``range_to`` and then kept by the exchange's own calendar date, so a market |
| 51 | that opens before midnight UTC keeps its first day. The window's first close |
| 52 | is the first trading day inside it and its last close is the last one. Daily |
| 53 | moves are close to close between consecutive bars inside the window. |
| 54 | |
| 55 | A fetch that fails, is rate limited, or returns fewer than two closes records |
| 56 | a degraded ``yahoo_finance`` source outcome and no artifact. So does an |
| 57 | ``autocomplete`` call that fails or answers in another shape: that is not the |
| 58 | same as Yahoo listing no matching equity, which records nothing. Nothing |
| 59 | raises. |
| 60 | """ |
| 61 | |
| 62 | from __future__ import annotations |
| 63 | |
| 64 | import json |
| 65 | import re |
| 66 | import shutil |
| 67 | import threading |
| 68 | from concurrent.futures import Future |
| 69 | from datetime import date, datetime, timedelta, timezone |
| 70 | from typing import Any |
| 71 | |
| 72 | from . import env, health, http, log, schema, subproc |
| 73 | |
| 74 | CLI_BIN = "yahoo-finance-pp-cli" |
| 75 | SOURCE = "yahoo_finance" |
| 76 | TIMEOUT_SECONDS = 20 |
| 77 | |
| 78 | BENCHMARK_SYMBOL = "^GSPC" |
| 79 | BENCHMARK_NAME = "S&P 500" |
| 80 | TOP_MOVES = 3 |
| 81 | |
| 82 | # Exchange labels the company resolver returns for US listings, case-folded. |
| 83 | _US_EXCHANGES = frozenset({ |
| 84 | "nasdaq", "new york stock exchange", "nyse american", "nyse arca", |
| 85 | }) |
| 86 | |
| 87 | # ``company_source`` of a company found by ``backup_company``. |
| 88 | BACKUP_SOURCE = "yahoo-backup" |
| 89 | |
| 90 | # ``ticker_source`` of a ticker the host passed with ``--ticker``. |
| 91 | HOST_SOURCE = "host" |
| 92 | MAX_HOST_TICKERS = 2 |
| 93 | # The symbol becomes a CLI argument, so it has to look like one: a letter or |
| 94 | # digit first, never a dash. |
| 95 | _HOST_SYMBOL = re.compile(r"[A-Z0-9][A-Z0-9.\-]{0,14}\Z") |
| 96 | _HOST_TEXT_LIMIT = 80 |
| 97 | |
| 98 | # Words dropped from the end of a company name before it is compared with the |
| 99 | # topic. "publ" is what is left of "AB (publ)" and "the" of ", The". |
| 100 | _DESIGNATORS = frozenset({ |
| 101 | "inc", "incorporated", "corp", "corporation", "co", "company", "ltd", |
| 102 | "limited", "plc", "ag", "sa", "nv", "ab", "publ", "se", "holdings", |
| 103 | "holding", "group", "the", |
| 104 | }) |
| 105 | _SHARE_CLASSES = frozenset({"a", "b", "c"}) |
| 106 | |
| 107 | # One fetch per symbol and window for the life of the process: the entities of |
| 108 | # a comparison run on threads and each asks for the same S&P 500 window. The |
| 109 | # lock guards the dict only. The thread that adds a key runs the CLI outside |
| 110 | # the lock and the others wait on that key's future, so different symbols are |
| 111 | # fetched at the same time. |
| 112 | _fetch_lock = threading.Lock() |
| 113 | _fetched: dict[tuple[str, str, str], Future] = {} |
| 114 | |
| 115 | |
| 116 | class SymbolSearchFailed(Exception): |
| 117 | """``autocomplete`` gave no usable answer, so the symbol is unknown.""" |
| 118 | |
| 119 | |
| 120 | def _log(msg: str) -> None: |
| 121 | log.source_log("Yahoo Finance", msg, tty_only=False) |
| 122 | |
| 123 | |
| 124 | def _is_available() -> bool: |
| 125 | """True when the yahoo-finance-pp-cli binary is on PATH.""" |
| 126 | return shutil.which(CLI_BIN) is not None |
| 127 | |
| 128 | |
| 129 | def forget_fetches() -> None: |
| 130 | """Drop the fetched windows, so the next request reaches the CLI again.""" |
| 131 | with _fetch_lock: |
| 132 | _fetched.clear() |
| 133 | |
| 134 | |
| 135 | def _run_cli(args: list[str]) -> dict[str, Any]: |
| 136 | """Run the CLI and return ``{"data": parsed}`` or ``{"error": text}``.""" |
| 137 | cmd = [CLI_BIN, *args, "--json"] |
| 138 | try: |
| 139 | result = subproc.run_with_timeout(cmd, timeout=TIMEOUT_SECONDS) |
| 140 | except (subproc.SubprocTimeout, OSError) as exc: |
| 141 | return {"error": f"{type(exc).__name__}: {exc}"} |
| 142 | if result.returncode != 0: |
| 143 | lines = (result.stderr or result.stdout or "").strip().splitlines() |
| 144 | return {"error": lines[0] if lines else f"exit {result.returncode}"} |
| 145 | stdout = (result.stdout or "").strip() |
| 146 | if not stdout: |
| 147 | return {"error": "empty output"} |
| 148 | try: |
| 149 | return {"data": json.loads(stdout)} |
| 150 | except json.JSONDecodeError as exc: |
| 151 | return {"error": f"json decode: {exc}"} |
| 152 | |
| 153 | |
| 154 | def _equities(query: str) -> list[tuple[str, str]]: |
| 155 | """The ``(symbol, name)`` of each equity ``autocomplete`` lists for the |
| 156 | query, in its order. Raises ``SymbolSearchFailed`` when the call failed or |
| 157 | its answer could not be read.""" |
| 158 | response = _run_cli(["autocomplete", "--query", query]) |
| 159 | if "error" in response: |
| 160 | raise SymbolSearchFailed(f"symbol search for {query!r} failed: {response['error']}") |
| 161 | try: |
| 162 | rows = response["data"]["results"]["ResultSet"]["Result"] |
| 163 | if not isinstance(rows, list): |
| 164 | raise TypeError(f"Result is {type(rows).__name__}, not a list") |
| 165 | return [ |
| 166 | (str(row.get("symbol") or "").strip(), str(row.get("name") or "")) |
| 167 | for row in rows |
| 168 | if str(row.get("typeDisp") or "").casefold() == "equity" |
| 169 | ] |
| 170 | except (AttributeError, KeyError, TypeError) as exc: |
| 171 | raise SymbolSearchFailed( |
| 172 | f"symbol search for {query!r}: schema: unexpected autocomplete response ({exc!r})" |
| 173 | ) from exc |
| 174 | |
| 175 | |
| 176 | def _first_equity(company: str, accept) -> str | None: |
| 177 | """The first equity ``autocomplete`` lists for the company that ``accept`` |
| 178 | takes, or None when it lists none. ``accept`` gets the symbol in upper |
| 179 | case. Raises ``SymbolSearchFailed`` when the call failed or its answer |
| 180 | could not be read.""" |
| 181 | for symbol, _name in _equities(company): |
| 182 | if accept(symbol.upper()): |
| 183 | return symbol |
| 184 | return None |
| 185 | |
| 186 | |
| 187 | def _name_key(name: str) -> str: |
| 188 | """A company name for comparison: case-folded, without punctuation, and |
| 189 | without the corporate designators and share class at its end. The last |
| 190 | word left is never dropped.""" |
| 191 | text = re.sub(r"[.'\u2019]", "", name.casefold()) |
| 192 | words = re.sub(r"[^\w\s]|_", " ", text).split() |
| 193 | while len(words) > 1: |
| 194 | if len(words) > 2 and words[-2] == "class" and words[-1] in _SHARE_CLASSES: |
| 195 | del words[-2:] |
| 196 | elif words[-1] in _DESIGNATORS: |
| 197 | del words[-1] |
| 198 | else: |
| 199 | break |
| 200 | return " ".join(words) |
| 201 | |
| 202 | |
| 203 | def _same_company_name(topic: str, name: str) -> bool: |
| 204 | key = _name_key(name) |
| 205 | return bool(key) and key == _name_key(topic) |
| 206 | |
| 207 | |
| 208 | def backup_company(topic: str, config: dict[str, Any] | None = None) -> dict[str, Any] | None: |
| 209 | """The company a topic names, from Yahoo's symbol search alone. For a |
| 210 | topic whose Wikidata lookup failed; the caller decides that. |
| 211 | |
| 212 | None when the search was not run (``EXCLUDE_SOURCES`` names this source, |
| 213 | or the binary is absent). ``{}`` when it ran and gave no certain match, |
| 214 | which includes a search that failed. Otherwise ``company`` (the topic as |
| 215 | typed), ``ticker`` and ``company_source``. Never raises. |
| 216 | """ |
| 217 | if is_excluded(config) or not _is_available(): |
| 218 | return None |
| 219 | topic = " ".join(topic.split()) |
| 220 | try: |
| 221 | equities = _equities(topic) |
| 222 | except SymbolSearchFailed as exc: |
| 223 | _log(f"backup {exc}") |
| 224 | return {} |
| 225 | except Exception as exc: |
| 226 | _log(f"backup symbol search for {topic!r} failed: {type(exc).__name__}: {exc}") |
| 227 | return {} |
| 228 | if not equities: |
| 229 | return {} |
| 230 | # Only the first equity: a later row is a guess among companies. |
| 231 | symbol, name = equities[0] |
| 232 | if not symbol or "." in symbol or not _same_company_name(topic, name): |
| 233 | return {} |
| 234 | return {"company": topic, "ticker": symbol.upper(), "company_source": BACKUP_SOURCE} |
| 235 | |
| 236 | |
| 237 | def _confirmed_symbol(company: dict[str, Any]) -> str | None: |
| 238 | """The Yahoo symbol for a resolved company, or None when not certain. |
| 239 | Raises ``SymbolSearchFailed`` when the symbol search itself failed.""" |
| 240 | name = str(company.get("company") or "").strip() |
| 241 | ticker = str(company.get("ticker") or "").strip().upper() |
| 242 | if ticker: |
| 243 | if str(company.get("exchange") or "").casefold() in _US_EXCHANGES: |
| 244 | return ticker |
| 245 | # The backup took this symbol from Yahoo itself and only without an |
| 246 | # exchange suffix, so it is already Yahoo's symbol. |
| 247 | if company.get("company_source") == BACKUP_SOURCE: |
| 248 | return ticker |
| 249 | if not name: |
| 250 | return None |
| 251 | return _first_equity( |
| 252 | name, lambda symbol: symbol == ticker or symbol.startswith(ticker + "."), |
| 253 | ) |
| 254 | candidates = { |
| 255 | str(candidate).strip().upper() |
| 256 | for candidate in company.get("ticker_candidates") or [] |
| 257 | if str(candidate).strip() |
| 258 | } |
| 259 | if not candidates or not name: |
| 260 | return None |
| 261 | seen: list[str] = [] |
| 262 | |
| 263 | def first_only(symbol: str) -> bool: |
| 264 | seen.append(symbol) |
| 265 | return True |
| 266 | |
| 267 | symbol = _first_equity(name, first_only) |
| 268 | if symbol and (seen[0] in candidates or seen[0].split(".", 1)[0] in candidates): |
| 269 | return symbol |
| 270 | return None |
| 271 | |
| 272 | |
| 273 | def _epoch(day: date) -> int: |
| 274 | return int(datetime(day.year, day.month, day.day, tzinfo=timezone.utc).timestamp()) |
| 275 | |
| 276 | |
| 277 | def _fetch_window(symbol: str, range_from: str, range_to: str) -> dict[str, Any]: |
| 278 | """``{"bars": [(iso date, close)], "currency": str}`` for the window, or |
| 279 | ``{"error": text}``. Fetched once per symbol and window.""" |
| 280 | key = (symbol, range_from, range_to) |
| 281 | with _fetch_lock: |
| 282 | pending = _fetched.get(key) |
| 283 | fetching = pending is None |
| 284 | if fetching: |
| 285 | pending = _fetched[key] = Future() |
| 286 | if fetching: |
| 287 | try: |
| 288 | pending.set_result(_fetch_window_uncached(symbol, range_from, range_to)) |
| 289 | except BaseException as exc: |
| 290 | # Whoever is waiting gets the error; the next request tries again. |
| 291 | with _fetch_lock: |
| 292 | if _fetched.get(key) is pending: |
| 293 | del _fetched[key] |
| 294 | pending.set_exception(exc) |
| 295 | return pending.result() |
| 296 | |
| 297 | |
| 298 | def _fetch_window_uncached(symbol: str, range_from: str, range_to: str) -> dict[str, Any]: |
| 299 | first = date.fromisoformat(range_from) |
| 300 | last = date.fromisoformat(range_to) |
| 301 | _log(f"chart {symbol} {range_from}..{range_to}") |
| 302 | response = _run_cli([ |
| 303 | "chart", symbol, |
| 304 | "--period1", str(_epoch(first - timedelta(days=1))), |
| 305 | "--period2", str(_epoch(last + timedelta(days=2))), |
| 306 | "--interval", "1d", |
| 307 | ]) |
| 308 | if "error" in response: |
| 309 | return response |
| 310 | try: |
| 311 | chart = response["data"]["results"]["chart"] |
| 312 | results = chart.get("result") or [] |
| 313 | if not results: |
| 314 | reason = (chart.get("error") or {}).get("description") or "no chart data" |
| 315 | return {"error": str(reason)} |
| 316 | meta = results[0].get("meta") or {} |
| 317 | offset = int(meta.get("gmtoffset") or 0) |
| 318 | stamps = results[0].get("timestamp") or [] |
| 319 | closes = results[0]["indicators"]["quote"][0].get("close") or [] if stamps else [] |
| 320 | bars = [] |
| 321 | for stamp, close in zip(stamps, closes): |
| 322 | if not isinstance(close, (int, float)) or isinstance(close, bool): |
| 323 | continue |
| 324 | day = datetime.fromtimestamp(stamp + offset, timezone.utc).date().isoformat() |
| 325 | if range_from <= day <= range_to: |
| 326 | bars.append((day, round(float(close), 4))) |
| 327 | except (AttributeError, IndexError, KeyError, TypeError, ValueError) as exc: |
| 328 | return {"error": f"schema: unexpected chart response ({exc!r})"} |
| 329 | return { |
| 330 | "bars": bars, |
| 331 | "currency": str(meta.get("currency") or "").upper(), |
| 332 | "instrument": str(meta.get("instrumentType") or "").upper(), |
| 333 | "name": str(meta.get("longName") or meta.get("shortName") or "").strip(), |
| 334 | } |
| 335 | |
| 336 | |
| 337 | def _percent(start: float, end: float) -> float: |
| 338 | return (end / start - 1.0) * 100.0 |
| 339 | |
| 340 | |
| 341 | def _summary(bars: list[tuple[str, float]]) -> dict[str, Any]: |
| 342 | """First and last close, the change between them, and the daily moves |
| 343 | ordered largest first. Needs two bars.""" |
| 344 | moves = [ |
| 345 | { |
| 346 | "date": day, |
| 347 | "previous_close": previous, |
| 348 | "close": close, |
| 349 | "change_pct": _percent(previous, close), |
| 350 | } |
| 351 | for (_previous_day, previous), (day, close) in zip(bars, bars[1:]) |
| 352 | if previous |
| 353 | ] |
| 354 | moves.sort(key=lambda move: abs(move["change_pct"]), reverse=True) |
| 355 | (start_date, start_close), (end_date, end_close) = bars[0], bars[-1] |
| 356 | return { |
| 357 | "start_date": start_date, |
| 358 | "start_close": start_close, |
| 359 | "end_date": end_date, |
| 360 | "end_close": end_close, |
| 361 | "change_pct": _percent(start_close, end_close), |
| 362 | "top_moves": moves[:TOP_MOVES], |
| 363 | } |
| 364 | |
| 365 | |
| 366 | def fetch_market_data(company: dict[str, Any], range_from: str, range_to: str) -> dict[str, Any]: |
| 367 | """The price window for a resolved company. |
| 368 | |
| 369 | Returns ``{}`` when there is nothing to fetch (binary absent, no ticker, |
| 370 | or a symbol Yahoo does not confirm), ``{"artifact": {...}}`` when the |
| 371 | window came back, and ``{"error": text}`` when the symbol search or the |
| 372 | fetch for a confirmed symbol failed. Never raises. |
| 373 | """ |
| 374 | if not (company.get("ticker") or company.get("ticker_candidates")): |
| 375 | return {} |
| 376 | if not _is_available(): |
| 377 | return {} |
| 378 | try: |
| 379 | try: |
| 380 | symbol = _confirmed_symbol(company) |
| 381 | except SymbolSearchFailed as exc: |
| 382 | _log(str(exc)) |
| 383 | return {"error": str(exc)} |
| 384 | if not symbol: |
| 385 | return {} |
| 386 | window = _fetch_window(symbol, range_from, range_to) |
| 387 | if "error" not in window and len(window["bars"]) < 2: |
| 388 | window = {"error": f"fewer than two daily closes in {range_from}..{range_to}"} |
| 389 | if "error" in window: |
| 390 | _log(f"{symbol}: {window['error']}") |
| 391 | return {"error": f"{symbol}: {window['error']}"} |
| 392 | if not window["bars"][0][1]: |
| 393 | return {"error": f"{symbol}: first close is zero"} |
| 394 | return {"artifact": _artifact( |
| 395 | symbol, window, range_from, range_to, |
| 396 | company=str(company.get("company") or ""), |
| 397 | via_person=bool(company.get("company_via_person")), |
| 398 | )} |
| 399 | except Exception as exc: |
| 400 | _log(f"failed for {company.get('company')!r}: {type(exc).__name__}: {exc}") |
| 401 | return {"error": f"{type(exc).__name__}: {exc}"} |
| 402 | |
| 403 | |
| 404 | def _artifact( |
| 405 | symbol: str, window: dict[str, Any], range_from: str, range_to: str, **labels: Any, |
| 406 | ) -> dict[str, Any]: |
| 407 | """The price window as the report stores it, with the S&P 500 beside a US |
| 408 | listing. ``window`` holds at least two bars.""" |
| 409 | artifact: dict[str, Any] = { |
| 410 | "symbol": symbol, |
| 411 | **labels, |
| 412 | "currency": window["currency"], |
| 413 | "range_from": range_from, |
| 414 | "range_to": range_to, |
| 415 | **_summary(window["bars"]), |
| 416 | } |
| 417 | # A US listing: quoted in dollars under a symbol with no exchange suffix. |
| 418 | if window["currency"] == "USD" and "." not in symbol: |
| 419 | benchmark = _fetch_window(BENCHMARK_SYMBOL, range_from, range_to) |
| 420 | if "error" in benchmark or len(benchmark["bars"]) < 2 or not benchmark["bars"][0][1]: |
| 421 | _log(f"{BENCHMARK_SYMBOL}: {benchmark.get('error') or 'fewer than two daily closes'}") |
| 422 | else: |
| 423 | summary = _summary(benchmark["bars"]) |
| 424 | artifact["benchmark"] = { |
| 425 | "symbol": BENCHMARK_SYMBOL, |
| 426 | "name": BENCHMARK_NAME, |
| 427 | "start_close": summary["start_close"], |
| 428 | "end_close": summary["end_close"], |
| 429 | "change_pct": summary["change_pct"], |
| 430 | } |
| 431 | return artifact |
| 432 | |
| 433 | |
| 434 | def parse_host_tickers(raw: str) -> list[dict[str, str]]: |
| 435 | """The pairs of a ``--ticker`` value, ``SYMBOL:Company name`` separated by |
| 436 | commas, so a company name cannot hold a comma. The symbol is upper-cased |
| 437 | and a leading ``$`` dropped; the name is everything after the first colon. |
| 438 | Only the first ``MAX_HOST_TICKERS`` pairs are read. Each is ``pair`` (as |
| 439 | typed), ``symbol`` and ``company``, with a ``reason`` when it cannot be |
| 440 | used: no company name, a symbol that is not one, or a repeated symbol.""" |
| 441 | entries = [entry.strip() for entry in raw.split(",") if entry.strip()] |
| 442 | if len(entries) > MAX_HOST_TICKERS: |
| 443 | ignored = ", ".join(entry[:_HOST_TEXT_LIMIT] for entry in entries[MAX_HOST_TICKERS:]) |
| 444 | _log(f"--ticker takes {MAX_HOST_TICKERS} pairs; ignoring {ignored}") |
| 445 | pairs: list[dict[str, str]] = [] |
| 446 | for entry in entries[:MAX_HOST_TICKERS]: |
| 447 | symbol, _colon, company = entry.partition(":") |
| 448 | symbol = symbol.strip().lstrip("$").upper() |
| 449 | pair = { |
| 450 | "pair": entry[:_HOST_TEXT_LIMIT], |
| 451 | "symbol": symbol, |
| 452 | "company": " ".join(company.split())[:_HOST_TEXT_LIMIT], |
| 453 | } |
| 454 | if not _HOST_SYMBOL.match(symbol): |
| 455 | pair["reason"] = "not a ticker symbol" |
| 456 | elif not pair["company"]: |
| 457 | pair["reason"] = "no company name" |
| 458 | elif any(symbol == earlier["symbol"] for earlier in pairs): |
| 459 | pair["reason"] = f"repeats {symbol}" |
| 460 | pairs.append(pair) |
| 461 | return pairs |
| 462 | |
| 463 | |
| 464 | def _check_host_ticker(symbol: str, company: str, range_from: str, range_to: str) -> dict[str, Any]: |
| 465 | """Whether Yahoo agrees that ``symbol`` is the stock of ``company``. |
| 466 | |
| 467 | ``{"window": ...}`` when it does. Otherwise ``{"reason": text}``, with |
| 468 | ``"error"`` as well when Yahoo could not be asked, which says nothing |
| 469 | about the pair. Raises nothing the caller does not catch.""" |
| 470 | window = _fetch_window(symbol, range_from, range_to) |
| 471 | if "error" in window: |
| 472 | failure = window["error"].casefold() |
| 473 | if "http 404" in failure or "no data found" in failure: |
| 474 | return {"reason": f"Yahoo has no price data for {symbol}"} |
| 475 | return {"reason": "not checked: price fetch failed", "error": f"{symbol}: {window['error']}"} |
| 476 | if window["instrument"] != "EQUITY": |
| 477 | return {"reason": f"{symbol} is not a stock on Yahoo ({window['instrument'] or 'no type'})"} |
| 478 | if len(window["bars"]) < 2 or not window["bars"][0][1]: |
| 479 | return {"reason": f"{symbol} has fewer than two daily closes in {range_from}..{range_to}"} |
| 480 | try: |
| 481 | equities = _equities(company) |
| 482 | except SymbolSearchFailed as exc: |
| 483 | return {"reason": "not checked: symbol search failed", "error": str(exc)} |
| 484 | listed_as = f"{symbol} is {window['name'] or 'unnamed'}" |
| 485 | if not equities: |
| 486 | return {"reason": f"Yahoo lists no stock for {company!r}; {listed_as}"} |
| 487 | # Only the first equity, as everywhere else: a later row is a guess. |
| 488 | first_symbol, first_name = equities[0] |
| 489 | same_name = _name_key(first_name) and _name_key(first_name) == _name_key(window["name"]) |
| 490 | if first_symbol.upper() == symbol or same_name: |
| 491 | return {"window": window} |
| 492 | return { |
| 493 | "reason": f"Yahoo's first stock for {company!r} is {first_symbol} ({first_name}); {listed_as}" |
| 494 | } |
| 495 | |
| 496 | |
| 497 | PRICE_WINDOW_DAYS = 30 |
| 498 | |
| 499 | |
| 500 | def _thirty_days_before(range_to: str) -> str: |
| 501 | """The footer says "in the L30", so the price window is always the 30 days |
| 502 | ending on the report's last day, whatever the research window was.""" |
| 503 | return (date.fromisoformat(range_to) - timedelta(days=PRICE_WINDOW_DAYS)).isoformat() |
| 504 | |
| 505 | |
| 506 | def is_excluded(config: dict[str, Any] | None) -> bool: |
| 507 | """True when ``EXCLUDE_SOURCES`` names this source.""" |
| 508 | return SOURCE in env.exclude_sources(config or {}) |
| 509 | |
| 510 | |
| 511 | def attach_market_data( |
| 512 | report: schema.Report, company: dict[str, Any], config: dict[str, Any] | None = None, |
| 513 | ) -> None: |
| 514 | """Fetch the report's window for the company and record it on the report: |
| 515 | the ``yahoo_finance`` artifact on success, a degraded source outcome on a |
| 516 | failed fetch, and nothing at all when there was nothing to fetch or the |
| 517 | run's ``config`` excludes the source.""" |
| 518 | if is_excluded(config): |
| 519 | return |
| 520 | outcome = fetch_market_data(company or {}, _thirty_days_before(report.range_to), report.range_to) |
| 521 | if "artifact" in outcome: |
| 522 | report.artifacts[SOURCE] = outcome["artifact"] |
| 523 | elif "error" in outcome: |
| 524 | _record_failure(report, outcome["error"]) |
| 525 | |
| 526 | |
| 527 | def _record_failure(report: schema.Report, error: str) -> None: |
| 528 | report.source_status[SOURCE] = schema.SourceOutcome( |
| 529 | source=SOURCE, |
| 530 | state=http.classify_failure(message=error), |
| 531 | detail=error, |
| 532 | fix_hint="doctor", |
| 533 | ) |
| 534 | |
| 535 | |
| 536 | def _record_missing_cli(report: schema.Report) -> None: |
| 537 | """Say once that the host's tickers went unchecked for want of the helper, |
| 538 | with the command that installs it.""" |
| 539 | detail = f"{CLI_BIN} is not on PATH; install: {health.pp_install_cmd('yahoo-finance')}" |
| 540 | _log(f"--ticker not checked: {detail}") |
| 541 | report.source_status[SOURCE] = schema.SourceOutcome( |
| 542 | source=SOURCE, |
| 543 | state=health.SKIPPED_UNCONFIGURED, |
| 544 | detail=detail, |
| 545 | attempted=False, |
| 546 | ) |
| 547 | |
| 548 | |
| 549 | def attach_host_tickers( |
| 550 | report: schema.Report, pairs: list[dict[str, str]], config: dict[str, Any] | None = None, |
| 551 | ) -> dict[str, Any]: |
| 552 | """Check the host's ``--ticker`` pairs and record the accepted ones on the |
| 553 | report, in place of ``attach_market_data``: there is no other ticker to |
| 554 | fall back to, because a line for another company is worse than none. |
| 555 | |
| 556 | The ``yahoo_finance`` artifact is the first accepted window, and a second |
| 557 | one sits in its ``more`` list. A check Yahoo could not answer records a |
| 558 | degraded source outcome. Returns the fields for the ``resolved`` artifact: |
| 559 | ``ticker_source``, then ``ticker``, ``tickers`` and ``company`` (the first |
| 560 | accepted pair's) when a pair was accepted, and ``ticker_rejected`` (each |
| 561 | ``pair`` and ``reason``) when one was not. With the source excluded or the |
| 562 | binary absent nothing is run and every pair is listed as not checked. |
| 563 | Never raises.""" |
| 564 | range_from = _thirty_days_before(report.range_to) |
| 565 | topic_key = _name_key(report.topic or "") |
| 566 | not_run = None |
| 567 | if is_excluded(config): |
| 568 | not_run = f"not checked: {SOURCE} is excluded" |
| 569 | elif not _is_available(): |
| 570 | not_run = f"not checked: {CLI_BIN} is not on PATH" |
| 571 | if pairs: |
| 572 | _record_missing_cli(report) |
| 573 | accepted: list[dict[str, Any]] = [] |
| 574 | rejected: list[dict[str, str]] = [] |
| 575 | errors: list[str] = [] |
| 576 | for pair in pairs: |
| 577 | symbol, company = pair["symbol"], pair["company"] |
| 578 | outcome: dict[str, Any] = {"reason": pair.get("reason") or not_run} |
| 579 | if not outcome["reason"]: |
| 580 | try: |
| 581 | outcome = _check_host_ticker(symbol, company, range_from, report.range_to) |
| 582 | if "window" in outcome: |
| 583 | accepted.append(_artifact( |
| 584 | symbol, outcome["window"], range_from, report.range_to, |
| 585 | company=company, via_person=False, |
| 586 | # Beside the ticker when the topic is not the company: |
| 587 | # the person who leads it, a product, a subsidiary. |
| 588 | name_company=_name_key(company) != topic_key, |
| 589 | )) |
| 590 | continue |
| 591 | except Exception as exc: |
| 592 | error = f"{symbol}: {type(exc).__name__}: {exc}" |
| 593 | outcome = {"reason": "not checked: the check failed", "error": error} |
| 594 | if "error" in outcome: |
| 595 | errors.append(outcome["error"]) |
| 596 | if not not_run: |
| 597 | _log(f"--ticker {pair['pair']} not used: {outcome['reason']}") |
| 598 | rejected.append({"pair": pair["pair"], "reason": outcome["reason"]}) |
| 599 | fields: dict[str, Any] = {"ticker_source": HOST_SOURCE} |
| 600 | if accepted: |
| 601 | report.artifacts[SOURCE] = {**accepted[0], "more": accepted[1:]} if accepted[1:] else accepted[0] |
| 602 | fields["ticker"] = accepted[0]["symbol"] |
| 603 | fields["tickers"] = [window["symbol"] for window in accepted] |
| 604 | fields["company"] = accepted[0]["company"] |
| 605 | if rejected: |
| 606 | fields["ticker_rejected"] = rejected |
| 607 | if errors: |
| 608 | _record_failure(report, "; ".join(errors)) |
| 609 | return fields |
| 610 |