Diurn
Docs / python

Python client

pip install diurn, version 0.1.0, Python >=3.12. Exchange calendars and trading hours from the Diurn API. The guide and the reference below are generated from the package itself, so they describe exactly this version.

Guide

Exchange calendars and trading hours for the world's markets, from the Diurn API, with an exchange_calendars-style interface.

pip install diurn            # the client and diurn.py: standard library only
pip install 'diurn[pd]'      # the Pandas flavor, also diurn.get_calendar
pip install 'diurn[sf]'      # the StaticFrame flavor

Nothing imports Pandas, StaticFrame, or NumPy until its flavor is used.

An API key is free at https://diurn.io/signin/; set DIURN_API_KEY.

import diurn

xnys = diurn.get_calendar('XNYS')
xnys.is_session('2026-11-26')  # False: Thanksgiving
xnys.next_session('2026-11-25')  # Timestamp('2026-11-27 00:00:00')
xnys.sessions_in_range('2026-11-01', '2026-11-30')  # DatetimeIndex
xnys.is_open_at_time('2026-11-27T18:30:00Z')  # False: an early close at 13:00
xnys.next_close('2026-11-27T15:00:00Z')  # Timestamp('2026-11-27 13:00:00-0500', tz='America/New_York')
xnys.schedule('2026-11-01', '2026-11-30')  # open, break_start, break_end, close, kind, verification, reason

Three flavors, one calendar

The same calendar, with the same methods, in three sets of types:

session range of sessions schedule instants
diurn / diurn.pd (diurn[pd]) pd.Timestamp pd.DatetimeIndex pd.DataFrame aware pd.Timestamp, venue's zone
diurn.sf (diurn[sf]) np.datetime64[D] sf.IndexDate sf.Frame np.datetime64[s], UTC
diurn.py datetime.date list[date] list[ScheduleRow] aware datetime, venue's zone
import diurn.sf as dsf

dsf.get_calendar('XTKS').schedule('2026-11-02', '2026-11-06')  # sf.Frame

import diurn.py as dpy

dpy.get_calendar('XHKG').next_session('2026-12-24')  # datetime.date(2026, 12, 28)

Every method accepts dates as datetime.date, ISO strings, pandas Timestamps or NumPy datetime64, and instants as aware datetimes, aware Timestamps, or ISO strings with an offset. A naive datetime is refused: it is not an instant.

The interface

is_session, sessions_in_range, next_session, previous_session, date_to_session(direction=), sessions_window, sessions_distance, next_open, next_close, is_open_at_time, session_open, session_close, session_break_start, session_break_end and schedule, as in exchange_calendars, with these differences:

  • A session is a day the venue trades, as the API's /v1/trading-days counts one: open, early_close, open_for_some, and a holiday that carries a session, such as NSE's Muhurat.
  • unknown is neither open nor closed. Past what Diurn can answer, a method that depends on such a day raises diurn.Indeterminate. Pass on_unknown="missing" to get None (or NaT) instead; ranges then leave the day out.
  • Instants keep the venue's zone, in the Pandas and plain flavors. They compare equal to UTC ones.
  • schedule(start, end) is a method over a range, since the calendar is answered by an API rather than precomputed. It adds kind, verification and reason; all_days=True keeps holidays and unknown days as rows.
  • next_session and previous_session take any date, not only a session.
  • A session's times are None (or NaT) where Diurn holds no hours for it, a day known to trade whose hours are not published; a date that is not a session is a ValueError, as in exchange_calendars.
  • sessions_distance over a range with an unknown day raises, or with on_unknown="missing" is None: a count that skipped the day would be wrong.
  • Product schedules. Where a venue keeps several (calendar.products), get_calendar(mic, product=...) picks one; by default the whole venue's sessions are used. A product with no hours of its own has none: it is never given another product's.
  • name is the MIC, as exchange_calendars names a calendar by its code; the registry's name is market_name. tz is the IANA name, a string, where exchange_calendars has a ZoneInfo.

The API

diurn.Client has one method per API operation and returns typed models: venue search, multi-venue status, exceptions, trading-day arithmetic, usage.

client = diurn.Client()  # DIURN_API_KEY, DIURN_API_URL
client.statuses(['XNYS', 'XLON', 'XTKS'])  # whether each is trading now
client.usage()  # your plan's meters

Retries are off by default. Client(retries=3) retries what waiting can fix: a rate limit, after the server's Retry-After; a 503 or a dropped connection, backing off from half a second. A plan's refusal (a MIC cap, a date outside the window) is never retried, and a wait longer than max_wait seconds (60) is raised rather than slept. A calendar retries as its client does: diurn.get_calendar('XNYS', client=diurn.Client(retries=3)).

diurn.AsyncClient has the same methods as coroutines, for an event loop. It needs nothing beyond the standard library: each call runs the client in a worker thread, so calls made together run together.

client = diurn.AsyncClient()
statuses = await asyncio.gather(*(client.status(mic) for mic in ('XNYS', 'XLON')))

Errors

Typed, never prose: AuthError (no or inactive key), UnknownVenue, OutOfWindow (with allowed_from and allowed_to), NotInPlan, MicCapExceeded (with mics_in_use and resets_at), RateLimited (with retry_after), Indeterminate and TransportError, all under diurn.DiurnError. Every plan refusal is an OverLimit with limit and resets_at. Indeterminate is raised the same whether the calendar met an unknown day or the API did (its 422, as IndeterminateResponse, also an ApiError); a stepping method that finds no session within 800 days raises it too.

Caching

