Resilient Caching Client for Daily Equity Prices

Medium · Software Engineering Fundamentals · Software Engineer · Online Assessment

Problem Statement

Build a Python client StockDataClient that downloads, validates, deduplicates, and caches daily opening and closing equity prices from an unreliable, cursor-paginated upstream feed.

Classes and Signatures

from typing import Callable, Dict, List
import time
from datetime import date
from decimal import Decimal


class ApiError(Exception):
    def __init__(self, status_code: int, message: str = "") -> None: ...


class StockDataClient:
    def __init__(
        self,
        fetch_page: Callable,
        max_attempts: int = 3,
        base_delay: float = 0.5,
        sleep: Callable[[float], None] = time.sleep,
    ) -> None: ...

    def get_price_history(
        self, ticker: str, start_date: date, end_date: date
    ) -> List[Dict]: ...

Behavioral Rules

  1. Paginated upstream callable:
    • fetch_page(ticker, start_date, end_date, page_token) returns a dictionary shaped as {"data": [...], "next_page_token": token_or_none}.
    • Start each range download with page_token=None and continue fetching subsequent pages until next_page_token is None or "".
    • If the upstream feed ever repeats a non-empty next_page_token within the same range download, raise RuntimeError rather than looping indefinitely.
  2. Retry policy and failure atomicity:
    • fetch_page may raise ApiError(status_code, message) for HTTP failures, or TimeoutError / ConnectionError when a socket fails.
    • Treat TimeoutError, ConnectionError, and ApiError with 500 <= status_code <= 599 as transient errors. Retry a failing page request up to max_attempts total tries; after the k-th failure (1 <= k < max_attempts), pause by calling sleep(base_delay * (2 ** (k - 1))) before retrying that same page. Re-raise the error once max_attempts tries fail.
    • Non-transient exceptions (such as ApiError(404) or unexpected runtime errors) must propagate immediately without sleeping or retrying.
    • If any page in a range download ultimately fails, discard partial results from earlier pages so no half-loaded range enters the cache.
  3. Record parsing and deduplication:
    • Valid raw records are dicts with "date" (an ISO "YYYY-MM-DD" string, date, or datetime), "open", and "close".
    • Convert "open" and "close" into positive, finite decimal.Decimal instances without binary floating-point rounding artifacts (convert float values via str(...) first; reject bool, NaN, Infinity, non-positive numbers, and unparseable values).
    • Skip malformed records and any stray records whose date falls outside the requested sub-range. When multiple valid records share a date, retain the first valid record encountered and ignore later copies.
  4. Full calendar output and gap-aware caching:
    • Return one dictionary per calendar date from start_date through end_date inclusive, ordered chronologically from earliest to latest:
      • Valid trading day: {"date": day, "open": Decimal(...), "close": Decimal(...), "status": "ok"}
      • Day with no valid record (weekends, holidays, or empty feed responses): {"date": day, "open": None, "close": None, "status": "missing"}
    • Normalize ticker by trimming whitespace and uppercasing so "orcl" and "ORCL" share cached entries and send "ORCL" upstream.
    • Cache both present prices and known "missing" dates per (ticker, date) so subsequent overlapping calls request only contiguous uncached date intervals.
  5. Argument validation:
    • Raise ValueError in __init__ if max_attempts < 1 (or base_delay < 0).
    • Raise ValueError in get_price_history if ticker is not a non-blank string or if start_date > end_date.
    • Raise TypeError unless both start_date and end_date are datetime.date objects (datetime.datetime instances must be rejected).

Examples

Example 1

# Upstream feed holds ORCL records:
#   2024-04-04 -> open "124.10", close "125.85"
#   2024-04-05 -> open "126.00", close "124.75"
client.get_price_history("ORCL", date(2024, 4, 4), date(2024, 4, 5))

Output:

[
    {"date": date(2024, 4, 4), "open": Decimal("124.10"), "close": Decimal("125.85"), "status": "ok"},
    {"date": date(2024, 4, 5), "open": Decimal("126.00"), "close": Decimal("124.75"), "status": "ok"},
]

Explanation: Both calendar days in [2024-04-04, 2024-04-05] have valid records, so both rows return status="ok" with exact Decimal prices.

Example 2

# Continuing on the same client instance from Example 1.
# For 2024-04-06..2024-04-08, the feed returns two records on Monday 2024-04-08:
#   {"date": "2024-04-08", "open": "125.20", "close": "127.40"}
#   {"date": "2024-04-08", "open": "999.00", "close": "999.00"}
# and no records for Saturday 2024-04-06 or Sunday 2024-04-07.
client.get_price_history("orcl", date(2024, 4, 5), date(2024, 4, 8))

