Skip to content

@mostlyrightmd/finance

Custom error type for earnings contract-id parsing / validation failures.

Mirrors the Python ValueError/TypeError distinction: in TS we use a named subclass so callers can instanceof-check rather than parse error messages.

  • ContractError

new EarningsContractIdError(message): EarningsContractIdError

string

EarningsContractIdError

ContractError.constructor


Error raised by alignEventDate for a bad event date, an unknown ticker, or a mis-paired (eventDate, callInstant). A named subclass so callers can instanceof-check rather than parse error messages.

  • ContractError

new EarningsPitError(message): EarningsPitError

string

EarningsPitError

ContractError.constructor

readonly optional callInstant: string

Optional ISO-8601 UTC instant of the call. When given, the event date is re-projected to the HQ-local calendar date of that instant (the ±1-UTC-day correction) — so a call that straddles a UTC day boundary lands on the correct local date. The re-projected hq-local date must be within ±1 calendar day of the supplied eventDate; a larger divergence throws (it signals a mis-paired (eventDate, callInstant)). When omitted, eventDate is returned unchanged (after coercion).


readonly callId: string

readonly optional eventSourceFactory: EventSourceFactory

Opens an EventSource for a URL. Default: new EventSource(url) (browser). Injectable so non-browser tests can mock it.

readonly mintToken: (ticker, callId) => Promise<string>

Mints a short-lived signed-URL token via the authenticated path. REQUIRED — a browser EventSource cannot set an Authorization header, so the token is carried on the URL (P2).

string

string

Promise<string>

readonly ticker: string


callScheduledAt: string

hqTimezone: string

provider: string

ticker: string


The frozen tuple a Kalshi earnings-mention contract resolves to.

Mirrors import(”./kalshi-nhigh.js”).NHighResolution: an immutable (ticker, targetWord, eventDate, resolutionRule) carrier so a resolution cannot be mutated downstream (the frozen-tuple contract enforced via Object.freeze, the TS twin of the Python @dataclass(frozen=True)).

readonly eventDate: string

Calendar date the call airs / the market settles for (YYYY-MM-DD).

readonly resolutionRule: string

Stable settlement-rule label (not an executable rule). Kalshi resolutions carry RESOLUTION_RULE; Polymarket derives carry the any-speaker variant.

readonly resolutionStatus: "qualifying_event" | "no_qualifying_event"

Whether a qualifying call exists for this date. "qualifying_event" for a normal resolution; "no_qualifying_event" when a derive sees a postponed/cancelled call. The Kalshi resolveEarnings path is always "qualifying_event".

readonly targetWord: string

readonly ticker: string


A canonical earnings row emitted by parseEarningsPayload. Carries the passthrough schema fields present on the source row plus the SDK overlay.

readonly optional callId: string

readonly delivery: "hosted" | "live"

Delivery channel lineage: "live" or "hosted".

readonly eventTime: null | string

Call air time (ISO-8601 UTC), or null if absent.

readonly optional kalshiCounted: boolean

readonly knowledgeTime: string

Transcript availability (POST-call), ISO-8601 UTC. The PIT invariant knowledgeTime = transcript availability, NEVER the call air time — a model deciding before this instant must not see the mention.

readonly optional matchedSurfaceForm: string

readonly optional mentionCount: number

readonly optional offsetSeconds: number

readonly retrievedAt: string

When the SDK retrieved the row (ISO-8601 UTC).

readonly optional roleSource: string

readonly optional segment: string

readonly optional segmentIndex: number

readonly source: "earnings_call"

Shared source identity — always EARNINGS_SOURCE_IDENTITY.

readonly optional speakerName: string

readonly optional speakerRole: string

readonly optional termCanonical: string

readonly optional text: string

readonly optional ticker: string


A canonical LIVE streaming row yielded by consumeEarningsStream.

Mirrors the Python _project_stream_row output. Carries the schema delta fields (isFinal / spokenAt / streamSeq / resolutionStatus) plus the SDK overlay (source / knowledgeTime). kalshiCounted is passed through verbatim — the consumer never re-derives it.

readonly optional callId: string

readonly event: "transcript_segment" | "fact_delta" | "end_of_call" | "resume_incomplete"

The SSE event that produced this row.

readonly optional isFinal: boolean

STT-segment finality ONLY — never settlement authority (P2).

readonly optional kalshiCounted: boolean

Passed through from the fact-delta row — NEVER re-derived client-side.

readonly knowledgeTime: null | string

