Skip to content
C.W.K.
Stream
Lesson 02 of 05 · published

Ask, Do Not Compute

~12 min · provider, timezone, api-design, fallback

Level 0Raw Ore
0 XP0/36 lessons0/12 achievements
0/100 XP to next level100 XP to go0% complete
The session date is a fact the provider already holds. Every attempt to derive it is a re-implementation of somebody else's calendar.

Three ways to get the date, ranked

Once you accept that the machine's calendar is not the market's, there are three candidate fixes, and only the third one holds.

Subtract a fixed offset. "New York is UTC minus five, so subtract five hours before taking the date." This is wrong twice a year in each direction, and the failures cluster exactly where nobody is looking — the week after a daylight saving transition, in one market but not the others.

Consult an exchange calendar. Better, and now you own a table of exchange hours and holidays for three countries, which is a second source of truth that drifts. You will find out it drifted when a market has an unscheduled half-day.

Ask the provider. The quote already carries the moment it was taken and the name of the exchange's timezone. Converting one through the other yields the session date the exchange itself would use. No table, no offsets, no drift — because the answer comes from the same place as the value it describes.

Derive nothing you can be told. If a payload contains the fact, take the fact. Every derivation is a second implementation of somebody else's rules, and it will diverge from theirs on exactly the days those rules are interesting — holidays, transitions, unscheduled closures. The derived version is not only more code, it is more code that is wrong precisely when it matters.

What the implementation actually does

The function is short and the interesting parts are its edges. It reads two fields — the epoch-second timestamp of the last regular-market moment, and the exchange's timezone name — builds an aware datetime in UTC, converts it into the exchange's zone, and takes the date.

Note that it does not convert into the server's zone. The intermediate representation is UTC because that is unambiguous, but the destination is the exchange, because the exchange is who defines what session this is.

The fallback is where honesty lives

The function returns None when the provider is silent — no timestamp, no zone name, or an unparseable one. It does not guess. Its docstring then says callers fall back to the UTC date and say so, rather than inventing a calendar.

That last clause is the whole discipline in miniature. A fallback that is indistinguishable from the real thing is not a fallback, it is a silent downgrade — and downgrades that leave no trace are how a system's accuracy erodes without anybody being able to point at the moment it happened.

And in this codebase, that clause is not implemented. The caller substitutes a fallback date and stores the provider's original source string unchanged, so a fallback-dated row is byte-identical in provenance to a provider-dated one. The honest half — returning None instead of guessing — is real and load-bearing. The disclosure half exists only in the docstring. Which is the sharpest lesson available here and the reason it is worth showing you the gap rather than the tidy version: a comment describing what the code does is a claim, not evidence. This one has been quoted, believed, and repeated — including, in an earlier draft, by this lesson.

Catch narrowly, and know why each one is there. The conversion catches four specific errors — an out-of-range timestamp, an overflow, a bad value, and an unknown timezone name. That is a list somebody thought about, not a bare except. Each entry corresponds to a real thing a provider can send you, and the narrowness means a genuinely unexpected failure still surfaces instead of being flattened into a None.

Code

The session date, asked rather than computed·python
def listing_close_date(info: dict[str, Any]) -> str | None:
    """The session date a quote actually belongs to -- asked of the
    provider, never computed from this machine's clock.

    Measured 2026-08-06 05:49 UTC: a US ETF proxy -> 2026-08-05
    (New York), a Tokyo-listed ETF -> 2026-08-06 (Tokyo). Two
    different session dates at one instant, which is exactly why a
    single local date cannot be right for both.

    Returns None when the provider is silent -- callers then fall
    back to the UTC date AND SAY SO, rather than inventing a
    calendar."""
    stamp = info.get("regularMarketTime")      # epoch seconds
    zone = info.get("exchangeTimezoneName")    # e.g. "America/New_York"
    if not isinstance(stamp, (int, float)) or not zone:
        return None
    try:
        moment = datetime.datetime.fromtimestamp(
            float(stamp), datetime.UTC)
        return moment.astimezone(
            zoneinfo.ZoneInfo(str(zone))).date().isoformat()
    except (OSError, OverflowError, ValueError,
            zoneinfo.ZoneInfoNotFoundError):
        return None

External links

Exercise

Find a value your code derives that the upstream payload could have told you directly — a date, a currency, a unit, a status. Replace the derivation with the field, and handle the case where the field is absent by returning an explicit unknown rather than falling through to your derivation. Then check whether any caller silently papers over that unknown; that is usually where the real bug is hiding.
Hint
The giveaway is a constant in your code that encodes somebody else's policy: an offset, a market close time, a rounding rule, a currency assumption. Every one of those is a copy of a fact that lives somewhere authoritative, and copies go stale on the schedule of the original, not yours.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.