Output:

[
    {"date": date(2024, 4, 5), "open": Decimal("126.00"), "close": Decimal("124.75"), "status": "ok"},
    {"date": date(2024, 4, 6), "open": None, "close": None, "status": "missing"},
    {"date": date(2024, 4, 7), "open": None, "close": None, "status": "missing"},
    {"date": date(2024, 4, 8), "open": Decimal("125.20"), "close": Decimal("127.40"), "status": "ok"},
]

Explanation: "orcl" normalizes to "ORCL". Because 2024-04-05 was already fetched in Example 1, the client queries fetch_page only for (date(2024, 4, 6), date(2024, 4, 8)). Weekend dates 04-06 and 04-07 become "missing" (and are negatively cached), while 04-08 keeps the first valid record.

Constraints

  • Valid date intervals span up to 5 years (1 <= (end_date - start_date).days + 1 <= 1827).
  • "data" in a page response may be empty, None, unsorted, or contain duplicate dates and malformed entries across page boundaries.
  • max_attempts >= 1 and base_delay >= 0 for valid client configurations.

Step-by-step walkthrough

  1. Restate the problem and clarify the contract

    We need to build StockDataClient, whose get_price_history(ticker, start_date, end_date) method returns one dictionary per calendar day from start_date through end_date inclusive, sorted from oldest to newest. Under the hood, prices come from a slow, paginated, and occasionally unreliable external API.

    An open-ended engineering prompt leaves several interface details implicit. In an interview, state these contracts clearly before writing code:

    • Dependency injection for testability. StockDataClient(fetch_page, max_attempts=3, base_delay=0.5, sleep=time.sleep) accepts fetch_page and sleep as arguments so tests can simulate API pages and network failures instantly without real network sockets or real waiting.
    • How errors arrive. fetch_page raises ApiError(status_code) for HTTP errors and TimeoutError or ConnectionError when the network drops.
    • Row shape for trading days vs. missing days. Every calendar date gets a row with four keys:
      • Present: {'date': day, 'open': Decimal(...), 'close': Decimal(...), 'status': 'ok'}
      • Absent (such as weekends, market holidays, or missing API records): {'date': day, 'open': None, 'close': None, 'status': 'missing'}
    • Deduplication rule. If the API returns multiple records for the same date, keep the first valid record and ignore later duplicates.
    • Input validation. Reject blank tickers or start_date > end_date with ValueError, and reject non-date values (including datetime.datetime) with TypeError. Normalize tickers to uppercase so 'orcl' and 'ORCL' share the same cache.
  2. Why a naive fetch-every-time loop falls short

    The most obvious implementation calls fetch_page from start_date to end_date on every call, puts the returned dates in a dictionary, and loops over the calendar range. That works once on a clean network, but breaks down in three ways:

    1. Redundant network calls. Asking for January 1–31 right after asking for January 10–20 downloads those 11 overlapping days all over again. Worse, if you only cache dates that returned prices, every weekend or holiday inside a cached range looks "missing" and triggers fresh API calls forever.
    2. Fragile pagination. A 5-year range (~1,826 days) can span dozens of pages. Without bounded retries, a single temporary HTTP 503 on page 12 aborts the entire call.
    3. Floating-point rounding. Parsing "125.85" or 0.1 through binary float introduces tiny representation errors (0.1 + 0.2 == 0.30000000000000004), which corrupts financial calculations.

    Because 5 years is at most ~1,827 calendar days, looping over individual date objects in Python takes less than a millisecond. The real bottleneck is the network, so we will add exact Decimal parsing, per-page retries with exponential backoff, and a gap-aware (ticker, date) cache.

  3. Parse prices into exact Decimals without float noise

    Binary floating-point numbers store fractions in base 2, where 0.1 has no exact finite representation. Python's decimal.Decimal stores numbers in base 10, so Decimal("0.1") + Decimal("0.2") == Decimal("0.3") exactly.

    One trap catches many Python developers: calling Decimal(0.1) directly on a float copies the binary error (Decimal('0.1000000000000000055511151231257827021181583404541015625')). Converting the float with str(value) first produces '0.1', giving the exact Decimal('0.1').

    We also guard against three edge cases in malformed API payloads: - isinstance(value, bool): in Python, bool is a subclass of int (True == 1), so we reject booleans first. - price.is_finite() before price <= 0: comparing Decimal('NaN') <= 0 raises InvalidOperation instead of returning False, so we check finiteness first. - Positive prices only: zero or negative stock prices are rejected as invalid records.

    from typing import Optional, Tuple
    from datetime import date, datetime
    from decimal import Decimal, InvalidOperation
    
    
    def parse_price(value: object) -> Optional[Decimal]:
        """Convert raw API price input into a positive, finite Decimal, or None if invalid."""
        # Reject bool explicitly because bool is a subclass of int in Python (True == 1)
        if isinstance(value, bool):
            return None
    
        # Convert float via str() first: str(0.1) is '0.1', whereas Decimal(0.1) keeps binary float noise
        if isinstance(value, float):
            text = str(value)
        elif isinstance(value, (str, int, Decimal)):
            text = str(value).strip()
        else:
            return None
    
        try:
            price = Decimal(text)
        except InvalidOperation:
            return None
    
        # Check is_finite() BEFORE price <= 0 because comparing Decimal('NaN') <= 0 raises InvalidOperation
        if not price.is_finite() or price <= 0:
            return None
        return price
    
    
    def parse_day(value: object) -> Optional[date]:
        """Convert an ISO 'YYYY-MM-DD' string, date, or datetime into a date object, or None."""
        # Check datetime before date because datetime is a subclass of date
        if isinstance(value, datetime):
            return value.date()
        if isinstance(value, date):
            return value
        if isinstance(value, str):
            try:
                return date.fromisoformat(value.strip())
            except ValueError:
                return None
        return None
    
    
    def parse_record(record: object) -> Optional[Tuple[date, Decimal, Decimal]]:
        """Extract (day, open_price, close_price) from one raw API dict, or None if malformed."""
        if not isinstance(record, dict):
            return None
        day = parse_day(record.get("date"))
        open_price = parse_price(record.get("open"))
        close_price = parse_price(record.get("close"))
        if day is None or open_price is None or close_price is None:
            return None
        return day, open_price, close_price
    
  4. Retry transient failures per page with exponential backoff

    Not every error deserves a retry: - Transient errors (temporary glitches that often succeed moments later): TimeoutError, ConnectionError, and HTTP 500–599 server errors. - Permanent errors (problems that will fail the exact same way every time): HTTP 400–499 client errors like 404 Not Found, or programming bugs like KeyError. Retrying these only wastes time, so we re-raise them immediately.

    When a transient error happens, exponential backoff doubles the pause after each failed attempt (base_delay * 2**(attempt - 1)), giving an overloaded server breathing room to recover:

    max_attempts = 3, base_delay = 0.5s
    
    Attempt 1 (t = 0.0s) ──► HTTP 503 ──► sleep 0.5s (0.5 * 2^0)
    Attempt 2 (t = 0.5s) ──► Timeout  ──► sleep 1.0s (0.5 * 2^1)
    Attempt 3 (t = 1.5s) ──► HTTP 503 ──► attempt == 3: stop and re-raise! (no extra sleep)
    

    Notice that we retry one page using its token, so if page 5 fails transiently, we retry page 5 rather than restarting from page 1.

    from typing import Callable, Dict, Optional
    from datetime import date
    
    
    class ApiError(Exception):
        """An HTTP error from the price API; status_code is the HTTP status."""
    
        def __init__(self, status_code: int, message: str = "") -> None:
            super().__init__(f"HTTP {status_code} {message}".strip())
            self.status_code = status_code
    
    
    def is_transient(error: Exception) -> bool:
        """Return True only for temporary failures worth retrying (timeouts, network drops, HTTP 5xx)."""
        if isinstance(error, (TimeoutError, ConnectionError)):
            return True
        # HTTP 5xx errors come from temporary server trouble; HTTP 4xx errors (like 404) are permanent
        if isinstance(error, ApiError):
            return 500 <= error.status_code <= 599
        return False
    
    
    class StockDataClient:
        def _fetch_with_retry(self, ticker: str, first: date, last: date, token: Optional[str]) -> Dict:
            """Fetch a single page, retrying transient errors with exponential backoff."""
            attempt = 0
            while True:
                try:
                    return self._fetch_page(ticker, first, last, token)
                except Exception as error:
                    attempt += 1
                    # Fail immediately on permanent errors (4xx, bugs) or once max_attempts is reached
                    if not is_transient(error) or attempt >= self._max_attempts:
                        raise
                    # Exponential backoff: sleep base_delay * 2^0, base_delay * 2^1, ... between attempts
                    backoff_seconds = self._base_delay * (2 ** (attempt - 1))
                    self._sleep(backoff_seconds)
    
  5. Consume pages safely until next_page_token runs out

    A paginated API returns a chunk of records plus a next_page_token cursor pointing to the next chunk. We start with page_token = None and loop until next_page_token comes back None or empty:

    call(token=None) ──► {data: [d1, d2], next_page_token: "p2"}
    call(token="p2") ──► {data: [d3, d4], next_page_token: "p3"}
    call(token="p3") ──► {data: [d5],     next_page_token: None} ──► done! (5 records)
    

    Two defensive checks protect the loop against misbehaving servers: - page.get("data") or [] treats a missing or None "data" field as an empty list instead of crashing. - seen_tokens remembers every non-empty token we have already requested; if a buggy server ever returns a token we already used, we raise RuntimeError instead of hanging in an infinite loop.

    from typing import List, Optional, Set
    from datetime import date
    
    
    class StockDataClient:
        def _fetch_all_pages(self, ticker: str, first: date, last: date) -> List:
            """Consume paginated API responses until next_page_token is empty or None."""
            records: List = []
            page_token: Optional[str] = None
            # seen_tokens: set of non-empty page tokens already requested, guarding against infinite token loops
            seen_tokens: Set[str] = set()
    
            while True:
                page = self._fetch_with_retry(ticker, first, last, page_token)
                page_items = page.get("data") or []
                records.extend(page_items)
    
                page_token = page.get("next_page_token")
                if not page_token:
                    return records
                if page_token in seen_tokens:
                    raise RuntimeError(f"API repeated page token {page_token!r}")
                seen_tokens.add(page_token)
    
  6. Cache by (ticker, date) and fetch only uncached gaps

    If we keyed the cache by the whole request (ticker, start_date, end_date), overlapping requests would still miss. Instead, we maintain two per-day structures:

    • _prices[(ticker, day)] = (open_price, close_price) for every valid trading record.
    • _fetched: a set of (ticker, day) pairs covered by a completed fetch.

    Why do we need _fetched in addition to _prices? Suppose Saturday 2024-04-06 has no trading data. Once we have fetched April 5–8, (ticker, 2024-04-06) is in _fetched even though it is not in _prices. On the next call, we immediately know April 6 is genuinely 'missing' without asking the API again. Caching known absences like this is called negative caching.

    When a new range arrives, we filter down to days not in _fetched and group consecutive uncached days into (run_start, run_end) intervals:

    Already in _fetched:             [Apr 04 .. Apr 05]
    New request:         [Apr 01 ......................... Apr 08]
    Uncached gaps:       [Apr 01..03]                  [Apr 06..08]
                         └─ Run 1 ─┘                   └─ Run 2 ─┘
    

    Finally, _load_range commits to _prices and _fetched only after every page of the run has arrived. If page 3 of 4 fails after all retries, nothing is written to the cache, so a later call cleanly retries the whole gap.

    from typing import Dict, List, Tuple
    from datetime import date, timedelta
    from decimal import Decimal
    
    
    def days_between(start: date, end: date) -> List[date]:
        """Generate every calendar date from start through end inclusive, in ascending order."""
        days: List[date] = []
        current_day = start
        while current_day <= end:
            days.append(current_day)
            current_day += timedelta(days=1)
        return days
    
    
    def contiguous_runs(days: List[date]) -> List[Tuple[date, date]]:
        """Collapse sorted dates into (run_start, run_end) intervals of consecutive calendar days."""
        # runs: list of (first_day, last_day), e.g. [(2024-04-01, 2024-04-03), (2024-04-06, 2024-04-08)]
        runs: List[Tuple[date, date]] = []
        for day in days:
            if runs and runs[-1][1] + timedelta(days=1) == day:
                # Extend the current run when this day immediately follows the previous day
                previous_start = runs[-1][0]
                runs[-1] = (previous_start, day)
            else:
                runs.append((day, day))
        return runs
    
    
    class StockDataClient:
        def _load_range(self, ticker: str, first: date, last: date) -> None:
            """Download all pages for [first, last], deduplicate, and commit atomically to the cache."""
            raw_records = self._fetch_all_pages(ticker, first, last)
    
            # found: {day: (open_price, close_price)} keeping only the first valid record per in-range date
            found: Dict[date, Tuple[Decimal, Decimal]] = {}
            for raw_record in raw_records:
                parsed = parse_record(raw_record)
                if parsed is None:
                    continue
                day, open_price, close_price = parsed
                # Ignore stray out-of-range dates so we never cache partial data outside [first, last]
                if day < first or day > last:
                    continue
                if day in found:
                    # Duplicate date in API response: keep the first valid record we saw
                    continue
                found[day] = (open_price, close_price)
    
            # Commit to cache only AFTER all pages succeed so a mid-range failure leaves no half-cached state
            for day, price_pair in found.items():
                self._prices[(ticker, day)] = price_pair
            for day in days_between(first, last):
                self._fetched.add((ticker, day))
    
  7. Assemble every calendar date and trace two requests

    get_price_history validates its inputs, loads any uncached runs, and walks all_days in ascending order to emit one fresh dictionary per calendar day.

    Notice one subtle Python type check in _check_args: datetime is a subclass of date, so isinstance(datetime(2024, 4, 4), date) returns True! However, datetime(2024, 4, 4) != date(2024, 4, 4) when looking up keys in _prices, and comparing datetime < date raises TypeError. Rejecting isinstance(boundary, datetime) explicitly catches that bug immediately.

    Let's trace the two sample calls starting from an empty cache:

    Call 1: get_price_history("ORCL", 2024-04-04, 2024-04-05)
      uncached_days = [04-04, 04-05] -> runs = [(04-04, 04-05)]
      API call 1: fetch_page("ORCL", 04-04, 04-05, None) -> 2 records, next_page_token=None
      _prices  = {("ORCL", 04-04): (124.10, 125.85), ("ORCL", 04-05): (126.00, 124.75)}
      _fetched = {("ORCL", 04-04), ("ORCL", 04-05)}
      returns: [04-04 ok, 04-05 ok]
    
    Call 2: get_price_history("orcl", 2024-04-05, 2024-04-08)  (04-06..04-07 weekend; 1st try hits 503)
      normalized_ticker = "ORCL"
      uncached_days = [04-06, 04-07, 04-08] -> runs = [(04-06, 04-08)]
      Run 1 (04-06..04-08): try 1 -> HTTP 503 -> sleep 0.5s -> try 2 -> duplicate records on 04-08
      deduplication keeps first valid 04-08 record (125.20, 127.40)
      returns: [04-05 ok (cached), 04-06 missing, 04-07 missing, 04-08 ok]
    

    If we later query 2024-04-06..2024-04-07, uncached_days is empty (both weekend days are in _fetched), so zero API calls are made.

  8. Complete solution

    from typing import Callable, Dict, List, Optional, Set, Tuple
    import time
    from datetime import date, datetime, timedelta
    from decimal import Decimal, InvalidOperation
    
    
    class ApiError(Exception):
        """An HTTP error from the price API; status_code is the HTTP status."""
    
        def __init__(self, status_code: int, message: str = "") -> None:
            super().__init__(f"HTTP {status_code} {message}".strip())
            self.status_code = status_code
    
    
    def is_transient(error: Exception) -> bool:
        """Return True only for temporary failures worth retrying (timeouts, network drops, HTTP 5xx)."""
        if isinstance(error, (TimeoutError, ConnectionError)):
            return True
        # HTTP 5xx errors come from temporary server trouble; HTTP 4xx errors (like 404) are permanent
        if isinstance(error, ApiError):
            return 500 <= error.status_code <= 599
        return False
    
    
    def parse_price(value: object) -> Optional[Decimal]:
        """Convert raw API price input into a positive, finite Decimal, or None if invalid."""
        # Reject bool explicitly because bool is a subclass of int in Python (True == 1)
        if isinstance(value, bool):
            return None
    
        # Convert float via str() first: str(0.1) is '0.1', whereas Decimal(0.1) keeps binary float noise
        if isinstance(value, float):
            text = str(value)
        elif isinstance(value, (str, int, Decimal)):
            text = str(value).strip()
        else:
            return None
    
        try:
            price = Decimal(text)
        except InvalidOperation:
            return None
    
        # Check is_finite() BEFORE price <= 0 because comparing Decimal('NaN') <= 0 raises InvalidOperation
        if not price.is_finite() or price <= 0:
            return None
        return price
    
    
    def parse_day(value: object) -> Optional[date]:
        """Convert an ISO 'YYYY-MM-DD' string, date, or datetime into a date object, or None."""
        # Check datetime before date because datetime is a subclass of date
        if isinstance(value, datetime):
            return value.date()
        if isinstance(value, date):
            return value
        if isinstance(value, str):
            try:
                return date.fromisoformat(value.strip())
            except ValueError:
                return None
        return None
    
    
    def parse_record(record: object) -> Optional[Tuple[date, Decimal, Decimal]]:
        """Extract (day, open_price, close_price) from one raw API dict, or None if malformed."""
        if not isinstance(record, dict):
            return None
        day = parse_day(record.get("date"))
        open_price = parse_price(record.get("open"))
        close_price = parse_price(record.get("close"))
        if day is None or open_price is None or close_price is None:
            return None
        return day, open_price, close_price
    
    
    def days_between(start: date, end: date) -> List[date]:
        """Generate every calendar date from start through end inclusive, in ascending order."""
        days: List[date] = []
        current_day = start
        while current_day <= end:
            days.append(current_day)
            current_day += timedelta(days=1)
        return days
    
    
    def contiguous_runs(days: List[date]) -> List[Tuple[date, date]]:
        """Collapse sorted dates into (run_start, run_end) intervals of consecutive calendar days."""
        # runs: list of (first_day, last_day), e.g. [(2024-04-01, 2024-04-03), (2024-04-06, 2024-04-08)]
        runs: List[Tuple[date, date]] = []
        for day in days:
            if runs and runs[-1][1] + timedelta(days=1) == day:
                # Extend the current run when this day immediately follows the previous day
                previous_start = runs[-1][0]
                runs[-1] = (previous_start, day)
            else:
                runs.append((day, day))
        return runs
    
    
    class StockDataClient:
        """Client that fetches, validates, deduplicates, and caches daily open/close stock prices."""
    
        def __init__(self, fetch_page: Callable, max_attempts: int = 3,
                     base_delay: float = 0.5, sleep: Callable[[float], None] = time.sleep) -> None:
            if max_attempts < 1:
                raise ValueError("max_attempts must be at least 1")
            if base_delay < 0:
                raise ValueError("base_delay must be non-negative")
            self._fetch_page = fetch_page
            self._max_attempts = max_attempts
            self._base_delay = base_delay
            self._sleep = sleep
            # _prices: {(ticker, day): (open_price, close_price)} for valid trading records
            self._prices: Dict[Tuple[str, date], Tuple[Decimal, Decimal]] = {}
            # _fetched: {(ticker, day)} for all calendar days covered by a completed fetch (including missing days)
            self._fetched: Set[Tuple[str, date]] = set()
    
        def get_price_history(self, ticker: str, start_date: date, end_date: date) -> List[Dict]:
            """Return one row per calendar date in [start_date, end_date], sorted ascending."""
            # Phase 1: Validate inputs and normalize ticker symbol so 'orcl' and 'ORCL' share cache entries
            normalized_ticker = self._check_args(ticker, start_date, end_date)
            all_days = days_between(start_date, end_date)
    
            # Phase 2: Find calendar days not yet fetched and load each contiguous gap from the API
            uncached_days: List[date] = []
            for day in all_days:
                if (normalized_ticker, day) not in self._fetched:
                    uncached_days.append(day)
    
            for run_start, run_end in contiguous_runs(uncached_days):
                self._load_range(normalized_ticker, run_start, run_end)
    
            # Phase 3: Build fresh output rows for every calendar day in ascending order
            rows: List[Dict] = []
            for day in all_days:
                cached_price = self._prices.get((normalized_ticker, day))
                if cached_price is None:
                    rows.append({"date": day, "open": None, "close": None, "status": "missing"})
                else:
                    open_price, close_price = cached_price
                    rows.append({"date": day, "open": open_price, "close": close_price, "status": "ok"})
            return rows
    
        def _check_args(self, ticker: str, start_date: date, end_date: date) -> str:
            if not isinstance(ticker, str) or not ticker.strip():
                raise ValueError("ticker must be a non-empty string")
            for boundary in (start_date, end_date):
                # Reject datetime explicitly: datetime subclasses date, yet datetime != date in dict keys
                if isinstance(boundary, datetime) or not isinstance(boundary, date):
                    raise TypeError("start_date and end_date must be datetime.date objects")
            if start_date > end_date:
                raise ValueError("start_date must not be after end_date")
            return ticker.strip().upper()
    
        def _load_range(self, ticker: str, first: date, last: date) -> None:
            """Download all pages for [first, last], deduplicate, and commit atomically to the cache."""
            raw_records = self._fetch_all_pages(ticker, first, last)
    
            # found: {day: (open_price, close_price)} keeping only the first valid record per in-range date
            found: Dict[date, Tuple[Decimal, Decimal]] = {}
            for raw_record in raw_records:
                parsed = parse_record(raw_record)
                if parsed is None:
                    continue
                day, open_price, close_price = parsed
                # Ignore stray out-of-range dates so we never cache partial data outside [first, last]
                if day < first or day > last:
                    continue
                if day in found:
                    # Duplicate date in API response: keep the first valid record we saw
                    continue
                found[day] = (open_price, close_price)
    
            # Commit to cache only AFTER all pages succeed so a mid-range failure leaves no half-cached state
            for day, price_pair in found.items():
                self._prices[(ticker, day)] = price_pair
            for day in days_between(first, last):
                self._fetched.add((ticker, day))
    
        def _fetch_all_pages(self, ticker: str, first: date, last: date) -> List:
            """Consume paginated API responses until next_page_token is empty or None."""
            records: List = []
            page_token: Optional[str] = None
            # seen_tokens: set of non-empty page tokens already requested, guarding against infinite token loops
            seen_tokens: Set[str] = set()
    
            while True:
                page = self._fetch_with_retry(ticker, first, last, page_token)
                page_items = page.get("data") or []
                records.extend(page_items)
    
                page_token = page.get("next_page_token")
                if not page_token:
                    return records
                if page_token in seen_tokens:
                    raise RuntimeError(f"API repeated page token {page_token!r}")
                seen_tokens.add(page_token)
    
        def _fetch_with_retry(self, ticker: str, first: date, last: date, token: Optional[str]) -> Dict:
            """Fetch a single page, retrying transient errors with exponential backoff."""
            attempt = 0
            while True:
                try:
                    return self._fetch_page(ticker, first, last, token)
                except Exception as error:
                    attempt += 1
                    # Fail immediately on permanent errors (4xx, bugs) or once max_attempts is reached
                    if not is_transient(error) or attempt >= self._max_attempts:
                        raise
                    # Exponential backoff: sleep base_delay * 2^0, base_delay * 2^1, ... between attempts
                    backoff_seconds = self._base_delay * (2 ** (attempt - 1))
                    self._sleep(backoff_seconds)
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Think of StockDataClient like filling in a wall calendar of daily stock prices from a slow mail-order catalog. Whenever someone asks for a stretch of dates, you check which boxes on the calendar are still blank, order catalog pages only for those blank stretches, pencil in the valid prices as exact base-10 decimals, and stamp weekends or holidays as "checked — no trading" so you never waste postage ordering them again.