Responses are cached on disk by MIC, range and the dataset the server serves. The dataset is checked against the free /health endpoint every few minutes, so a cached answer is reused exactly as long as it is still the answer, and a repeat query makes no metered request. The directory is DIURN_CACHE_DIR, or the platform's own cache directory: ~/Library/Caches/diurn on macOS, %LOCALAPPDATA%\diurn\Cache on Windows, and $XDG_CACHE_HOME/diurn or ~/.cache/diurn elsewhere (XDG_CACHE_HOME is honoured on any platform where it is set). get_calendar(..., cache=False) turns it off.

License

MIT or Apache-2.0, at your option.

Calendars

One venue's calendar in each of three flavors: the same methods, different types. diurn.get_calendar is the pandas flavor.

diurn.pd.get_calendarfunction

def diurn.pd.get_calendar(mic: str, *, client: Client | None = None, on_unknown: OnUnknown = 'raise', product: str | None = None, cache: bool = True, as_of: datetime.datetime | str | None = None) -> Calendar

The calendar for a MIC, in pandas types. The key is DIURN_API_KEY unless client carries one.

diurn.pd.Calendarclass

class diurn.pd.Calendar
    __init__(core: Calendar)

A venue's trading calendar in pandas types. core is the plain-Python calendar underneath, for its Day objects and anything not wrapped here.

  • micproperty
    mic: str

    The venue's ISO 10383 MIC.

  • nameproperty
    name: str

    The MIC, as exchange_calendars names a calendar by its code.

  • market_nameproperty
    market_name: str

    The venue's name in the ISO 10383 registry.

  • productsproperty
    products: tuple[str, ...]

    The product schedules the venue keeps; empty for almost every one.

  • tzproperty
    tz: str

    The IANA zone the venue's sessions are quoted in.

  • is_sessionmethod
    def is_session(date: object) -> bool | None
  • sessions_in_rangemethod
    def sessions_in_range(start: object, end: object) -> DatetimeIndex

    The sessions from start to end, inclusive. An unknown day raises, or with on_unknown="missing" is left out (it is not a session, and not a closure either).

  • next_sessionmethod
    def next_session(date: object) -> Timestamp

    The first session after date. Unlike exchange_calendars, date need not be a session.

  • previous_sessionmethod
    def previous_session(date: object) -> Timestamp

    The last session before date; date need not be a session.

  • date_to_sessionmethod
    def date_to_session(date: object, direction: str = 'none') -> Timestamp

    date if it is a session; otherwise the next or previous one, or (direction="none") a ValueError.

  • sessions_windowmethod
    def sessions_window(session: object, count: int) -> DatetimeIndex

    abs(count) sessions from session: forwards for a positive count, backwards (ending at session) for a negative one. session must be a session.

  • is_open_at_timemethod
    def is_open_at_time(when: object) -> bool | None

    Whether a session is running at the instant, outside its breaks.

  • next_openmethod
    def next_open(when: object) -> Timestamp

    The first session open after the instant.

  • next_closemethod
    def next_close(when: object) -> Timestamp

    The first session close after the instant.

  • session_openmethod
    def session_open(session: object) -> Timestamp

    The session's first open, in the venue's zone; NaT where its hours are not held.

  • session_closemethod
    def session_close(session: object) -> Timestamp

    The session's last close; None where its hours are not held.

  • session_break_startmethod
    def session_break_start(session: object) -> Timestamp

    The start of the session's break (Tokyo's lunch); None without one.

  • session_break_endmethod
    def session_break_end(session: object) -> Timestamp

    The end of the session's break; None without one.

  • sessions_distancemethod
    def sessions_distance(start: object, end: object) -> int | None

    The number of sessions from start to end, both included; negative when end is before start, as in exchange_calendars. An unknown day in the range raises, or with on_unknown="missing" makes the answer None: a count that skipped it would be wrong, not partial.

  • schedulemethod
    def schedule(start: object, end: object, *, all_days: bool = False) -> DataFrame

    One row per session (or per day, with all_days=True): open, break_start, break_end, close as aware Timestamps in the venue's zone, then kind, verification and reason.

diurn.sf.get_calendarfunction

def diurn.sf.get_calendar(mic: str, *, client: Client | None = None, on_unknown: OnUnknown = 'raise', product: str | None = None, cache: bool = True, as_of: datetime.datetime | str | None = None) -> Calendar

The calendar for a MIC, in StaticFrame types.

diurn.sf.Calendarclass

class diurn.sf.Calendar
    __init__(core: Calendar)

