Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ own, so a fix to one package moves only the projects that pin it.
| [`primitives-kit`](packages/primitives-kit) | Shared contracts with no behaviour of their own: a rate-budget protocol, its error tree, a vendor quota reading. | 0.1.0 | 3.12+ | none |
| [`pack-contracts`](packages/pack-contracts) | What a plugin pack is written against: a manifest read without importing the pack, pluggy hookspecs, a ledger that enforces the versioning rule. | 0.2.1 | 3.12+ | none |
| [`platform-kit`](packages/platform-kit) | A service platform: typed config, one notification path, a watchdog plane, a strict plugin loader, a FastAPI composition root, a Postgres rate budget, ingest lanes with a freshness verdict, a daemon run-loop kit, a job-engine port with a Windmill adapter, OpenTelemetry tracing with a per-trace span budget, a counted outbound HTTP client and a guarded fetch of an untrusted image URL, gauge and counter readings for a store many processes write (its statements over a caller's sync or async executor, the per-process publisher and the text exposition), an ntfy push transport with its spool file contract, an identity and permission model with route-declared policy, a shadow-to-enforce readiness check and user administration, and the async daemon loops (a cadence loop, a wake-coalescing loop, reconnecting LISTEN and NATS wake wires, a thread-backed side publisher that never blocks its sync caller and counts every dropped copy, a compute-once shared producer cache), an event-loop lag sampler that names what held the loop, a Postgres job queue with a claim gate, an off-loop heartbeat, a stall reaper and a step journal, a migration ledger held to account (sha256 per applied file, a transactional rollback, live catalog vs replay fingerprint, background policies declared vs running), pgmq message operations with every queue's health from pgmq's own metrics, a column watch (a value column that has never been non-NULL is a producer nobody wrote), and the runtime side of typed config (an append-only override ledger with its attribution watch, the live value-and-source view, and a config fingerprint stamped on graded rows with the watch for an unstamped one). | 0.31.0 | 3.11+ | primitives-kit (`sql`), pack-contracts (`packs`) |
| [`market-ports`](packages/market-ports) | Typed market-data ports: frozen rows, capability-mapped providers, fallback chains that report which tier answered, retries and rate budgets, public-vendor adapters, and stdlib bar analytics (forward outcome labels, a read's kill rule, VWAP and its sigma) and calendar flags. | 0.20.0 | 3.12+ | primitives-kit |
| [`market-ports`](packages/market-ports) | Typed market-data ports: frozen rows, capability-mapped providers, fallback chains that report which tier answered, retries and rate budgets, public-vendor adapters, and stdlib bar analytics (forward outcome labels, a read's kill rule, VWAP and its sigma) and calendar flags. | 0.21.0 | 3.12+ | primitives-kit |
| [`content-data`](packages/content-data) | A content-source registry declared as data and validated against built-in and pack-contributed kinds, with a versioned content contract, prompt-pack pins and a conformance kit. | 1.1.0 | 3.12+ | platform-kit, pack-contracts (through platform-kit's `packs`) |
| [`honesty-stats`](packages/honesty-stats) | Statistics that keep an evaluation honest: deflated Sharpe ratios, the probability of overfitting, purged cross-validation, conformal intervals, proper forecast scores, false-discovery control, effective counts under dependence, SPA, StepM and the Model Confidence Set, sequential tests, two-proportion lifts, group separation, hit rates over a luck baseline, an alpha-investing error budget and fixed verdict ladders. | 0.5.0 | 3.12+ | none |
| [`learn-kit`](packages/learn-kit) | The fit side of evaluation: a gate, a run ledger and a loop runner for learning loops, earned weights, lifecycle rules (health, retirement, rotation), a test fingerprint, a discrete-time hazard, hierarchical shrinkage, probability calibrators, forecast combiners, and the ledger and registry on MLflow. | 0.4.1 | 3.12+ | honesty-stats |
Expand Down
24 changes: 24 additions & 0 deletions packages/market-ports/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,30 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and

## [Unreleased]

## [0.21.0]

### Added

- `market_ports.adapters.financedatabase` (extra `reference`: financedatabase, polars), the first
`INSTRUMENTS` adapter, in the built-in roster as `financedatabase`. One `Instrument` per symbol
from the first of equities, ETFs, indices, funds, currencies and cryptos that lists it (a
symbol listed twice in one class answers with its first row; delisted rows excluded); an
`InstrumentStatus` `not_found` for a symbol no class lists. A class that fails to load is a
`VendorError` and nothing partial is kept, so `not_found` always means every class was searched.
The six classes load once per fetcher, off the event loop, under a lock, keeping only the
columns `COLUMNS` maps (about 130 MB as Polars frames on financedatabase 2.5.2);
`financedatabase_provider(loader=...)` is the test seam. The library downloads its files from
GitHub on first use and caches them itself; its retired funds class warns on load
(`FutureWarning`), which the adapter does not hide.
- `Instrument` reference data, every field optional text: `currency`, `country`, `state`, `city`,
`sector`, `industry_group`, `industry`, `category_group`, `category`, `family`, `market`,
`market_cap_class` (a size label, never a number), `isin`, `website`, `summary`.

### Changed

- `Symbol` (every symbols query) also accepts `=` after the first character, so a currency pair
written `EURUSD=X` is a symbol.

## [0.20.0]

### Added
Expand Down
1 change: 1 addition & 0 deletions packages/market-ports/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ the provider is built, so each tier's price basis is stated once (`Fetcher.basis
| `ssga` | `ssga` | `index_weights` from the SPDR daily holdings workbook | — | `ssga` | — |
| `forexfactory` | `forexfactory` | `econ_calendar` (this week's file; a range outside it is `Unverified`, never empty) | — | — | — |
| `atlantafed` | `atlantafed` | `rate_probabilities`: one `RateDistribution` per observation date and three-month reference window (rate percentiles in bps, below / above / within the target range, the 25 bp buckets); a moved workbook is re-found from the tracker page and reported as an `AttemptFailedEvent` | `workbook_url` | `atlantafed` | — |
| `financedatabase` | `financedatabase` | `instruments`: one `Instrument` per symbol (asset class, name, exchange, currency, country, sector / industry or fund category and family, ISIN, website, summary) from the first of equities, ETFs, indices, funds, currencies, cryptos that lists it; an `InstrumentStatus` `not_found` for one none lists. The library downloads its files on first use; they load once per provider, off the loop | `loader` (test seam) | `reference` | — |

A symbol a vendor answered for with nothing comes back as one `InstrumentStatus` row (`no_data`:
known, nothing in the range; `not_found`: no such symbol), which a fallback chain treats as
Expand Down
7 changes: 5 additions & 2 deletions packages/market-ports/pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[project]
name = "market-ports"
version = "0.20.0"
version = "0.21.0"
description = "Typed market-data ports: frozen pydantic rows, a three-step Fetcher, capability-mapped Providers, fallback chains that name the answering tier, stamina retries, pyrate-limiter budgets, a built-in provider roster and a recorded-payload contract kit."
readme = "README.md"
license = "MIT"
Expand Down Expand Up @@ -51,7 +51,10 @@ ssga = ["openpyxl>=3.1.5"]
atlantafed = ["openpyxl>=3.1.5"]
# `market_ports.time`: session days and their real bells (half days included) over exchange_calendars.
calendars = ["exchange-calendars>=4.13.3"]
all = ["market-ports[cache,ws,yfinance,ssga,atlantafed,calendars]"]
# The FinanceDatabase adapter (`market_ports.adapters.financedatabase`): instrument reference data.
# The library downloads its files from GitHub on first use; it reads them as Polars frames.
reference = ["financedatabase>=2.5.2", "polars>=2.0"]
all = ["market-ports[cache,ws,yfinance,ssga,atlantafed,calendars,reference]"]

[build-system]
requires = ["hatchling>=1.27"]
Expand Down
3 changes: 2 additions & 1 deletion packages/market-ports/src/market_ports/adapters/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,9 @@
| `ssga` | `ssga` | `FUND_HOLDINGS` | `ssga` |
| `forexfactory` | `forexfactory` | `ECONOMIC_CALENDAR` | none |
| `atlantafed` | `atlantafed` | `RATE_PROBABILITIES` (the probability-tracker history workbook) | `atlantafed` |
| `financedatabase` | `financedatabase` | `INSTRUMENTS` (reference definitions, six asset classes) | `reference` |

A vendor library (yfinance, openpyxl, websockets) is imported when its adapter first uses it, never
A vendor library (yfinance, openpyxl, websockets, financedatabase) is imported when its adapter first uses it, never
at import time, so the registry loads every plugin on a core-only install and a missing extra
surfaces as an `ImportError` naming the extra.
"""
Expand Down
239 changes: 239 additions & 0 deletions packages/market-ports/src/market_ports/adapters/financedatabase.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,239 @@
"""FinanceDatabase adapter: what a symbol IS, from a static reference database (`INSTRUMENTS`).

FinanceDatabase (the `financedatabase` package, the `reference` extra) is a keyless, offline-first
reference set of about 280,000 instruments in six asset classes: equities, ETFs, indices, funds,
currencies and cryptos. Each class is a compressed file the library downloads from its GitHub
repository on first use and keeps as Parquet in its own cache directory (`FINANCEDATABASE_CACHE_DIR`,
else the platform cache), checking it for changes at most once a day. The library does its own
HTTP (`requests`), so this provider's `FetchContext` client, budget and redirect fence are unused.

A symbol is looked up in `CLASSES` order and the FIRST class that lists it answers; inside one
class a symbol listed twice answers with its first row. A symbol no class lists is an
`InstrumentStatus` `not_found`, never an empty success, and is only reported once every class was
searched: a class that failed to load is a `VendorError`, so "unknown" always means "looked
everywhere". Delisted rows are excluded (the library's default). The library retired its funds
class in October 2026 (its data stays, no longer updated) and says so with a `FutureWarning` on
load; the adapter lets that warning through rather than hide a vendor's own notice.

Loading is the expensive part (a few seconds and about 130 MB for all six classes as Polars
frames, measured on financedatabase 2.5.2). It happens once per `FinanceDatabaseInstruments`
instance, off the event loop, under a lock, and only the columns `COLUMNS` names are kept; a
lookup after that is one vectorised filter per class. `FINANCEDATABASE`, the module's provider,
holds one such instance, so a process that shares it pays the load once.

Library checked: financedatabase itself (`<Class>().select(as_pandas=False)`, its public API). Its
`search` is a substring match over every column, not an exact symbol lookup, so it is not used.
"""

from __future__ import annotations

import asyncio
import threading
from collections.abc import Callable, Mapping, Sequence
from importlib.metadata import PackageNotFoundError, version
from typing import Any, ClassVar, override

from pydantic import BaseModel, ConfigDict

from market_ports.adapters._util import drift, require_extra
from market_ports.capabilities import Capability
from market_ports.errors import VendorError
from market_ports.fetcher import Fetcher, Receipt
from market_ports.http import FetchContext
from market_ports.models import AssetClass, Instrument, InstrumentState, InstrumentStatus, Row
from market_ports.provider import Provider
from market_ports.queries import InstrumentsQuery
from market_ports.registry import hookimpl

__all__ = [
"CLASSES",
"COLUMNS",
"FINANCEDATABASE",
"FinanceDatabaseInstruments",
"financedatabase_provider",
"register_providers",
]

#: The library's class name, the payload's key for it and the `AssetClass` it answers with, in
#: lookup order: the first class that lists a symbol wins.
CLASSES: tuple[tuple[str, str, AssetClass], ...] = (
("Equities", "equities", AssetClass.EQUITY),
("ETFs", "etfs", AssetClass.ETF),
("Indices", "indices", AssetClass.INDEX),
("Funds", "funds", AssetClass.FUND),
("Currencies", "currencies", AssetClass.FX),
("Cryptos", "cryptos", AssetClass.CRYPTO),
)
_ASSET = {key: asset for _, key, asset in CLASSES}

#: The vendor column -> `Instrument` field. Every class's first column is its symbol; a column a
#: class does not publish is None on its rows.
COLUMNS: Mapping[str, str] = {
"name": "description",
"exchange": "exchange",
"currency": "currency",
"country": "country",
"state": "state",
"city": "city",
"sector": "sector",
"industry_group": "industry_group",
"industry": "industry",
"category_group": "category_group",
"category": "category",
"family": "family",
"market": "market",
"market_cap": "market_cap_class",
"isin": "isin",
"website": "website",
"summary": "summary",
}
_SYMBOL = "symbol"

#: A frame loader: the library's class name -> that class's rows as a Polars frame (symbol first).
Loader = Callable[[str], Any]


def _library_loader(name: str) -> Any:
fd = require_extra("financedatabase", "reference")
return getattr(fd, name)().select(as_pandas=False)


def _text(value: Any) -> str | None:
"""A cell as text: stripped, and None for a blank or the library's spelled-out missing marks."""
if value is None:
return None
s = str(value).strip()
return None if not s or s.lower() in ("nan", "none") else s


def _library_version() -> str | None:
try:
return version("financedatabase")
except PackageNotFoundError:
return None


class _Item(BaseModel):
model_config: ClassVar[ConfigDict] = ConfigDict(extra="ignore")

symbol: str
asset_class: str | None = None
row: dict[str, Any] | None = None


class FinanceDatabaseInstruments(Fetcher[InstrumentsQuery, Row]):
"""`INSTRUMENTS` from FinanceDatabase: an `Instrument` per listed symbol, `not_found` otherwise."""

query_model: ClassVar[type[BaseModel]] = InstrumentsQuery

def __init__(self, *, loader: Loader | None = None) -> None:
"""`loader` replaces the library (a test seam): class name -> a Polars frame, symbol first."""
self._loader: Loader = loader or _library_loader
self._frames: dict[str, Any] | None = None
self._lock = threading.Lock()

@property
def loaded(self) -> bool:
"""Whether every class is in memory (the first fetch loads them)."""
return self._frames is not None

def frames(self) -> Mapping[str, Any]:
"""Every class's rows, loaded on the first call and kept. Blocking: call it off the loop.

Only a complete set is kept: a class that fails to load raises, and the next call retries
all of them.
"""
with self._lock:
if self._frames is None:
pl = require_extra("polars", "reference")
frames: dict[str, Any] = {}
for name, key, _ in CLASSES:
frame = self._loader(name)
symbol = frame.columns[0]
keep = [c for c in COLUMNS if c in frame.columns]
frames[key] = frame.select(pl.col(symbol).alias(_SYMBOL), *keep).unique(
subset=_SYMBOL, keep="first", maintain_order=True
)
self._frames = frames
return self._frames

def lookup(self, symbols: Sequence[str]) -> dict[str, Any]:
"""The payload for `symbols`: each one's first class and row, or no class. Blocking."""
pl = require_extra("polars", "reference")
frames = self.frames()
found: dict[str, tuple[str, dict[str, Any]]] = {}
for _, key, _ in CLASSES:
remaining = [s for s in symbols if s not in found]
if not remaining:
break
for row in frames[key].filter(pl.col(_SYMBOL).is_in(remaining)).to_dicts():
found.setdefault(row.pop(_SYMBOL), (key, row))
items = [
{"symbol": s, "asset_class": found[s][0], "row": found[s][1]} if s in found else {"symbol": s}
for s in symbols
]
return {"library_version": _library_version(), "symbols": items}

@override
async def extract(self, query: InstrumentsQuery, ctx: FetchContext) -> Any:
try:
return await asyncio.to_thread(self.lookup, query.symbols)
except ImportError:
raise
except Exception as exc:
raise VendorError(ctx.provider, f"financedatabase could not be read: {type(exc).__name__}: {exc}") from exc

@override
def transform(self, query: InstrumentsQuery, data: Any, receipt: Receipt) -> Sequence[Row]:
items = data.get("symbols") if isinstance(data, Mapping) else None
if not isinstance(items, list):
raise drift(("symbols",), "no symbols list")
out: list[Row] = []
for i, raw in enumerate(items):
item = _Item.model_validate(raw)
if item.asset_class is None:
out.append(
InstrumentStatus(
symbol=item.symbol,
vendor_symbol=item.symbol,
state=InstrumentState.NOT_FOUND,
detail="financedatabase lists it in none of " + ", ".join(k for _, k, _ in CLASSES),
source=receipt.source,
ts_recv=receipt.received_at,
)
)
continue
asset = _ASSET.get(item.asset_class)
if asset is None:
raise drift((i, "asset_class"), f"not a FinanceDatabase class: {item.asset_class[:40]!r}")
row = item.row or {}
fields = {field: _text(row.get(column)) for column, field in COLUMNS.items()}
out.append(
Instrument(
symbol=item.symbol,
vendor_symbol=item.symbol,
asset_class=asset,
source=receipt.source,
ts_recv=receipt.received_at,
**fields,
)
)
return out


def financedatabase_provider(*, loader: Loader | None = None) -> Provider:
"""A FinanceDatabase provider with its own loaded-once cache (`loader`: see the fetcher)."""
return Provider(
name="financedatabase",
has={Capability.INSTRUMENTS: FinanceDatabaseInstruments(loader=loader)},
description="FinanceDatabase reference definitions (equities, ETFs, indices, funds, FX, crypto), no key",
)


FINANCEDATABASE = financedatabase_provider()


@hookimpl
def register_providers(register: Any) -> None:
"""Register `FINANCEDATABASE`."""
register(FINANCEDATABASE)
Loading