A naive client that re-downloads [start_date, end_date] from scratch on every call fails in three ways. First, overlapping requests (like asking for January 1–31 right after January 10–20) pay slow network round trips for data you already have, and weekends trigger repeat fetches forever if you only cache days with prices. Second, a single temporary server hiccup on page 8 of 10 crashes the entire call unless you retry individual pages. Third, parsing prices through binary float introduces rounding noise (0.1 + 0.2 == 0.30000000000000004).

Walk through a tiny example: 1. You request ORCL for 2024-04-04 to 2024-04-05. Both days are uncached, so the client fetches one range [04-04, 04-05], stores both Decimal price pairs (124.10/125.85 and 126.00/124.75) in _prices, and marks both dates in _fetched. 2. Next, you request "orcl" for 2024-04-05 to 2024-04-08, where Saturday 04-06 and Sunday 04-07 have no trading. Normalizing to "ORCL" and checking _fetched skips 04-05 and leaves one uncached gap: [04-06, 04-08]. 3. Suppose the first request for [04-06, 04-08] hits an HTTP 503 (transient error — a temporary server or network failure that may succeed on retry). The client waits 0.5 seconds using exponential backoff (doubling the wait time after each consecutive failure), retries that page, keeps the first valid Monday 04-08 record (125.20/127.40), and still marks 04-06 and 04-07 in _fetched (negative caching — recording that a lookup returned nothing so you do not repeat it). 4. Finally, the client walks all four calendar dates in order, emitting 'ok' for 04-05 (from cache), 'missing' for 04-06 and 04-07, and 'ok' for 04-08 (newly fetched).