A venue's trading calendar in StaticFrame types. core is the plain-Python calendar underneath.

  • micproperty
    mic: str

    The venue's ISO 10383 MIC.

  • nameproperty
    name: str

    The MIC, as exchange_calendars names a calendar by its code.

  • market_nameproperty
    market_name: str

    The venue's name in the ISO 10383 registry.

  • productsproperty
    products: tuple[str, ...]

    The product schedules the venue keeps; empty for almost every one.

  • tzproperty
    tz: str

    The IANA zone the venue's sessions are quoted in.

  • is_sessionmethod
    def is_session(date: object) -> bool | None
  • sessions_in_rangemethod
    def sessions_in_range(start: object, end: object) -> IndexDate

    The sessions from start to end, inclusive. An unknown day raises, or with on_unknown="missing" is left out (it is not a session, and not a closure either).

  • next_sessionmethod
    def next_session(date: object) -> np.datetime64

    The first session after date. Unlike exchange_calendars, date need not be a session.

  • previous_sessionmethod
    def previous_session(date: object) -> np.datetime64

    The last session before date; date need not be a session.

  • date_to_sessionmethod
    def date_to_session(date: object, direction: str = 'none') -> np.datetime64

    date if it is a session; otherwise the next or previous one, or (direction="none") a ValueError.

  • sessions_windowmethod
    def sessions_window(session: object, count: int) -> IndexDate

    abs(count) sessions from session: forwards for a positive count, backwards (ending at session) for a negative one. session must be a session.

  • is_open_at_timemethod
    def is_open_at_time(when: object) -> bool | None

    Whether a session is running at the instant, outside its breaks.

  • next_openmethod
    def next_open(when: object) -> np.datetime64

    The first session open after the instant.

  • next_closemethod
    def next_close(when: object) -> np.datetime64

    The first session close after the instant.

  • session_openmethod
    def session_open(session: object) -> np.datetime64

    The session's first open, in UTC; NaT where its hours are not held.

  • session_closemethod
    def session_close(session: object) -> np.datetime64

    The session's last close; None where its hours are not held.

  • session_break_startmethod
    def session_break_start(session: object) -> np.datetime64

    The start of the session's break (Tokyo's lunch); None without one.

  • session_break_endmethod
    def session_break_end(session: object) -> np.datetime64

    The end of the session's break; None without one.

  • sessions_distancemethod
    def sessions_distance(start: object, end: object) -> int | None

    The number of sessions from start to end, both included; negative when end is before start, as in exchange_calendars. An unknown day in the range raises, or with on_unknown="missing" makes the answer None: a count that skipped it would be wrong, not partial.

  • schedulemethod
    def schedule(start: object, end: object, *, all_days: bool = False) -> Frame

    One row per session (or per day, with all_days=True): open, break_start, break_end, close in UTC, then kind, verification and reason.

diurn.py.get_calendarfunction

def diurn.py.get_calendar(mic: str, *, client: Client | None = None, on_unknown: OnUnknown = 'raise', product: str | None = None, cache: bool = True, as_of: datetime.datetime | str | None = None) -> Calendar

The calendar for a MIC. The key is DIURN_API_KEY unless client carries one.

diurn.py.Calendarclass

class diurn.py.Calendar
    __init__(mic: str, client: Client | None = None, *, on_unknown: OnUnknown = 'raise', product: str | None = None, cache: bool | DiskCache = True, as_of: datetime.datetime | str | None = None)

One venue's trading calendar, answered by the Diurn API.

product picks one product schedule where a venue keeps several (see products); by default the sessions for the whole venue are used, or, on a venue whose every session is scoped to products, all of them.

  • daymethod
    def day(date: object) -> Day

    The day, whatever its kind.

  • days_in_rangemethod
    def days_in_range(start: object, end: object) -> list[Day]

    Every day from start to end, inclusive.

  • is_sessionmethod
    def is_session(date: object) -> bool | None
  • sessions_in_rangemethod
    def sessions_in_range(start: object, end: object) -> list[datetime.date]

    The sessions from start to end, inclusive. An unknown day raises, or with on_unknown="missing" is left out (it is not a session, and not a closure either).

  • next_sessionmethod
    def next_session(date: object) -> datetime.date | None

    The first session after date. Unlike exchange_calendars, date need not be a session.

  • previous_sessionmethod
    def previous_session(date: object) -> datetime.date | None

    The last session before date; date need not be a session.

  • date_to_sessionmethod
    def date_to_session(date: object, direction: Literal['none', 'next', 'previous'] = 'none') -> datetime.date | None

    date if it is a session; otherwise the next or previous one, or (direction="none") a ValueError.

  • sessions_windowmethod
    def sessions_window(session: object, count: int) -> list[datetime.date]

    abs(count) sessions from session: forwards for a positive count, backwards (ending at session) for a negative one. session must be a session.

  • is_open_at_timemethod
    def is_open_at_time(when: object) -> bool | None

    Whether a session is running at the instant, outside its breaks.

  • next_openmethod
    def next_open(when: object) -> datetime.datetime | None

    The first session open after the instant.

  • next_closemethod
    def next_close(when: object) -> datetime.datetime | None

    The first session close after the instant.

  • schedulemethod
    def schedule(start: object, end: object, *, all_days: bool = False) -> list[ScheduleRow]

    One row per session from start to end; with all_days=True, one per day, so holidays and unknown days appear with their kind and no times.

  • session_openmethod
    def session_open(session: object) -> datetime.datetime | None

    The session's first open. None where Diurn holds no hours for it (a day known to trade whose hours are not published).

  • session_closemethod
    def session_close(session: object) -> datetime.datetime | None

    The session's last close; None where its hours are not held.

  • session_break_startmethod
    def session_break_start(session: object) -> datetime.datetime | None

    The start of the session's break (Tokyo's lunch); None without one.

  • session_break_endmethod
    def session_break_end(session: object) -> datetime.datetime | None

    The end of the session's break; None without one.

  • sessions_distancemethod
    def sessions_distance(start: object, end: object) -> int | None

    The number of sessions from start to end, both included; negative when end is before start, as in exchange_calendars. An unknown day in the range raises, or with on_unknown="missing" makes the answer None: a count that skipped it would be wrong, not partial.

Days and schedules

The plain-Python records the calendars are built from.

diurn.Daydataclass

class diurn.Day

Day(date: 'datetime.date', kind: 'str', verification: 'str', reason: 'str | None', sessions: 'tuple[Session, ...]')

