Coverage for src/polars_yahoo/_ticker.py: 100%
41 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 15:16 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 15:16 +0000
1"""Single-symbol access: price history, dividends and splits."""
3from __future__ import annotations
5from collections.abc import Callable
6from functools import cached_property
7from typing import Any
9import polars as pl
11from . import _chart, _http
12from ._chart import DateLike
13from .exceptions import ResponseError
15# What a parser raises when a chart result does not have the shape Yahoo documents.
16_PARSE_ERRORS = (KeyError, TypeError, AttributeError, pl.exceptions.PolarsError)
19class Ticker:
20 """One Yahoo Finance symbol.
22 ``session`` lets you inject any object with a ``requests``-style ``get``;
23 by default a browser-impersonating ``curl_cffi`` session is used.
24 ``timeout`` is in seconds per request; an HTTP 429, a 5xx or a transport
25 failure is retried up to ``retries`` times. Before each retry it waits a random
26 time of at most ``backoff * 2**attempt`` seconds, so the cap doubles each time.
27 """
29 def __init__(
30 self,
31 symbol: str,
32 *,
33 session: _http.Session | None = None,
34 timeout: float = _http.TIMEOUT,
35 retries: int = _http.RETRIES,
36 backoff: float = _http.BACKOFF,
37 ) -> None:
38 """Normalise the symbol (stripped, upper-case) and keep the session and request settings."""
39 symbol = symbol.strip().upper()
40 if not symbol:
41 raise ValueError("symbol must not be empty") # noqa: TRY003 - argument validation; a ValueError with context is the idiom
42 _http.check_request_settings(timeout, retries, backoff)
43 self.symbol = symbol
44 self._session = session
45 self._timeout = timeout
46 self._retries = retries
47 self._backoff = backoff
49 def _get(self, params: dict[str, Any]) -> dict[str, Any]:
50 """Fetch one chart result with this ticker's session and request settings."""
51 return _http.get_chart(
52 self.symbol,
53 params,
54 session=self._session,
55 timeout=self._timeout,
56 retries=self._retries,
57 backoff=self._backoff,
58 )
60 def __repr__(self) -> str:
61 """Show the symbol."""
62 return f"Ticker({self.symbol!r})"
64 def _parse(self, parser: Callable[..., pl.DataFrame], *args: Any) -> pl.DataFrame:
65 """Run ``parser`` on a chart result, turning a malformed result into :class:`ResponseError`.
67 ``get_chart`` only returns a result Yahoo sent as usable data, so the status is 200.
68 """
69 try:
70 return parser(self.symbol, *args)
71 except _PARSE_ERRORS as exc:
72 raise ResponseError(self.symbol, 200, "malformed chart payload") from exc
74 def history(
75 self,
76 period: str | None = "1mo",
77 interval: str = "1d",
78 start: DateLike | None = None,
79 end: DateLike | None = None,
80 prepost: bool = False,
81 ) -> pl.DataFrame:
82 """Return OHLCV bars as a long polars frame.
84 Daily and longer intervals carry a ``date`` column (exchange-local),
85 intraday ones a time-zone-aware ``timestamp``. Prices are as Yahoo
86 reports them, unadjusted, with Yahoo's own ``adj_close`` alongside.
87 """
88 params = _chart.build_params(period=period, interval=interval, start=start, end=end, prepost=prepost)
89 result = self._get(params)
90 return self._parse(_chart.parse_prices, result, interval)
92 @cached_property
93 def _events(self) -> dict[str, Any]:
94 """Fetch the full-history chart result that carries dividends and splits.
96 Yahoo returns every event in range whatever the interval, so the
97 coarsest bars are requested to keep the payload small. The result is
98 cached on the instance, so ``dividends()`` and ``splits()`` share one
99 request; create a new ``Ticker`` to refetch.
100 """
101 params = _chart.build_params(period="max", interval="3mo")
102 return self._get(params)
104 def dividends(self) -> pl.DataFrame:
105 """Return the full dividend history: ``ticker, date, dividend``."""
106 return self._parse(_chart.parse_dividends, self._events)
108 def splits(self) -> pl.DataFrame:
109 """Return the full split history: ``ticker, date, numerator, denominator, ratio``."""
110 return self._parse(_chart.parse_splits, self._events)