Complexity

Let D be the number of calendar days in [start_date, end_date], R be the total raw records returned by the API across uncached gaps, and P be the number of API pages fetched.

  • Time: O(D + R) local CPU work, plus at most P * max_attempts network calls. We enumerate the D calendar days once, perform O(1) average hash-set and dictionary lookups per day to find uncached gaps and assemble output rows, and scan the R returned records once to parse Decimal prices and drop duplicates. Because D is at most ~1,827 days for a 5-year range, local work takes under a millisecond and network latency dominates; a fully cached range makes zero API calls.
  • Space: O(D + R) temporary memory per call, plus O(U) persistent memory for the cache, where U is the total number of distinct (ticker, date) pairs ever fetched across the client's lifetime. Each cached day stores at most one tuple in _prices and one entry in _fetched (roughly 1 MB per 5 years of a single ticker in CPython).

Edge cases

  • Single-day range (start_date == end_date): produces a one-element list without off-by-one errors because days_between uses <=.
  • datetime passed instead of date: rejected with TypeError. Although datetime subclasses date, datetime(2024, 4, 4) != date(2024, 4, 4) in dictionary keys, which would break cache lookups.
  • Weekends, holidays, or empty API payloads (data: [] or None): emitted with 'status': 'missing' and None prices, and marked in _fetched so subsequent calls do not re-fetch them.
  • Duplicate dates within or across pages: deduplicated by keeping the first valid record per calendar day; if the first copy for a day is malformed and a second copy is valid, the valid copy wins.
  • Malformed values: NaN, Infinity, zero or negative numbers, booleans (True/False), unparseable strings, missing fields, and non-dict items are safely skipped.
  • Stray out-of-range dates from the API: ignored rather than cached, since we did not request that date's surrounding range.
  • Mid-pagination failure: if page 3 fails all max_attempts retries, nothing from pages 1–2 is committed to _prices or _fetched, leaving the cache clean for a future retry.
  • Repeated pagination token: raises RuntimeError immediately instead of looping infinitely against a broken server.