datedatetime.date
kindstr
verificationstr
reasonstr | None
sessionstuple[Session, ...]
  • is_unknownproperty
    is_unknown: bool
  • is_sessionproperty
    is_session: bool

    Whether the venue trades: as /v1/trading-days reads a day. A holiday trades if it carries a session, which is Muhurat.

diurn.Sessiondataclass

class diurn.Session

One session: its open and close as aware datetimes in the venue's zone, its breaks, and the product it is for, in the venue's own words (None: the whole venue). The names are those in Calendar.products.

namestr
opendatetime.datetime
closedatetime.datetime
breakstuple[tuple[datetime.datetime, datetime.datetime], ...]
productsstr | None
verificationstr

diurn.ScheduleRowdataclass

class diurn.ScheduleRow

A day's schedule, as exchange_calendars lays it out: the first open, the last close, and the first break between them; plus Diurn's kind, verification and reason.

datedatetime.date
opendatetime.datetime | None
break_startdatetime.datetime | None
break_enddatetime.datetime | None
closedatetime.datetime | None
kindstr
verificationstr
reasonstr | None
  • to_utcmethod
    def to_utc() -> ScheduleRowUTC

    The row with its instants in UTC, as whole seconds since the Unix epoch, for a frame type that has no time zones (NumPy's datetime64, so StaticFrame).

diurn.ScheduleRowUTCdataclass

class diurn.ScheduleRowUTC

A ScheduleRow with its instants in UTC, and without its date: one record of a frame indexed by session. Its fields, in order, are the frame's columns.

Instants are whole seconds since the Unix epoch, not datetimes: that is what a datetime64[s] holds, so NumPy takes them as they are rather than converting an object per value (a third faster for a schedule). Sessions are quoted to the minute, so nothing is lost.

openint | None
break_startint | None
break_endint | None
closeint | None
kindstr
verificationstr
reasonstr | None

The API client

One method per API operation, returning the response models below.

diurn.Clientclass

class diurn.Client
    __init__(api_key: str | None = None, base_url: str | None = None, timeout: float = 30.0, send: Send | None = None, retries: int = 0, max_wait: float = 60.0)

A connection to the Diurn API.

api_key defaults to DIURN_API_KEY, and base_url to DIURN_API_URL or https://api.diurn.io. Every endpoint but the registry record, /health and the OpenAPI document needs a key; a free one is at https://diurn.io/signin/.

retries (default 0) retries a request the server asks to be repeated later (rate_limited, after its Retry-After) or that failed in transit (a 503, a dropped connection), waiting at most max_wait seconds at a time. A plan's refusal is never retried.

  • last_headersproperty
    last_headers: dict[str, str]

    The headers of the last response, lower-cased: the usage headers (diurn-mics-day, ratelimit-remaining, ...) and x-diurn-dataset.

  • healthmethod
    def health() -> Health
  • venuemethod
    def venue(mic: str) -> VenueResponse

    The ISO 10383 record, with the venue's zone and how it is answered. Free and unmetered.

  • venuesmethod
    def venues(q: str | None = None, country: str | None = None, resolution: str | None = None, status: str | None = None, limit: int | None = None, cursor: str | None = None) -> VenuesResponse

    List and search venues. Free and unmetered.

  • usagemethod
    def usage() -> UsageView

    Your usage against your plan. Needs a key; never metered.

  • sessionsmethod
    def sessions(mic: str, start: DateLike, end: DateLike, *, kinds: Sequence[str] | None = None, provenance: bool = False, as_of: InstantLike | None = None) -> DaysResponse

    Every day from start to end, inclusive, with its sessions.

  • daymethod
    def day(mic: str, date: DateLike, *, as_of: InstantLike | None = None) -> DayResponse

    One day, with its provenance in full.

  • statusmethod
    def status(mic: str, at: InstantLike | None = None, *, as_of: InstantLike | None = None) -> StatusResponse

    Whether the venue is trading at an instant (now, if at is None).

  • next_openmethod
    def next_open(mic: str, start: InstantLike, *, as_of: InstantLike | None = None) -> InstantResponse
  • next_closemethod
    def next_close(mic: str, start: InstantLike, *, as_of: InstantLike | None = None) -> InstantResponse
  • next_trading_daymethod
    def next_trading_day(mic: str, start: DateLike, n: int = 1, *, inclusive: bool = False, on_unknown: OnUnknown = 'error', as_of: InstantLike | None = None) -> StepResponse
  • previous_trading_daymethod
    def previous_trading_day(mic: str, start: DateLike, n: int = 1, *, inclusive: bool = False, on_unknown: OnUnknown = 'error', as_of: InstantLike | None = None) -> StepResponse
  • count_trading_daysmethod
    def count_trading_days(mic: str, start: DateLike, end: DateLike, *, as_of: InstantLike | None = None) -> CountResponse

    Trading days from start to end, inclusive; a lower bound where unknown is above zero.

  • statusesmethod
    def statuses(mics: Sequence[str], at: InstantLike | None = None, *, as_of: InstantLike | None = None) -> StatusesResponse

    Whether several venues are trading at an instant (now, if None).

  • exceptionsmethod
    def exceptions(mics: Sequence[str], start: DateLike, end: DateLike, *, kinds: Sequence[str] | None = None, as_of: InstantLike | None = None) -> ExceptionsResponse

    Holidays and irregular days across venues, one row each.

  • sessions_bulkmethod
    def sessions_bulk(mics: Sequence[str], start: DateLike, end: DateLike, *, as_of: InstantLike | None = None) -> BulkResponse

    Many venues over a range, column-oriented.

  • trading_daysmethod
    def trading_days(mics: Sequence[str], start: DateLike, end: DateLike, *, as_of: InstantLike | None = None) -> TradingDaysResponse

    A date-and-boolean series per venue; None where it cannot say.

  • joint_next_trading_daymethod
    def joint_next_trading_day(mics: Sequence[str], start: DateLike, n: int = 1, *, mode: Mode = 'all', inclusive: bool = False, on_unknown: OnUnknown = 'error', as_of: InstantLike | None = None) -> JointStepResponse

    The nth date after start on which all (or any) of the venues trade.

  • joint_previous_trading_daymethod
    def joint_previous_trading_day(mics: Sequence[str], start: DateLike, n: int = 1, *, mode: Mode = 'all', inclusive: bool = False, on_unknown: OnUnknown = 'error', as_of: InstantLike | None = None) -> JointStepResponse

diurn.AsyncClientclass

class diurn.AsyncClient
    __init__(api_key: str | None = None, base_url: str | None = None, timeout: float = 30.0, send: Send | None = None, retries: int = 0, max_wait: float = 60.0)

The same operations as Client, as coroutines.

client = diurn.AsyncClient()
statuses = await asyncio.gather(*(client.status(m) for m in mics))

Standard library only: each call runs the synchronous client in a worker thread (asyncio.to_thread), so requests made together run together, as many at once as the default executor has threads. The arguments are Client's, and client is the Client underneath. last_headers is that of whichever call finished last.

  • last_headersproperty
    last_headers: dict[str, str]
  • healthasync method
    async def health() -> Health
  • venueasync method
    async def venue(mic: str) -> VenueResponse

    The ISO 10383 record, with the venue's zone and how it is answered. Free and unmetered.

  • venuesasync method
    async def venues(q: str | None = None, country: str | None = None, resolution: str | None = None, status: str | None = None, limit: int | None = None, cursor: str | None = None) -> VenuesResponse

    List and search venues. Free and unmetered.

  • usageasync method
    async def usage() -> UsageView

    Your usage against your plan. Needs a key; never metered.

  • sessionsasync method
    async def sessions(mic: str, start: DateLike, end: DateLike, *, kinds: Sequence[str] | None = None, provenance: bool = False, as_of: InstantLike | None = None) -> DaysResponse

    Every day from start to end, inclusive, with its sessions.

  • dayasync method
    async def day(mic: str, date: DateLike, *, as_of: InstantLike | None = None) -> DayResponse

    One day, with its provenance in full.

  • statusasync method
    async def status(mic: str, at: InstantLike | None = None, *, as_of: InstantLike | None = None) -> StatusResponse

    Whether the venue is trading at an instant (now, if at is None).

  • next_openasync method
    async def next_open(mic: str, start: InstantLike, *, as_of: InstantLike | None = None) -> InstantResponse
  • next_closeasync method
    async def next_close(mic: str, start: InstantLike, *, as_of: InstantLike | None = None) -> InstantResponse
  • next_trading_dayasync method
    async def next_trading_day(mic: str, start: DateLike, n: int = 1, *, inclusive: bool = False, on_unknown: OnUnknown = 'error', as_of: InstantLike | None = None) -> StepResponse
  • previous_trading_dayasync method
    async def previous_trading_day(mic: str, start: DateLike, n: int = 1, *, inclusive: bool = False, on_unknown: OnUnknown = 'error', as_of: InstantLike | None = None) -> StepResponse
  • count_trading_daysasync method
    async def count_trading_days(mic: str, start: DateLike, end: DateLike, *, as_of: InstantLike | None = None) -> CountResponse

    Trading days from start to end, inclusive; a lower bound where unknown is above zero.

  • statusesasync method
    async def statuses(mics: Sequence[str], at: InstantLike | None = None, *, as_of: InstantLike | None = None) -> StatusesResponse

    Whether several venues are trading at an instant (now, if None).

  • exceptionsasync method
    async def exceptions(mics: Sequence[str], start: DateLike, end: DateLike, *, kinds: Sequence[str] | None = None, as_of: InstantLike | None = None) -> ExceptionsResponse

    Holidays and irregular days across venues, one row each.

  • sessions_bulkasync method
    async def sessions_bulk(mics: Sequence[str], start: DateLike, end: DateLike, *, as_of: InstantLike | None = None) -> BulkResponse

    Many venues over a range, column-oriented.

  • trading_daysasync method
    async def trading_days(mics: Sequence[str], start: DateLike, end: DateLike, *, as_of: InstantLike | None = None) -> TradingDaysResponse

    A date-and-boolean series per venue; None where it cannot say.

  • joint_next_trading_dayasync method
    async def joint_next_trading_day(mics: Sequence[str], start: DateLike, n: int = 1, *, mode: Mode = 'all', inclusive: bool = False, on_unknown: OnUnknown = 'error', as_of: InstantLike | None = None) -> JointStepResponse

    The nth date after start on which all (or any) of the venues trade.

  • joint_previous_trading_dayasync method
    async def joint_previous_trading_day(mics: Sequence[str], start: DateLike, n: int = 1, *, mode: Mode = 'all', inclusive: bool = False, on_unknown: OnUnknown = 'error', as_of: InstantLike | None = None) -> JointStepResponse

Errors

Every error the package raises is a diurn.DiurnError.

diurn.DiurnErrorexception

class diurn.DiurnError(Exception)

Every error this package raises.

diurn.ApiErrorexception

class diurn.ApiError(DiurnError)
    __init__(status: int, error: str, message: str, body: dict[str, Any] | None = None)

The API answered with an error.

error is the API's stable tag; status the HTTP status; body the response as sent, for anything not lifted into an attribute.

diurn.Indeterminateexception

class diurn.Indeterminate(DiurnError)
    __init__(mic: str, date: datetime.date, message: str = '')

Diurn cannot say whether the market trades on a date.

Raised when an answer would depend on an unknown day (past what Diurn can answer). Diurn never reports such a day as closed or open; pass on_unknown="missing" to get a missing value instead of this error.

diurn.TransportErrorexception

class diurn.TransportError(DiurnError)

The API could not be reached, or answered with something that is not the API (a proxy's page, a broken connection).

diurn.AuthErrorexception

class diurn.AuthError(ApiError)
    __init__(status: int, error: str, message: str, body: dict[str, Any] | None = None)

No key (needs_key), or a key that is not active (unauthorized).

Keys are free at https://diurn.io/signin/; set DIURN_API_KEY or pass api_key=.

diurn.errors.BadRequestexception

class diurn.errors.BadRequest(ApiError)
    __init__(status: int, error: str, message: str, body: dict[str, Any] | None = None)

The request could not be understood: a malformed date, too many days, or as_of outside the archive's record.

diurn.OverLimitexception

class diurn.OverLimit(ApiError)
    __init__(status: int, error: str, message: str, body: dict[str, Any] | None = None)

A refusal from the plan's limits. limit is {kind, used, max} where the API sends it; resets_at when the limit eases; upgrade where to get more.

diurn.errors.Unavailableexception

class diurn.errors.Unavailable(ApiError)
    __init__(status: int, error: str, message: str, body: dict[str, Any] | None = None)

The service could not answer just now (503), for example an as_of dataset that could not be loaded.

diurn.UnknownVenueexception

class diurn.UnknownVenue(ApiError)
    __init__(status: int, error: str, message: str, body: dict[str, Any] | None = None)

No such MIC, or no calendar answers it.

diurn.errors.IndeterminateResponseexception

class diurn.errors.IndeterminateResponse(ApiError, Indeterminate)
    __init__(status: int, error: str, message: str, body: dict[str, Any] | None = None)

The API's 422 indeterminate: a trading-day walk reached a date it cannot answer (Client.next_trading_day and the joint steps, with on_unknown="error"). An Indeterminate, so one except catches it whether the calendar or the API found the day; date is that day, and mic is empty, since the API names the date only.

diurn.MicCapExceededexception

class diurn.MicCapExceeded(OverLimit)
    __init__(status: int, error: str, message: str, body: dict[str, Any] | None = None)

Asking for this MIC would exceed a unique-MIC cap (429). mics_in_use are the MICs holding the window's slots; asking again for one of them is free.

diurn.NotInPlanexception

class diurn.NotInPlan(OverLimit)
    __init__(status: int, error: str, message: str, body: dict[str, Any] | None = None)

The plan does not include this: an endpoint, provenance or as_of (403).

diurn.OutOfWindowexception

class diurn.OutOfWindow(OverLimit)
    __init__(status: int, error: str, message: str, body: dict[str, Any] | None = None)

Dates outside the plan's window (403). allowed_from and allowed_to are the dates the plan may ask about; None is unbounded.

diurn.RateLimitedexception

class diurn.RateLimited(OverLimit)
    __init__(status: int, error: str, message: str, body: dict[str, Any] | None = None, retry_after: float | None = None)

Too many requests a minute (429). retry_after is the server's Retry-After, in seconds, where it sent one.

Response models

What Client returns: generated from the API's OpenAPI document, one frozen dataclass per response shape.

DayKindDtoliteral

DayKindDto = Literal['open', 'weekend', 'holiday', 'early_close', 'open_for_some', 'unknown']

OverLimitErrorliteral

OverLimitError = Literal['not_in_plan', 'out_of_window', 'mic_cap_exceeded', 'rate_limited']

StateDtoliteral

StateDto = Literal['running', 'closed', 'unknown']

VerificationDtoliteral

VerificationDto = Literal['verified', 'corroborated', 'inferreddefinitional', 'inferredpredictive', 'inferredadvisory']

ApiErrordataclass

class ApiError

Typed, because SPEC: client-shared-surface requires every client to distinguish auth failure from an unknown calendar from an out-of-range query, and it cannot if the server returns prose.

errorstr
messagestr

BreakDtodataclass

class BreakDto

BreakDto(end: 'str', start: 'str')

endstr
startstr

BulkBodydataclass

class BulkBody

BulkBody(from_: 'datetime.date', to: 'datetime.date', as_of: 'str | None' = None, mics: 'tuple[str, ...]' = ())

from_datetime.date
todatetime.date
as_ofstr | None= None
micstuple[str, ...]= ()

BulkCalendardataclass

class BulkCalendar

BulkCalendar(kinds: 'str', verification: 'str')

kindsstr
verificationstr

BulkResponsedataclass

class BulkResponse

Column-oriented: the dates once, then one short code per day per calendar.

datestuple[datetime.date, ...]
from_datetime.date
legendLegend
todatetime.date
venuesdict[str, BulkCalendar]
as_ofstr | None= None
datasetDatasetServed | None= None

CountResponsedataclass

class CountResponse

CountResponse(count: 'int', from_: 'datetime.date', mic: 'str', to: 'datetime.date', unknown: 'int', as_of: 'str | None' = None, dataset: 'DatasetServed | None' = None)

countint
from_datetime.date
micstr
todatetime.date
unknownint
as_ofstr | None= None
datasetDatasetServed | None= None

DataWindowdataclass

class DataWindow

The dates the plan may ask about, from today (UTC). Null is unbounded.

from_datetime.date | None= None
todatetime.date | None= None

DatasetServeddataclass

class DatasetServed

The dataset that answered an as_of request (SPEC-pricing §5.1).

idstr
reconstructedbool
served_fromstr
served_untilstr | None= None

DayDtodataclass

class DayDto

DayDto(date: 'datetime.date', kind: 'DayKindDto', verification: 'VerificationDto', products: 'ProductSplitDto | None' = None, provenance: 'Provenance | None' = None, reason: 'str | None' = None, sessions: 'tuple[SessionDto, ...]' = ())

datedatetime.date
kindDayKindDto
verificationVerificationDto
productsProductSplitDto | None= None
provenanceProvenance | None= None
reasonstr | None= None
sessionstuple[SessionDto, ...]= ()

DayResponsedataclass

class DayResponse

One day, and with as_of, which dataset answered.

datedatetime.date
kindDayKindDto
verificationVerificationDto
productsProductSplitDto | None= None
provenanceProvenance | None= None
reasonstr | None= None
sessionstuple[SessionDto, ...]= ()
as_ofstr | None= None
datasetDatasetServed | None= None

DaysResponsedataclass

class DaysResponse

DaysResponse(days: 'tuple[DayDto, ...]', as_of: 'str | None' = None, dataset: 'DatasetServed | None' = None, mic: 'str | None' = None)

daystuple[DayDto, ...]
as_ofstr | None= None
datasetDatasetServed | None= None
micstr | None= None

ExceptionsBodydataclass

class ExceptionsBody

ExceptionsBody(from_: 'datetime.date', to: 'datetime.date', as_of: 'str | None' = None, kinds: 'tuple[str, ...]' = (), mics: 'tuple[str, ...]' = ())

from_datetime.date
todatetime.date
as_ofstr | None= None
kindstuple[str, ...]= ()
micstuple[str, ...]= ()

ExceptionsResponsedataclass

class ExceptionsResponse

ExceptionsResponse(days: 'tuple[VenueDay, ...]', from_: 'datetime.date', to: 'datetime.date', as_of: 'str | None' = None, dataset: 'DatasetServed | None' = None)

daystuple[VenueDay, ...]
from_datetime.date
todatetime.date
as_ofstr | None= None
datasetDatasetServed | None= None

Healthdataclass

class Health

Health(artifact: 'str', built_at: 'str', dataset: 'str', mapped_venues: 'int', registry_published: 'datetime.date', status: 'str')

artifactstr
built_atstr
datasetstr
mapped_venuesint
registry_publisheddatetime.date
statusstr

InstantResponsedataclass

class InstantResponse

InstantResponse(from_: 'str', as_of: 'str | None' = None, at: 'str | None' = None, dataset: 'DatasetServed | None' = None, mic: 'str | None' = None)

from_str
as_ofstr | None= None
atstr | None= None
datasetDatasetServed | None= None
micstr | None= None

JointSkippeddataclass

class JointSkipped

A date passed over: the venues that did not trade it, other than for a weekend.

closeddict[str, SkippedDay]
datedatetime.date

JointStepBodydataclass

class JointStepBody

JointStepBody(from_: 'datetime.date', as_of: 'str | None' = None, inclusive: 'bool | None' = None, mics: 'tuple[str, ...]' = (), mode: 'str | None' = None, n: 'int | None' = None, on_unknown: 'str | None' = None)

from_datetime.date
as_ofstr | None= None
inclusivebool | None= None
micstuple[str, ...]= ()
modestr | None= None
nint | None= None
on_unknownstr | None= None

JointStepResponsedataclass

class JointStepResponse

JointStepResponse(date: 'datetime.date', from_: 'datetime.date', mics: 'tuple[str, ...]', mode: 'str', n: 'int', skipped: 'tuple[JointSkipped, ...]', venues: 'dict[str, DayKindDto]', as_of: 'str | None' = None, dataset: 'DatasetServed | None' = None, unknown_skipped: 'tuple[datetime.date, ...]' = ())

datedatetime.date
from_datetime.date
micstuple[str, ...]
modestr
nint
skippedtuple[JointSkipped, ...]
venuesdict[str, DayKindDto]
as_ofstr | None= None
datasetDatasetServed | None= None
unknown_skippedtuple[datetime.date, ...]= ()

Legenddataclass

class Legend

Legend(kinds: 'dict[str, str]', verification: 'dict[str, str]')

kindsdict[str, str]
verificationdict[str, str]

MicWindowdataclass

class MicWindow

One MIC cap's count (SPEC-pricing §6.4). max is null on a plan with every MIC.

usedint
windowstr
maxint | None= None
micstuple[str, ...] | None= None
resets_atstr | None= None

OverLimitdataclass

class OverLimit

OverLimit(error: 'OverLimitError', message: 'str', allowed: 'OverLimitAllowed | None' = None, limit: 'OverLimitLimit | None' = None, mics_in_use: 'tuple[str, ...]' = (), resets_at: 'str | None' = None, upgrade: 'str | None' = None)

errorOverLimitError
messagestr
allowedOverLimitAllowed | None= None
limitOverLimitLimit | None= None
mics_in_usetuple[str, ...]= ()
resets_atstr | None= None
upgradestr | None= None

OverLimitAlloweddataclass

class OverLimitAllowed

For out_of_window: the dates the plan may ask about; null is unbounded

from_datetime.date | None= None
todatetime.date | None= None

OverLimitLimitdataclass

class OverLimitLimit

OverLimitLimit(kind: 'OverLimitLimitKind | None' = None, max: 'int | None' = None, used: 'int | None' = None)

kindOverLimitLimitKind | None= None
maxint | None= None
usedint | None= None

ProductSplitDtodataclass

class ProductSplitDto

Which products traded on a day that did not treat them alike.

closedtuple[str, ...]= ()
notestr | None= None
opentuple[str, ...]= ()

Provenancedataclass

class Provenance

The evidence behind a day. Only ever sent when asked for.

retrieveddatetime.date | None= None
sourcestr | None= None

Ratedataclass

class Rate

Rate(bulk_per_minute: 'int', per_minute: 'int')

bulk_per_minuteint
per_minuteint

ResolutionDtodataclass

class ResolutionDto

How a MIC reaches its answer (SPEC: calendar-membership). The MIC pages state the same.

kindstr
viastr

RunningSessiondataclass

class RunningSession

RunningSession(close: 'str', name: 'str', open: 'str', trade_date: 'datetime.date', verification: 'VerificationDto', products: 'str | None' = None)

closestr
namestr
openstr
trade_datedatetime.date
verificationVerificationDto
productsstr | None= None

SessionDtodataclass

class SessionDto

SessionDto(close: 'str', name: 'str', open: 'str', verification: 'VerificationDto', breaks: 'tuple[BreakDto, ...]' = (), products: 'str | None' = None, provenance: 'Provenance | None' = None)

closestr
namestr
openstr
verificationVerificationDto
breakstuple[BreakDto, ...]= ()
productsstr | None= None
provenanceProvenance | None= None

SkippedDaydataclass

class SkippedDay

A day stepped over: not a weekend, and not trading.

datedatetime.date
kindDayKindDto
reasonstr | None= None

StatusResponsedataclass

class StatusResponse

StatusResponse(at: 'str', day: 'DayDto', state: 'StateDto', as_of: 'str | None' = None, dataset: 'DatasetServed | None' = None, mic: 'str | None' = None, next_close: 'str | None' = None, next_open: 'str | None' = None, running: 'RunningSession | None' = None)

atstr
dayDayDto
stateStateDto
as_ofstr | None= None
datasetDatasetServed | None= None
micstr | None= None
next_closestr | None= None
next_openstr | None= None
runningRunningSession | None= None

StatusesBodydataclass

class StatusesBody

StatusesBody(as_of: 'str | None' = None, at: 'str | None' = None, mics: 'tuple[str, ...]' = ())

as_ofstr | None= None
atstr | None= None
micstuple[str, ...]= ()

StatusesResponsedataclass

class StatusesResponse

StatusesResponse(at: 'str', venues: 'dict[str, VenueStatus]', as_of: 'str | None' = None, dataset: 'DatasetServed | None' = None)

atstr
venuesdict[str, VenueStatus]
as_ofstr | None= None
datasetDatasetServed | None= None

StepResponsedataclass

class StepResponse

StepResponse(date: 'datetime.date', from_: 'datetime.date', kind: 'DayKindDto', mic: 'str', n: 'int', skipped: 'tuple[SkippedDay, ...]', as_of: 'str | None' = None, dataset: 'DatasetServed | None' = None, unknown_skipped: 'tuple[datetime.date, ...]' = ())

datedatetime.date
from_datetime.date
kindDayKindDto
micstr
nint
skippedtuple[SkippedDay, ...]
as_ofstr | None= None
datasetDatasetServed | None= None
unknown_skippedtuple[datetime.date, ...]= ()

TradingDaysResponsedataclass

class TradingDaysResponse

A date and whether the venue trades on it, and nothing else.

datestuple[datetime.date, ...]
from_datetime.date
todatetime.date
venuesdict[str, TradingSeries]
as_ofstr | None= None
datasetDatasetServed | None= None

TradingSeriesdataclass

class TradingSeries

TradingSeries(trading: 'tuple[bool | None, ...]', unknown: 'int')

tradingtuple[bool | None, ...]
unknownint

UsageViewdataclass

class UsageView

An account's usage against its plan (SPEC-pricing §6.4): what GET /v1/usage answers, and what the account page shows.

horizonDataWindow
mics_dayMicWindow
mics_monthMicWindow
planstr
rateRate
venue_daysVenueDays | None= None

VenueDaydataclass

class VenueDay

One venue's day, in a row-oriented list.

datedatetime.date
kindDayKindDto
verificationVerificationDto
micstr
productsProductSplitDto | None= None
provenanceProvenance | None= None
reasonstr | None= None
sessionstuple[SessionDto, ...]= ()

VenueDaysdataclass

class VenueDays

VenueDays(max: 'int', used: 'int', resets_at: 'str | None' = None)

maxint
usedint
resets_atstr | None= None

VenueResponsedataclass

class VenueResponse

VenueResponse(mic: 'str', name: 'str', operating_mic: 'str', products: 'tuple[str, ...]', status: 'str', country: 'str | None' = None, resolution: 'ResolutionDto | None' = None, timezone: 'str | None' = None)

micstr
namestr
operating_micstr
productstuple[str, ...]
statusstr
countrystr | None= None
resolutionResolutionDto | None= None
timezonestr | None= None

VenueStatusdataclass

class VenueStatus

One venue's entry: StatusResponse without the at the response states once.

dayDayDto
stateStateDto
next_closestr | None= None
next_openstr | None= None
runningRunningSession | None= None

VenuesResponsedataclass

class VenuesResponse

VenuesResponse(venues: 'tuple[VenueResponse, ...]', next_cursor: 'str | None' = None)

venuestuple[VenueResponse, ...]
next_cursorstr | None= None