STT-finalization/publish wallclock (ISO-8601 UTC, >= spokenAt), or null.

readonly optional matchedSurfaceForm: string

readonly optional mentionCount: number

readonly optional offsetSeconds: number

readonly optional resolutionStatus: string

Provisional for a counted fact delta; a live count is never settled.

readonly optional roleSource: string

readonly optional segment: string

readonly optional segmentIndex: number

readonly source: "earnings.hosted.stream"

Always EARNINGS_LIVE_STREAM_SOURCE — provisional live lineage.

readonly optional speakerName: string

readonly optional speakerRole: string

readonly spokenAt: null | string

Aired event time (ISO-8601 UTC), or null.

readonly streamSeq: null | number

Monotonic SSE id: = stream_seq (drives Last-Event-ID resume).

readonly optional termCanonical: string

readonly optional text: string

readonly optional ticker: string


The minimal EventSource surface the consumer needs — declared structurally so tests can inject a mock without a DOM. Matches the browser EventSource.

onerror: null | (event) => void

addEventListener(type, listener): void

string

(event) => void

void

close(): void

void


  • FetchWithRetryOptions

readonly hostedUrl: string

The hosted feed base URL. REQUIRED — the SDK ships no default endpoint (the serving layer is the satellite +).

readonly optional retrievedAt: string

Retrieval timestamp override (ISO-8601 UTC). Default: now.


readonly apiKey: string

The MOSTLYRIGHT_API_KEY. REQUIRED. Used to MINT a signed, single-scope ?token= locally (the browser cannot set an x-api-key header); the raw key is never placed in the URL.

readonly callId: string

Call id filter for the stream.

readonly optional eventSourceFactory: EventSourceFactory

Opens an EventSource for a URL. Default: new EventSource(url) (browser). Injectable so non-browser tests can mock it.

readonly hostedUrl: string

The earnings serving base URL (MOSTLYRIGHT_FINANCE_HOSTED_URL) — the deployed mr-serving origin. REQUIRED; a missing seam throws HostedConfigError.

readonly optional maxReconnects: number

Max reconnect attempts after a terminal disconnect before giving up. Default 5. Each attempt re-opens with the last seen Last-Event-ID.

readonly optional signal: AbortSignal

Optional AbortSignal — when fired, the stream closes the EventSource and ends iteration cleanly (no further reconnect).

readonly ticker: string

Ticker filter for the stream.


The minimal MessageEvent surface: a JSON data string + lastEventId.

readonly data: string

readonly optional lastEventId: string


readonly optional retrievedAt: string

Retrieval timestamp (ISO-8601 UTC). Default: now.

readonly optional source: "earnings.live" | "earnings.hosted"

Delivery channel source id. Only earnings.hosted is browser-viable here; earnings.live throws (server-only). Default earnings.hosted.


Untrusted Polymarket event payload shape (all fields optional).

readonly optional eventDate: string

ISO YYYY-MM-DD calendar date. A time-bearing value is rejected.

readonly optional name: string

readonly optional slug: string

readonly optional status: string

readonly optional targetWord: string

readonly optional ticker: string

readonly optional title: string

readonly optional webcastUrl: string


readonly targetWord: string

The word/phrase the market resolves on. Required, non-empty.

EarningsStreamEvent: typeof SSE_STREAM_EVENTS[number]


EventSourceFactory: (url) => EventSourceLike

Factory that opens an EventSource for a fully-formed URL (with ?token=). In the browser this is (url) => new EventSource(url); tests inject a mock.

string

EventSourceLike

const EARNINGS_CALENDAR_SEED: ReadonlyArray<EarningsCalendarRow>


const EARNINGS_SERIES_ROSTER: ReadonlySet<string>


const TICKER_HQ_TIMEZONE: Readonly<Record<string, string>>


const transcripts: object

The finance earnings-transcripts namespace — the curated verb surface.

  • get — fetch hosted transcript rows (browser/MV3-viable hosted consumer).
  • stream — consume the hosted SSE transcript stream (Last-Event-ID reconnect).
  • resolve — the Kalshi earnings-mention resolver.
  • derive — a Polymarket earnings event → resolution.

readonly derive: (event) => null | EarningsResolution = deriveEarnings

Derive a frozen EarningsResolution from a Polymarket event payload.

The payload is untrusted. The derive refuses (returns null) when:

  • the slug/title/name does not look like an earnings-mention market;
  • a webcastUrl is present but its host is NOT on WEBCAST_HOST_ALLOWLIST (security boundary — refuse before derive);
  • the ticker is missing or not in EARNINGS_SERIES_ROSTER;
  • targetWord or eventDate is missing / unparseable.