Common mistakes

  • Calling Decimal(float_val) directly: Decimal(0.1) preserves binary floating-point inaccuracy (0.10000000000000000555...). Always convert floats via Decimal(str(float_val)).
  • Comparing Decimal('NaN') <= 0 before checking is_finite(): unlike floats, comparing a NaN Decimal with <= raises decimal.InvalidOperation.
  • Retrying 4xx client errors: retrying 404 Not Found or 400 Bad Request three times wastes 1.5 seconds of sleep on an error that cannot self-heal.
  • Restarting from page 1 when a later page fails: retry at the single-page helper level with the same page_token so earlier pages are not re-downloaded.
  • Keying the cache by (ticker, start_date, end_date): prevents partial reuse when ranges overlap.
  • Forgetting negative caching: if you only check day in _prices, every weekend and market holiday triggers a new API request on every call.
  • Writing to the cache page by page: if a multi-page fetch fails partway through, marking early pages as fetched makes the unreached dates look permanently missing or half-cached.

Alternative approaches

  • Interval-tree / merged date intervals for _fetched: storing sorted (first, last) intervals per ticker uses O(number of contiguous intervals) memory instead of one set entry per day, at the cost of extra interval-subtraction code. For 5-year ranges (~1,827 days per ticker), a hash set of (ticker, date) is simpler and less bug-prone.
  • Randomized jitter on backoff: in production with many clients, sleeping random.uniform(0, base_delay * 2 ** (attempt - 1)) (jitter — adding randomness to retry delays so synchronized clients do not all retry at the exact same instant) prevents retry waves. Here deterministic delays keep unit tests exact unless a random generator is injected.

