Handling Market Holidays and Timezones When Querying Stock APIs

Time bugs in a stock app are quiet. The chart shows Friday's close on a Monday and nobody knows why. The error log fills up on Thanksgiving because "no new data" looks like an outage. The server in Frankfurt and the user in Chicago disagree about what "today" means.

None of this is hard, but it is easy to get wrong once. This guide covers what SteadyAPI returns for time, how to ask whether the market is open, how to find holidays without hardcoding a calendar, and how to cache quotes without serving stale prices or wasting requests.

All examples use Python 3.9+ with requests. They use the standard zoneinfo module, so there is nothing extra to install.

What the timestamps mean

  • Unix timestamps are UTC. Candles carry date_utc in epoch seconds. Quotes carry regularMarketTime, the time of the last regular-session trade, in the same format.
  • date is the exchange's local date. Each candle also has date as YYYY-MM-DD in the exchange's time zone. For US stocks that is New York. Use it to group candles by trading day.
  • The zone name is in the quote. exchangeTimezoneName is America/New_York. Load that zone with ZoneInfo and convert. Do not subtract a fixed number of hours. The gmtoffset field is only the offset at the time of the request.
  • A daily candle starts at the open. Its date_utc is 9:30 AM Eastern. Converted with a real time zone, the same time reads as -05:00 in November and -04:00 in March, after daylight saving time starts. A fixed UTC-5 would put the candle an hour off for part of the year.

Ask the API whether the market is open

GET https://api.steadyapi.com/v2/markets/market-info (weight 1) takes no parameters and returns the current U.S. market status. These fields cover most needs:

  • mrktStatus and marketIndicator: the session, such as After-Hours.
  • isTradingHours and isBusinessDay: booleans.
  • previousTradeDate and nextTradeDate: strings like Nov 12, 2026, not ISO dates. Parse them with strptime("%b %d, %Y").
  • marketOpeningTime, marketClosingTime and the pre-market and after-hours times: strings in Eastern Time, such as Nov 11, 2026 09:30 AM ET.
  • openRaw and closeRaw: ISO-style strings with no zone. They are Eastern too, so attach America/New_York yourself.

For a single stock, the quote has marketState as well. Values like REGULAR, PRE and POST tell you which session its price is from.


Find holidays from the data

Do not maintain a holiday list in your code. Exchanges close for reasons a static list will miss. In January 2025, US markets shut for a national day of mourning, and an AAPL daily series shows that weekday with no candle.

The history endpoint already knows. A weekday between the first and last candle with no candle is a day the market was closed. Half days are different: they appear as normal candles, with lower volume.


The script

import time
from datetime import date, datetime, timedelta
from zoneinfo import ZoneInfo

import requests

API_KEY = "YOUR_STEADYAPI_KEY"
BASE = "https://api.steadyapi.com"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}
NY = ZoneInfo("America/New_York")


def get(path, **params):
    r = requests.get(f"{BASE}{path}", headers=HEADERS, params=params, timeout=30)
    r.raise_for_status()
    data = r.json()
    if data.get("success") is False:
        raise RuntimeError(data.get("message", "Request failed"))
    return data


def candles(symbol, interval="1d"):
    body = get("/v1/markets/stock/history", symbol=symbol, interval=interval)["body"]
    # Keys are epoch seconds. Non-numeric keys such as "events" are not candles.
    rows = [v for k, v in body.items() if k.isdigit()]
    return sorted(rows, key=lambda c: c["date_utc"])


def closed_weekdays(rows):
    """Weekdays between the first and last candle with no candle: market holidays."""
    traded = {c["date"] for c in rows}
    day, last, missing = date.fromisoformat(rows[0]["date"]), date.fromisoformat(rows[-1]["date"]), []
    while day <= last:
        if day.weekday() < 5 and day.isoformat() not in traded:
            missing.append(day)
        day += timedelta(days=1)
    return missing


_cache = {}


def cached_quote(symbol):
    hit = _cache.get(symbol)
    if hit and hit["expires"] > time.time():
        return hit["quote"]
    quote = get("/v1/markets/stock/quotes", ticker=symbol)["body"][0]
    ttl = {"REGULAR": 15, "PRE": 60, "POST": 60}.get(quote.get("marketState"), 1800)
    _cache[symbol] = {"quote": quote, "expires": time.time() + ttl}
    return quote


info = get("/v2/markets/market-info")["body"]
print("Status:", info["mrktStatus"], "| business day:", info["isBusinessDay"],
      "| next trade date:", info["nextTradeDate"])

q = cached_quote("AAPL")
tz = ZoneInfo(q["exchangeTimezoneName"])
print("Last trade:", datetime.fromtimestamp(q["regularMarketTime"], tz).isoformat(),
      "| market state:", q["marketState"])

rows = candles("AAPL")
last = rows[-1]
print("Newest daily candle:", last["date"], "starts", datetime.fromtimestamp(last["date_utc"], NY).strftime("%H:%M %Z"))
print("Closed weekdays in range:", [d.isoformat() for d in closed_weekdays(rows)][-5:])

Four things in it deserve a note.

  • candles() skips non-numeric keys. The history body is an object keyed by epoch seconds. With diffandsplits=true it also has an events key for dividends and splits. A loop that treats every key as a candle will crash on it.
  • closed_weekdays() compares date strings. It never touches a time zone, so it cannot drift by a day.
  • cached_quote() picks a lifetime from marketState. 15 seconds during the regular session, 60 seconds in pre-market and after hours, and 30 minutes for any other state. Those numbers are choices, not API rules. Adjust them to your plan and your users.
  • Failed lookups raise. get() checks for "success": false as well as HTTP errors, since a failed lookup can return 200.

Sample output

Status: After-Hours | business day: True | next trade date: Nov 12, 2026
Last trade: 2026-11-11T16:00:01-05:00 | market state: POST
Newest daily candle: 2026-11-11 starts 09:30 EST
Closed weekdays in range: ['2026-04-03', '2026-05-25', '2026-06-19', '2026-07-03', '2026-09-07']

Those five dates are Good Friday, Memorial Day, Juneteenth, the observed Independence Day, and Labor Day. The script found them without a calendar. Your output will show the current day.


Cache with the calendar in mind

  • Quotes: cache by market state, as above. A price that is 15 seconds old in the regular session is normal. A price cached for 15 seconds on a Sunday wastes requests.
  • Daily history: past candles do not change. Fetch a symbol's history once, store it, and refresh after the close. While the market is open, treat the newest candle as in progress.
  • Market status: it changes at known times. Fetch it once, then reuse it until the next session boundary.
  • Count it: quotes cost 2 requests, history 1, and market-info 1. Refreshing one ticker every 15 seconds for a 6.5-hour session is 1,560 quote requests, or 3,120 request units. Poll less often, or batch symbols. One quote call takes up to 200 symbols. See the polling comparison for architecture.

Treat "no data" as information

When a request fails, the API returns a message and "success": false. That is a signal to check what day it is, not to retry. A weekend or holiday request for a calendar date can legitimately return nothing. Retry on 5xx and timeouts, log a failed lookup once, and move on.

The dividend calendar's default date is the next trading day, so you rarely need to compute one yourself. The quotes and history guide covers the history parameters.


Conclusion

Store UTC, convert with the exchange's zone name, take holidays from the data, and let marketState set your cache lifetime. That removes most market-time bugs.

Create a free account at steadyapi.com (no card required) and run the script on your own symbols. Then read the API documentation for every parameter and ready-made examples in cURL, JavaScript, PHP, and Python.