A postponed / cancelled call yields a resolution with resolutionStatus="no_qualifying_event".

PolymarketEarningsEvent

null | EarningsResolution

readonly get: (ticker, eventDate, options) => Promise<DataResult<EarningsRow>> = fetchEarningsHosted

Fetch + parse the hosted earnings feed for a ticker on an event date.

Mirrors awc.ts graceful-degradation discipline: returns [] on 4xx, timeout, exhausted retries, or a non-JSON/malformed body — NEVER throws for a transport/parse failure (a caller AbortSignal still propagates). Rows are byte-equivalent to the Python EarningsAdapter.from_rows(source="earnings.hosted") output; only the delivery lineage differs between live and hosted.

Browser-viable: fetch + JSON only. For endpoints without CORS headers, run behind a Chrome MV3 service worker (host_permissions) or a CORS proxy — same posture as fetchAwcMetars.

string

string

FetchEarningsHostedOptions

Promise<DataResult<EarningsRow>>

readonly resolve: (contractId, eventDate, options) => EarningsResolution = resolveEarnings

Resolve a Kalshi earnings-mention contract to its frozen tuple.

The contractId is the Kalshi market identifier — one of the three root variants KXEARNINGSMENTION<TICKER> (e.g. KXEARNINGSMENTIONNKE), KXMENTIONEARN<TICKER>, or the Berkshire fixed root KXBRKEM. The suffix is the ticker; it is validated against EARNINGS_SERIES_ROSTER.

string

Kalshi market identifier. Case-insensitive.

The calendar date the call airs / the market settles for. Either a UTC date-only Date (H/M/S/ms == 0) or a YYYY-MM-DD string.

string | Date

ResolveEarningsOptions

EarningsResolution

A frozen EarningsResolution.

The contract id matches no known root, the ticker is unknown, the event date is time-bearing/invalid, or the target word is empty.

readonly stream: (options) => AsyncGenerator<EarningsStreamRow, void, void> = hostedStream

Consume the earnings live /stream SSE feed with Last-Event-ID reconnect.

Opens new EventSource("${MOSTLYRIGHT_FINANCE_HOSTED_URL}/stream?...&apiKey=…"), subscribes to the named events, yields projected rows tagged source="earnings.hosted.stream", and tracks the last seen event id. On a terminal disconnect (the 3600s Cloud Run cut, an instance swap) it RE-OPENS a fresh EventSource carrying the last seen id as lastEventId= so the server replays the buffered tail — ZERO events lost across the cut. Iteration ends on end_of_call, on signal abort, or after maxReconnects failed reconnects.

Browser/MV3-viable: EventSource + JSON only. No Node built-ins.

HostedStreamOptions

AsyncGenerator<EarningsStreamRow, void, void>

when MOSTLYRIGHT_FINANCE_HOSTED_URL / apiKey is missing — surfaced BEFORE the first connection.

when reconnection is exhausted (maxReconnects reached) — the last transport error is re-thrown so the caller sees the failure, not a silent gap.


const version: "1.9.9" = "1.9.9"

Public package version; kept in lockstep with package.json.


const WEBCAST_HOST_ALLOWLIST: ReadonlySet<string>

Netloc allowlist for webcast / resolution-source hosts. A host NOT on this list is refused before any provider classification or derive ( security boundary) — mirrors polymarket.RESOLUTION_SOURCE_ALLOWLIST. These are the exact public webcast hosts behind the provider fingerprints; a substring fingerprint alone is NOT a trust decision — the allowlist is.


const WEBCAST_PROVIDER_FINGERPRINTS: Readonly<Record<string, string>>

alignEventDate(eventDate, ticker, options): string

Coerce + hq-tz-correct an earnings eventDate to the issuer-local date.

The calendar date the call airs / the market settles for. Either a UTC date-only Date (H/M/S/ms == 0) or a YYYY-MM-DD string — a time-bearing Date is rejected.

string | Date

string

The issuer ticker; its IANA HQ timezone is looked up in TICKER_HQ_TIMEZONE.

AlignEventDateOptions = {}

string

The HQ-local calendar date as YYYY-MM-DD.

eventDate is time-bearing/invalid, ticker is unknown, callInstant is naive (no UTC offset), or the re-projected date diverges from eventDate by more than ±1 calendar day.