Follow-up questions

  • How would you redesign the client to handle multi-threaded callers and batch endpoints that accept several symbols per request? Keep the cache keyed by (ticker, date), compute the uncached (run_start, run_end) gaps for each requested symbol, and group symbols that share overlapping gaps into multi-symbol batch requests. When callers run on multiple threads simultaneously, guard _prices and _fetched with a lock and add single-flight coalescing (a map of in-progress (ticker, run) futures so two threads requesting the same uncached symbol wait on one shared network call rather than issuing duplicates). Bound concurrent outbound requests with a semaphore and treat HTTP 429 Too Many Requests as retryable while respecting its Retry-After header.
  • Once memory usage reaches a fixed budget, which cache eviction strategy fits historical price data best, and how do you keep negative-cache state consistent? Use LRU eviction (Least Recently Used — discarding the items untouched for the longest time once capacity is full), because traffic concentrates on active symbols and recent date windows while historical daily closes are immutable once finalized. Evict in coarse units such as (ticker, year_month) so dropping one bucket reclaims ~30 days with minimal metadata overhead, and always purge _prices and _fetched entries together for that bucket so an evicted trading day never looks 'missing'.
  • What schema and write path would you use to back this cache with a relational database rather than process memory? Define equity_prices(ticker TEXT, day DATE, open NUMERIC, close NUMERIC, status TEXT, fetched_at TIMESTAMP, PRIMARY KEY (ticker, day)), storing exact NUMERIC/DECIMAL columns instead of binary floats and persisting status = 'missing' rows to retain negative caching across restarts. Query SELECT day, open, close, status FROM equity_prices WHERE ticker = ? AND day BETWEEN ? AND ? to locate uncached date intervals, download only the missing runs upstream, and commit each completed run atomically in one transaction via an upsert (INSERT ... ON CONFLICT DO NOTHING so concurrent workers safely insert rows without duplicate-key errors). Pair the table with a small in-memory LRU layer for hot symbols, and avoid permanently caching the current unfinished trading day before market close.

Follow-up questions

Similar questions

More Tradedesk interview questions

All 5 Tradedesk questions →