feat(market): LDA lobbying filings and issue codes for tracked organizations and PFS terms (lda.gov)

This commit is contained in:
kert
2026-11-14 10:29:27 -05:00
parent b6a909ca4d
commit c87d3c5ead
8 changed files with 1669 additions and 0 deletions

View File

@@ -21,6 +21,7 @@ import httpx
import typer
from market import edgar, http, tiingo
from market import lda as lda_api
from market.seed import (
SEAT_LABEL_KEYS,
SEED_PATH,
@@ -33,6 +34,8 @@ from market.tables import (
EntityRow,
FilingRow,
HitRow,
LdaFilingRow,
LdaIssueRow,
LinkRow,
PassageRow,
SecurityRow,
@@ -63,6 +66,7 @@ app = typer.Typer(no_args_is_help=True)
ENTITIES_GAP = "sec-edgar:entities"
PRICES_GAP = "tiingo:prices"
FTS_GAP = "sec-edgar:fts"
LDA_GAP = "lda:lda"
# ── indirections the tests monkeypatch ───────────────────────────────
@@ -1060,6 +1064,200 @@ def fts(
typer.echo(f"stored: fts links {len(links)} (retired {retired})")
# ── lobbying disclosures ─────────────────────────────────────────────
def _lda_now() -> dt.date:
return dt.date.today()
def _lda_tracked(con: Any) -> list[EntityRow]:
"""Organizations (pseudo seats excluded) and the seed companies; the
SIC-sweep filers are not lobbying targets."""
seed_ciks = {c.cik for c in load_seed()[0]}
return [
e
for e in _or_empty(read_entities, con, [])
if (e.kind == "organization" and not e.pseudo)
or (e.kind == "company" and e.cik in seed_ciks)
]
@app.command()
def lda(
entity: list[str] = typer.Option(
[], "--entity", help="A tracked entity key (repeatable; all when none given)."
),
terms: bool = typer.Option(
False, "--terms", help="Also search the PFS terms in every filing's issues."
),
from_year: int = typer.Option(lda_api.FIRST_YEAR, "--from"),
to_year: int = typer.Option(0, "--to", help="Default: this year."),
limit: int = typer.Option(
0, "--limit", help="At most N network requests (hoarded pages are free)."
),
max_minutes: float = typer.Option(
0.0, "--max-minutes", help="Stop fetching after this long (rerun resumes)."
),
refresh: bool = typer.Option(False, "--refresh", help="Download again."),
write: bool = typer.Option(False, "--write", help="Store filings and issues."),
) -> None:
"""Lobbying Disclosure Act filings from lda.gov (market.lda_filing,
market.lda_issue) for the tracked organizations and seed companies, and
with --terms every filing whose specific issues name a PFS term. A client
is kept as the tracked entity only when its name equals the entity's name
or an alias; a rerun resumes from the hoard (data/market/lda)."""
to_year = to_year or _lda_now().year
if from_year > to_year:
typer.echo(f"--from {from_year} is after --to {to_year}")
raise typer.Exit(2)
con = _read()
try:
tracked = _lda_tracked(con)
finally:
con.close()
if not tracked:
typer.echo("no tracked entities — run `stack market entities --write`")
raise typer.Exit(1)
by_key = {e.key: e for e in tracked}
for k in entity:
if k not in by_key:
typer.echo(f"unknown entity: {k}")
raise typer.Exit(2)
chosen = [by_key[k] for k in dict.fromkeys(entity)] or tracked
index = lda_api.alias_index(
[(e.key, lda_api.query_names(e.name, e.aliases)) for e in tracked]
)
key = http.api_key("lda")
pacer = lda_api.new_pacer(key)
started = time.monotonic()
budget = lda_api.Budget(
limit,
(lambda: time.monotonic() - started > max_minutes * 60)
if max_minutes
else None,
)
this_year = _lda_now().year
one_year = from_year == to_year
# (kind, dir, stem, params)
queries: list[tuple[str, str, str, dict[str, Any]]] = []
for e in chosen:
for name in lda_api.query_names(e.name, e.aliases):
params: dict[str, Any] = {"client_name": name}
if one_year:
params["filing_year"] = from_year
queries.append(
(
"entity",
str(from_year) if one_year else "all",
http.slug(name),
params,
)
)
if terms:
for y in range(from_year, to_year + 1):
for t in lda_api.LDA_TERMS:
queries.append(
(
"term",
str(y),
http.slug(t),
{"filing_specific_lobbying_issues": t, "filing_year": y},
)
)
found: dict[str, tuple[LdaFilingRow, list[LdaIssueRow]]] = {}
done = {"entity": 0, "term": 0}
cl = http.client("lda", key)
try:
for kind, sub, stem, params in queries:
if budget.exhausted:
break
year = int(sub) if sub.isdigit() else 0
stale = None if year and year <= this_year - 2 else 86400.0
for rec in lda_api.query_pages(
cl,
params,
pacer=pacer,
cache_dir=http.hoard("lda", sub),
stem=stem,
refresh=refresh,
stale_after=stale,
budget=budget,
):
if not from_year <= int(rec["filing_year"]) <= to_year:
continue
owner = lda_api.match_client(
(rec.get("client") or {}).get("name", ""), index
)
if kind == "entity" and not owner:
continue # a foundation or a PAC arm is not the entity
uuid = rec["filing_uuid"]
if uuid in found and (found[uuid][0].entity_key or not owner):
continue
found[uuid] = lda_api.to_filing(
rec,
entity_key=owner,
matched_by="client" if owner else "",
source_file=rec["_source_file"],
)
if not budget.exhausted:
done[kind] += 1
except http.Refused as exc:
_gap(LDA_GAP, str(exc), write=write)
return
finally:
cl.close()
rows = [f for f, _ in found.values()]
issues = [i for _, iss in found.values() for i in iss]
gone = lda_api.supersede(rows)
health = Counter(
i.general_issue_code
for f, iss in found.values()
if f.filing_uuid not in gone
for i in {i.general_issue_code: i for i in iss}.values()
if i.general_issue_code in lda_api.HEALTH_ISSUES
)
typer.echo(
f"{len(rows)} filings, {len({r.client_id for r in rows})} clients, "
f"{len({r.registrant_id for r in rows})} registrants, {len(gone)} superseded; "
f"{len({r.entity_key for r in rows if r.entity_key})} tracked entities; "
f"{budget.used} requests; entities {done['entity']} terms {done['term']} "
f"of {len(queries)} queries"
)
if health:
typer.echo(
"issue codes: "
+ " ".join(f"{c} {health[c]}" for c in lda_api.HEALTH_ISSUES if health[c])
)
if budget.exhausted:
typer.echo(f"stopped: {budget.why} (rerun resumes from the hoard)")
if not write:
typer.echo("dry run: pass --write to store")
return
from cms.ingest_log import log_ingest
store = _store()
for y in sorted({r.filing_year for r in rows}):
typer.echo(f"{y}: bib {lda_api.cite(store, y)}")
with _batch() as con:
ensure_tables(con)
n = lda_api.write_lda(con, rows, issues)
if not budget.exhausted:
clear_gap(con, LDA_GAP)
src = str(http.hoard(http.MANIFEST))
for table, count in (
("market.lda_filing", n),
("market.lda_issue", len(issues)),
):
log_ingest(
con, module="market.lda", table_name=table, rows=count, source_file=src
)
_publish()
typer.echo(f"stored: {n} filings, {len(issues)} issue rows")
@app.command()
def gaps() -> None:
"""Sources that could not be read (market.source_gap)."""

395
src/market/lda.py Normal file
View File

@@ -0,0 +1,395 @@
"""Lobbying Disclosure Act filings (LD-1 registrations, LD-2 reports) from
the Senate Office of Public Records API, now served at lda.gov.
``lda.senate.gov`` was sunset on 2026-07-31. The API needs no key (anonymous
clients get 15 requests a minute, a registered key 120); a key, when
``LDA_API_KEY`` is set, travels only in the ``Authorization: Token`` header.
Names are matched by exact normalised name (``alias_match(prefix=False)``): a
foundation or a political-action arm of an organization is a different
client. Lobbyists' personal names and contact details are never stored.
"""
from __future__ import annotations
import dataclasses
import datetime as dt
import json
import os
from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
from pathlib import Path
from typing import Any
import httpx
from market import http
from market.seed import norm_org
from market.tables import (
LdaFilingRow,
LdaIssueRow,
_chunks,
ensure_tables,
write_lda_filings,
write_lda_issues,
)
SOURCE = "lda"
LDA_API = "https://lda.gov/api/v1/"
HOST = "lda.gov"
PAGE_SIZE = 25 # the API's maximum
FIRST_YEAR = 2008 # the LD-2 quarterly reports start with the HLOGA era
ANON_INTERVAL = 4.2 # 15 requests a minute is the limit; 14.3 here
KEYED_INTERVAL = 0.55 # 120 a minute is the limit; 109 here
LDA_TERMS = (
"physician fee schedule",
"conversion factor",
"relative value",
"evaluation and management",
"home-based",
)
HEALTH_ISSUES = ("MMM", "HCR", "MED", "INS", "PHA", "BUD", "TAX")
#: registrations carry no spending
REGISTRATIONS = ("RR", "RA")
_EPOCH = dt.datetime(1970, 1, 1)
def new_pacer(key: str | None = None) -> http.Pacer:
return http.Pacer(KEYED_INTERVAL if key else ANON_INTERVAL)
def cite(store: Any, year: int) -> str:
"""A bib ``source`` item for one filing year's LDA filings (a citation;
the raw pages stay in ``data/market/lda``)."""
from bib.item import Source
from bib.tag import Tag
item = Source(
title=f"Lobbying Disclosure Act filings, {year}",
url=f"{LDA_API}filings/?filing_year={year}",
doc_type="dataset",
abstract="Senate Office of Public Records LD-1/LD-2 filings via lda.gov; "
"raw pages in data/market/lda and market.lda_filing.",
access_date=dt.date.today().isoformat(),
)
return store.upsert(
item,
tags=[
Tag.module("market"),
Tag.table("market.lda_filing"),
Tag.source("lda"),
],
)
# ── rows ─────────────────────────────────────────────────────────────
def _money(value: Any) -> float | None:
return None if value in (None, "") else float(value)
def _utc(text: str | None) -> dt.datetime:
"""An ISO timestamp as naive UTC (the epoch when missing)."""
if not text:
return _EPOCH
when = dt.datetime.fromisoformat(text)
if when.tzinfo is not None:
when = when.astimezone(dt.timezone.utc).replace(tzinfo=None)
return when
def to_filing(
rec: Mapping[str, Any], *, entity_key: str, matched_by: str, source_file: str
) -> tuple[LdaFilingRow, list[LdaIssueRow]]:
"""One API filing as a row plus one issue row per lobbying activity.
``amount`` is income when reported, else expenses; a registration has
none. Lobbyists, covered positions and contacts are dropped."""
kind = str(rec.get("filing_type") or "")
income, expenses = _money(rec.get("income")), _money(rec.get("expenses"))
amount = (
None if kind in REGISTRATIONS else income if income is not None else expenses
)
registrant = rec.get("registrant") or {}
client = rec.get("client") or {}
uuid = str(rec["filing_uuid"])
row = LdaFilingRow(
filing_uuid=uuid,
filing_type=kind,
filing_year=int(rec["filing_year"]),
filing_period=str(rec.get("filing_period") or ""),
dt_posted=_utc(rec.get("dt_posted")),
registrant_id=int(registrant.get("id") or 0),
registrant_name=str(registrant.get("name") or ""),
client_id=int(client.get("id") or 0),
client_name=str(client.get("name") or ""),
income=income,
expenses=expenses,
amount=amount,
superseded=False,
document_url=str(rec.get("filing_document_url") or ""),
entity_key=entity_key,
matched_by=matched_by,
source_file=source_file,
)
issues = [
LdaIssueRow(
uuid,
str(a.get("general_issue_code") or ""),
str(a.get("description") or ""),
)
for a in rec.get("lobbying_activities") or ()
]
return row, issues
def _group(r: LdaFilingRow) -> tuple[int, int, int, str]:
return (r.registrant_id, r.client_id, r.filing_year, r.filing_period)
def supersede(rows: Sequence[LdaFilingRow]) -> set[str]:
"""The LDA supersede rule (D4), its only implementation: within each
(registrant, client, filing_year, filing_period) every report-type
filing except the latest ``dt_posted`` is superseded (ties go to the
later uuid). Registrations carry no amount and are never superseded."""
groups: dict[tuple[int, int, int, str], list[LdaFilingRow]] = {}
for r in rows:
if r.filing_type not in REGISTRATIONS:
groups.setdefault(_group(r), []).append(r)
gone: set[str] = set()
for members in groups.values():
latest = max(members, key=lambda r: (r.dt_posted, r.filing_uuid))
gone |= {r.filing_uuid for r in members if r is not latest}
return gone
def _stored(con: Any, rows: Iterable[LdaFilingRow]) -> dict[str, LdaFilingRow]:
"""Stored rows sharing a uuid or a supersede group with *rows*."""
cols = ", ".join(f.name for f in dataclasses.fields(LdaFilingRow))
rows = list(rows)
found: dict[str, LdaFilingRow] = {}
for part in _chunks(sorted({r.filing_uuid for r in rows}), 400):
got = con.execute(
f"SELECT {cols} FROM market.lda_filing WHERE filing_uuid IN "
f"({','.join('?' * len(part))})",
list(part),
).fetchall()
found.update({g[0]: LdaFilingRow(*g) for g in got})
keys = sorted({_group(r) for r in rows if r.filing_type not in REGISTRATIONS})
for part in _chunks(keys, 400):
got = con.execute(
f"SELECT {cols} FROM market.lda_filing WHERE "
"(registrant_id, client_id, filing_year, filing_period) IN "
"(SELECT * FROM (VALUES " + ", ".join(["(?, ?, ?, ?)"] * len(part)) + "))",
[v for k in part for v in k],
).fetchall()
found.update({g[0]: LdaFilingRow(*g) for g in got})
return found
def write_lda(
con: Any, rows: Sequence[LdaFilingRow], issues: Sequence[LdaIssueRow]
) -> int:
"""Store *rows* and their issue rows. The stored rows of every group the
batch touches are read back, :func:`supersede` runs over stored ∪ new and
the flags are rewritten, so an amendment written alone still retires the
stored original. A row that arrives without an entity keeps the entity a
stored copy was matched to. Returns the number of new filings."""
if not rows:
return 0
ensure_tables(con)
new = {r.filing_uuid: r for r in rows}
stored = _stored(con, new.values())
merged = dict(stored)
for uuid, r in new.items():
old = stored.get(uuid)
if old is not None and not r.entity_key and old.entity_key:
r = dataclasses.replace(
r, entity_key=old.entity_key, matched_by=old.matched_by
)
merged[uuid] = r
gone = supersede(list(merged.values()))
write_lda_filings(
con,
[
dataclasses.replace(r, superseded=u in gone)
for u, r in sorted(merged.items())
],
)
for part in _chunks(sorted(new), 400):
con.execute(
f"DELETE FROM market.lda_issue WHERE filing_uuid IN ({','.join('?' * len(part))})",
list(part),
)
write_lda_issues(con, [i for i in issues if i.filing_uuid in new])
return len(new)
# ── readers ──────────────────────────────────────────────────────────
def spend_by_year(con: Any, entity_key: str) -> dict[int, float]:
"""Reported amount per filing year, each filing counted once: its own
amount, never split across issue codes; superseded reports and
registrations excluded. A client's total is the sum of its own expenses
and the income of the firms that lobby for it."""
rows = con.execute(
"SELECT filing_year, SUM(amount) FROM market.lda_filing "
"WHERE entity_key = ? AND NOT superseded AND amount IS NOT NULL "
"GROUP BY filing_year ORDER BY filing_year",
[entity_key],
).fetchall()
return {int(y): float(v) for y, v in rows}
def filings_by_issue(con: Any, entity_key: str, code: str) -> list[str]:
"""Uuids of the entity's current (non-superseded) filings that list the
general issue *code*."""
rows = con.execute(
"SELECT DISTINCT f.filing_uuid FROM market.lda_filing f "
"JOIN market.lda_issue i USING (filing_uuid) "
"WHERE f.entity_key = ? AND i.general_issue_code = ? AND NOT f.superseded "
"ORDER BY 1",
[entity_key, code],
).fetchall()
return [r[0] for r in rows]
# ── names ────────────────────────────────────────────────────────────
def query_names(name: str, aliases: str) -> list[str]:
"""The distinct (by normalised form) names to search for: the entity's
own name first, then its ``|``-joined aliases."""
seen: dict[str, str] = {}
for n in (name, *aliases.split("|")):
k = norm_org(n)
if k and k not in seen:
seen[k] = n
return list(seen.values())
def alias_index(entities: Iterable[tuple[str, Iterable[str]]]) -> dict[str, str]:
"""Normalised name -> entity key, keys taken in sorted order so a shared
name goes to the first. Looking a name up here is
``alias_match(name, aliases, prefix=False)`` without the scan."""
out: dict[str, str] = {}
for key, names in sorted(entities, key=lambda e: e[0]):
for n in names:
k = norm_org(n)
if k and k not in out:
out[k] = key
return out
def match_client(name: str, index: Mapping[str, str]) -> str:
"""The entity whose name equals *name* after normalisation, else ``""``
(``... FOUNDATION`` is not ``...``)."""
return index.get(norm_org(name), "")
# ── fetching ─────────────────────────────────────────────────────────
class Budget:
"""At most *limit* network requests (0 = unlimited), and an optional
*stop* callable that ends the run (a time limit). A hoarded page costs
nothing."""
def __init__(self, limit: int = 0, stop: Callable[[], bool] | None = None) -> None:
self.limit = limit
self.stop = stop
self.used = 0
self.exhausted = False
self.why = ""
def take(self) -> bool:
if self.limit and self.used >= self.limit:
self.exhausted, self.why = True, "request limit"
return False
if self.stop is not None and self.stop():
self.exhausted, self.why = True, "time limit"
return False
self.used += 1
return True
def _page(
cl: httpx.Client,
url: str,
params: Mapping[str, Any] | None,
*,
pacer: Any,
path: Path | None,
refresh: bool,
stale_after: float | None,
budget: Budget | None,
) -> tuple[dict[str, Any], str] | None:
"""One page: the hoarded copy when fresh, else a download (hoarded, never
overwriting). ``None`` when the budget forbids the download."""
if path is not None:
have = http.newest(path)
fresh = have.is_file() and not refresh
if fresh and stale_after is not None:
fresh = (dt.datetime.now().timestamp() - have.stat().st_mtime) < stale_after
if fresh:
return json.loads(have.read_bytes()), str(have)
if budget is not None and not budget.take():
return None
r = http.get(cl, url, params=params, pacer=pacer, source=SOURCE)
try:
payload = r.json()
except ValueError:
payload = None
if not isinstance(payload, dict):
raise http.Refused(
SOURCE, r.status_code, "response is not JSON (a bot or challenge page?)"
)
where = path
if path is not None:
where = http.save(path, r.content)
os.utime(where) # an identical page is fresh again
http.manifest(where, str(r.request.url))
return payload, str(where or "")
def query_pages(
cl: httpx.Client,
params: Mapping[str, Any],
*,
pacer: Any,
cache_dir: Path | None = None,
stem: str = "q",
refresh: bool = False,
stale_after: float | None = None,
budget: Budget | None = None,
) -> Iterator[dict[str, Any]]:
"""Every filing of ``/filings/?<params>``, following ``next``. Each
record carries ``_source_file`` (the hoarded page). Pages are hoarded at
``<cache_dir>/<stem>.<n>.json``; a page older than *stale_after* seconds
(``None``: never) is fetched again and a changed body lands beside the old
one. A ``next`` link that leaves lda.gov, or a body that is not a JSON
object, is :class:`~market.http.Refused`."""
url: str = f"{LDA_API}filings/"
use: Mapping[str, Any] | None = {**params, "page_size": PAGE_SIZE}
n = 0
while url:
n += 1
path = cache_dir / f"{stem}.{n}.json" if cache_dir is not None else None
got = _page(
cl,
url,
use,
pacer=pacer,
path=path,
refresh=refresh,
stale_after=stale_after,
budget=budget,
)
if got is None:
return
payload, src = got
for rec in payload.get("results") or ():
yield {**rec, "_source_file": src}
url = payload.get("next") or ""
use = None
if url and httpx.URL(url).host != HOST:
raise http.Refused(SOURCE, 0, "next link leaves lda.gov")

View File

@@ -55,6 +55,17 @@ CREATE TABLE IF NOT EXISTS market.price_daily (
CREATE TABLE IF NOT EXISTS market.series (
series_id VARCHAR, symbol VARCHAR, source VARCHAR, year INTEGER,
month INTEGER, value DOUBLE, item_key VARCHAR
);
CREATE TABLE IF NOT EXISTS market.lda_filing (
filing_uuid VARCHAR, filing_type VARCHAR, filing_year INTEGER,
filing_period VARCHAR, dt_posted TIMESTAMP, registrant_id BIGINT,
registrant_name VARCHAR, client_id BIGINT, client_name VARCHAR,
income DOUBLE, expenses DOUBLE, amount DOUBLE, superseded BOOLEAN,
document_url VARCHAR, entity_key VARCHAR, matched_by VARCHAR,
source_file VARCHAR
);
CREATE TABLE IF NOT EXISTS market.lda_issue (
filing_uuid VARCHAR, general_issue_code VARCHAR, description VARCHAR
)
"""
@@ -216,6 +227,44 @@ class MonthlyRow:
item_key: str
@dataclass(frozen=True)
class LdaFilingRow:
"""One Lobbying Disclosure Act filing (LD-1 registration or LD-2 report).
``amount`` is the report's income (a registrant lobbying for clients) or
expenses (an organization lobbying for itself); a registration has none.
``superseded`` marks a report replaced by a later one of the same
registrant, client, year and period (``market.lda.supersede``)."""
filing_uuid: str
filing_type: str
filing_year: int
filing_period: str
dt_posted: dt.datetime # UTC, naive
registrant_id: int
registrant_name: str
client_id: int
client_name: str
income: float | None
expenses: float | None
amount: float | None
superseded: bool
document_url: str
entity_key: str # "" when the client is not a tracked entity
matched_by: str # "client" | ""
source_file: str
@dataclass(frozen=True)
class LdaIssueRow:
"""One lobbying activity of a filing: its general issue code and the
specific-issues text. Never carries money (a filing's amount is not
split across its issue codes)."""
filing_uuid: str
general_issue_code: str
description: str
def _insert(con: Any, table: str, rows: Sequence[Any], chunk: int = 400) -> int:
"""Insert *rows* with multi-row ``VALUES`` statements (``executemany`` is
a statement per row, far too slow for filing lists)."""
@@ -514,6 +563,53 @@ def read_series(con: Any, symbols: Sequence[str]) -> list[MonthlyRow]:
)
# ── lda_filing / lda_issue ───────────────────────────────────────────
def write_lda_filings(con: Any, rows: Sequence[LdaFilingRow]) -> int:
"""Upsert by ``filing_uuid``. Flags are the caller's: use
``market.lda.write_lda`` to set ``superseded``."""
ensure_tables(con)
for chunk in _chunks(sorted({r.filing_uuid for r in rows})):
con.execute(
"DELETE FROM market.lda_filing WHERE filing_uuid IN "
f"({','.join('?' * len(chunk))})",
list(chunk),
)
return _insert(con, "market.lda_filing", rows)
def read_lda_filings(con: Any, entity_key: str | None = None) -> list[LdaFilingRow]:
rows = _select(
con,
LdaFilingRow,
"market.lda_filing",
"entity_key = ?" if entity_key is not None else "",
[entity_key] if entity_key is not None else [],
)
return sorted((LdaFilingRow(*r) for r in rows), key=lambda f: f.filing_uuid)
def write_lda_issues(con: Any, rows: Sequence[LdaIssueRow]) -> int:
"""Replace every issue row of each ``filing_uuid`` in *rows*."""
ensure_tables(con)
for chunk in _chunks(sorted({r.filing_uuid for r in rows})):
con.execute(
"DELETE FROM market.lda_issue WHERE filing_uuid IN "
f"({','.join('?' * len(chunk))})",
list(chunk),
)
return _insert(con, "market.lda_issue", rows)
def read_lda_issues(con: Any) -> list[LdaIssueRow]:
rows = _select(con, LdaIssueRow, "market.lda_issue")
return sorted(
(LdaIssueRow(*r) for r in rows),
key=lambda i: (i.filing_uuid, i.general_issue_code, i.description),
)
# ── districts ────────────────────────────────────────────────────────

View File

@@ -1563,3 +1563,352 @@ def test_fts_cli_classify_limit_stops_between_rounds(env, monkeypatch, tmp_path)
# the link now rests on the second, still unlabelled passage
(link,) = T.read_links(c, basis="fts")
assert link.strength == "mention"
# ── lda ──────────────────────────────────────────────────────────────
def _lda_rec(**over):
rec = json.loads((FX / "lda_aafp_2024_q1.json").read_text())
rec.update(over)
return rec
def _lda_entities(c, *extra):
T.write_entities(
c,
[
T.EntityRow(
"AAFP",
"American Academy of Family Physicians",
"organization",
aliases="AMERICAN ACADEMY OF FAMILY PHYSICIANS",
),
T.EntityRow(
"PRIMARY-CARE-SEAT",
"Primary care rotating-seat societies",
"organization",
aliases="PRIMARY CARE ROTATING SEAT",
pseudo=True,
),
T.EntityRow(
"0000000001",
"SWEEP ONLY CO",
"company",
cik="0000000001",
aliases="SWEEP ONLY",
),
*extra,
],
)
@pytest.fixture
def lda(env, monkeypatch):
from market import lda as L
c, store, published, hoard = env
_lda_entities(c)
seen: list[httpx.Request] = []
monkeypatch.setattr(L, "new_pacer", lambda key=None: _Pacer())
monkeypatch.setattr(mk, "_lda_now", lambda: date(2026, 11, 13))
state = {"results": [_lda_rec()], "status": 200, "text": None}
def handler(request):
seen.append(request)
if state["status"] != 200:
return httpx.Response(state["status"], text="no")
if state["text"] is not None:
return httpx.Response(200, text=state["text"])
q = request.url.params
name = q.get("client_name") or ""
results = state["results"]
if name:
results = [
r for r in results if name.upper() in r["client"]["name"].upper()
]
year = q.get("filing_year")
if year:
results = [r for r in results if str(r["filing_year"]) == year]
return httpx.Response(
200,
json={
"count": len(results),
"next": None,
"previous": None,
"results": results,
},
)
monkeypatch.setattr(
http,
"client",
lambda source, key=None: httpx.Client(transport=httpx.MockTransport(handler)),
)
monkeypatch.setattr(http, "api_key", lambda source, env=None: None)
return c, store, published, hoard, seen, state
def test_lda_cli_entity_write(lda):
c, store, published, hoard, seen, state = lda
foundation = _lda_rec(
filing_uuid="f0000000-0000-0000-0000-000000000000",
client={
**_lda_rec()["client"],
"name": "AMERICAN ACADEMY OF FAMILY PHYSICIANS FOUNDATION",
},
)
state["results"] = [_lda_rec(), foundation]
T.write_gap(c, "lda:lda", "old")
res = runner.invoke(
app,
[
"market",
"lda",
"--entity",
"AAFP",
"--from",
"2024",
"--to",
"2024",
"--write",
],
)
assert res.exit_code == 0, res.output
rows = T.read_lda_filings(c)
assert [(r.filing_uuid[:8], r.entity_key, r.matched_by) for r in rows] == [
("df5f17c4", "AAFP", "client")
]
assert rows[0].amount == 825016.0 and rows[0].source_file.endswith(".1.json")
assert _count(c, "market.lda_issue") == 5
assert T.read_gaps(c) == []
assert published == [True]
assert {
(t, n)
for t, n in c.execute("SELECT table_name, rows FROM cms.ingest_log").fetchall()
} == {("market.lda_filing", 1), ("market.lda_issue", 5)}
assert seen and all(r.url.host == "lda.gov" for r in seen)
assert seen[0].url.params["client_name"] == "American Academy of Family Physicians"
assert seen[0].url.params["filing_year"] == "2024"
assert "authorization" not in seen[0].headers
files = list((hoard / "lda" / "2024").glob("*.1.json"))
assert files and all(
"american-academy-of-family-physicians" in f.name for f in files
)
assert "1 filings" in res.output and "1 clients" in res.output
assert "HCR 1" in res.output and "MMM 1" in res.output
assert [i.title for i in store.list_items() if "Lobbying" in i.title] == [
"Lobbying Disclosure Act filings, 2024"
]
def test_lda_cli_without_write_stores_nothing(lda):
c, _, published, _, seen, _ = lda
res = runner.invoke(app, ["market", "lda", "--from", "2024", "--to", "2024"])
assert res.exit_code == 0, res.output
assert "dry run: pass --write" in res.output
assert _count(c, "market.lda_filing") == 0
assert published == []
names = {r.url.params["client_name"] for r in seen}
assert "American Academy of Family Physicians" in names
assert not any("PRIMARY CARE" in n.upper() for n in names) # pseudo skipped
assert not any("SWEEP" in n.upper() for n in names) # not a seed company
def test_lda_cli_terms_offline(lda):
c, _, _, hoard, seen, state = lda
other = _lda_rec(
filing_uuid="a0000000-0000-0000-0000-000000000000",
client={**_lda_rec()["client"], "id": 5, "name": "SOME UNTRACKED CLIENT"},
)
state["results"] = [_lda_rec(), other]
cmd = [
"market",
"lda",
"--entity",
"AAFP",
"--terms",
"--from",
"2024",
"--to",
"2024",
]
res = runner.invoke(app, [*cmd, "--write"])
assert res.exit_code == 0, res.output
terms = [r for r in seen if "filing_specific_lobbying_issues" in r.url.params]
assert [r.url.params["filing_specific_lobbying_issues"] for r in terms] == list(
__import__("market.lda", fromlist=["x"]).LDA_TERMS
)
got = {
r.filing_uuid[:2]: (r.entity_key, r.matched_by) for r in T.read_lda_filings(c)
}
assert got == {"df": ("AAFP", "client"), "a0": ("", "")}
# a second run reads only the hoard: not one request leaves
n = len(seen)
again = runner.invoke(app, cmd)
assert again.exit_code == 0 and len(seen) == n
assert "2 filings" in again.output and "0 requests" in again.output
assert "terms 5" in again.output
def test_lda_cli_range_uses_all_dir_and_filters_years(lda):
c, _, _, hoard, seen, state = lda
old = _lda_rec(filing_uuid="b0000000-0000-0000-0000-000000000000", filing_year=2015)
state["results"] = [_lda_rec(), old]
res = runner.invoke(
app,
[
"market",
"lda",
"--entity",
"AAFP",
"--from",
"2020",
"--to",
"2024",
"--write",
],
)
assert res.exit_code == 0, res.output
assert "filing_year" not in seen[0].url.params
assert list((hoard / "lda" / "all").glob("*.1.json"))
assert [r.filing_year for r in T.read_lda_filings(c)] == [2024]
def test_lda_cli_refusal_prints_gap(lda):
c, _, published, _, seen, state = lda
state["status"] = 403
res = runner.invoke(
app,
[
"market",
"lda",
"--entity",
"AAFP",
"--from",
"2024",
"--to",
"2024",
"--write",
],
)
assert res.exit_code == 0, res.output
assert "gap: lda:lda: lda: HTTP 403" in res.output
assert [(g.source) for g in T.read_gaps(c)] == ["lda:lda"]
assert _count(c, "market.lda_filing") == 0
assert len(seen) == 1 # no workaround, no retry on a 403
state["status"], state["text"] = 200, "<html>Just a moment</html>"
res = runner.invoke(
app, ["market", "lda", "--entity", "AAFP", "--from", "2024", "--to", "2024"]
)
assert "gap: lda:lda:" in res.output and "not JSON" in res.output
assert len(T.read_gaps(c)) == 1 # no --write: not recorded again
def test_lda_cli_limit_and_minutes_stop_early_and_keep_the_gap(lda, monkeypatch):
c, _, _, _, seen, _ = lda
_lda_entities(
c,
T.EntityRow(
"ACP",
"American College of Physicians",
"organization",
aliases="AMERICAN COLLEGE OF PHYSICIANS",
),
)
T.write_gap(c, "lda:lda", "old")
res = runner.invoke(
app,
["market", "lda", "--from", "2024", "--to", "2024", "--limit", "1", "--write"],
)
assert res.exit_code == 0, res.output
assert len(seen) == 1 and "stopped: request limit" in res.output
assert [g.note for g in T.read_gaps(c)] == ["old"]
assert _count(c, "market.lda_filing") == 1
ticks = iter([0.0])
monkeypatch.setattr(mk.time, "monotonic", lambda: next(ticks, 10_000.0))
res = runner.invoke(
app,
[
"market",
"lda",
"--from",
"2024",
"--to",
"2024",
"--max-minutes",
"1",
"--refresh",
],
)
assert res.exit_code == 0, res.output
assert "stopped: time limit" in res.output
def test_lda_cli_bad_entity_and_empty_registry(lda, monkeypatch):
c, *_ = lda
res = runner.invoke(app, ["market", "lda", "--entity", "NOPE"])
assert res.exit_code == 2 and "unknown entity: NOPE" in res.output
res = runner.invoke(app, ["market", "lda", "--entity", "PRIMARY-CARE-SEAT"])
assert res.exit_code == 2
bare = duckdb.connect(":memory:")
monkeypatch.setattr(mk, "_read", lambda: bare)
res = runner.invoke(app, ["market", "lda"])
assert res.exit_code == 1 and "stack market entities --write" in res.output
def test_lda_cli_resupersedes_across_runs(lda):
c, _, _, _, _, state = lda
cmd = [
"market",
"lda",
"--entity",
"AAFP",
"--from",
"2024",
"--to",
"2024",
"--write",
]
assert runner.invoke(app, cmd).exit_code == 0
amend = _lda_rec(
filing_uuid="c0000000-0000-0000-0000-000000000000",
filing_type="1A",
dt_posted="2024-05-01T11:45:16-04:00",
expenses="900000.00",
)
state["results"] = [amend]
assert runner.invoke(app, [*cmd, "--refresh"]).exit_code == 0
got = {r.filing_uuid[:2]: r.superseded for r in T.read_lda_filings(c)}
assert got == {"df": True, "c0": False}
def test_lda_cli_year_order_and_seed_company_tracked(lda, monkeypatch):
c, _, _, _, seen, state = lda
monkeypatch.undo() # the real clock, only to read it
assert mk._lda_now() == date.today()
res = runner.invoke(app, ["market", "lda", "--from", "2025", "--to", "2024"])
assert res.exit_code == 2 and "is after --to" in res.output
def test_lda_cli_tracks_seed_companies_only(lda):
c, _, _, _, seen, state = lda
seed = load_seed()[0][0]
T.write_entities(
c,
[
T.EntityRow(
seed.cik,
seed.name,
"company",
cik=seed.cik,
aliases="|".join(seed.aliases),
)
],
)
res = runner.invoke(
app, ["market", "lda", "--entity", seed.cik, "--from", "2024", "--to", "2024"]
)
assert res.exit_code == 0, res.output
assert {r.url.params["client_name"] for r in seen} >= {seed.name}
assert "0 filings" in res.output

View File

@@ -0,0 +1,172 @@
{
"url": "https://lda.gov/api/v1/filings/df5f17c4-62a7-4d7f-8ebe-aeb15147f396/",
"filing_uuid": "df5f17c4-62a7-4d7f-8ebe-aeb15147f396",
"filing_type": "Q1",
"filing_type_display": "1st Quarter - Report",
"filing_year": 2024,
"filing_period": "first_quarter",
"filing_period_display": "1st Quarter (Jan 1 - Mar 31)",
"filing_document_url": "https://lda.gov/filings/public/filing/df5f17c4-62a7-4d7f-8ebe-aeb15147f396/print/",
"filing_document_content_type": "text/html",
"income": null,
"expenses": "825016.00",
"expenses_method": "C",
"expenses_method_display": "C",
"posted_by_name": null,
"dt_posted": "2024-04-15T15:36:27-04:00",
"termination_date": null,
"registrant_country": "United States of America",
"registrant_ppb_country": null,
"registrant_address_1": "11400 TOMAHAWK CREEK PARKWAY",
"registrant_address_2": null,
"registrant_different_address": false,
"registrant_city": "LEAWOOD",
"registrant_state": "KS",
"registrant_zip": "66211",
"registrant": {
"id": 1342,
"url": "https://lda.gov/api/v1/registrants/1342/",
"house_registrant_id": 32180,
"name": "AMERICAN ACADEMY OF FAMILY PHYSICIANS",
"description": null,
"address_1": "11400 TOMAHAWK CREEK PARKWAY",
"address_2": null,
"address_3": null,
"address_4": null,
"city": "LEAWOOD",
"state": "KS",
"state_display": "Kansas",
"zip": "66211",
"country": "US",
"country_display": "United States of America",
"ppb_country": "US",
"ppb_country_display": "United States of America",
"contact_name": null,
"contact_telephone": null,
"dt_updated": "2026-07-22T14:55:32.986947-04:00"
},
"client": {
"id": 102605,
"url": "https://lda.gov/api/v1/clients/102605/",
"client_id": 12,
"name": "AMERICAN ACADEMY OF FAMILY PHYSICIANS",
"general_description": null,
"client_government_entity": false,
"client_self_select": true,
"state": "KS",
"state_display": "Kansas",
"country": "US",
"country_display": "United States of America",
"ppb_state": "KS",
"ppb_state_display": "Kansas",
"ppb_country": "US",
"ppb_country_display": "United States of America",
"effective_date": "2007-08-02"
},
"lobbying_activities": [
{
"general_issue_code": "BUD",
"general_issue_code_display": "Budget/Appropriations",
"description": "No Bill No. Teaching Health Centers GME; Community Health Centers, National Health Service Corps No Bill No. FY 2025 Appropriations",
"foreign_entity_issues": "",
"lobbyists": [],
"government_entities": [
{
"id": 137,
"name": "Health Resources & Services Administration (HRSA)"
},
{
"id": 2,
"name": "HOUSE OF REPRESENTATIVES"
},
{
"id": 1,
"name": "SENATE"
}
]
},
{
"general_issue_code": "EDU",
"general_issue_code_display": "Education",
"description": "No Bill No. - Congressional Primary Care Caucus No Bill No. - Teaching Health Centers GME; Community Health Centers, National Health Service Corps No Bill No. - Rural Residency Planning and Development Act (S.704/H.R. 1202) - REDI Act (H.R. 2569) - DOC Act (H.R. 4986) - Student Loan Interest Elimination Act (H.R. 7416) - Closing The College Hunger Gap Act",
"foreign_entity_issues": "",
"lobbyists": [],
"government_entities": [
{
"id": 2,
"name": "HOUSE OF REPRESENTATIVES"
},
{
"id": 1,
"name": "SENATE"
}
]
},
{
"general_issue_code": "HCR",
"general_issue_code_display": "Health Issues",
"description": "No Bill No. - Congressional Primary Care Caucus NO Bill No. - Teaching Health Centers GME; Community Health Centers, National Health Service Corps No Bill No. - COVID-19 Vaccines No Bill No. - PAHPA Reauthorization NO Bill No. - Medicare Physician Payment Reform No Bill No. - Black Maternal Health Momnibus Act No Bill No. - Physician Workforce No Bill No. - Prior authorization/reducing administrative burden NO Bill No. - Health care affordability, including Medicare physician payments and site neutral payments, anti-competitive contracting, and the No Surprises Act No Bill No. - Black Maternal Health Momnibus Act No Bill No. - DATA in Public Health Act No Bill No. - Complete Care Act No Bill No. - Health Communication Access and Resources for Everyone Act No Bill No. - Tobacco Users Quit Act(S.704/H.R. 1202) REDI Act No Bill No. - FY2024 NDAA No Bill No. - Vaccine commercialization No Bill No. - VA Standards of Practice No Bill No. - MATE Improvement Act No Bill No. - SPEAK Act of 2023 No Bill No. - Access to Donor Milk Act NO Bill No. - Health Communication Access and Resources for Everyone Act No Bill No. - Primary and Virtual Care Affordability Act No Bill No. - Advancing Menopause Care and Mid-Life Women's Health Act (S. 230/H.R. 834) Rural Physician Workforce Production Act (S. 862) Restoring America's Health Care Workforce and Readiness Act (H.R. 498) 988 Lifeline Cybersecurity Responsibility Act (H.R. 1114) Long-COVID Recovery Now Act (S. 114/H.R. 766) Preventive Health Savings Act (S. 923) Better Mental Health for Americans (H.R. 286) Healthcare Providers' Safety Act (H.R. 2569) DOC Act (H.R. 1770) Equitable Community Access to Pharmacist Services Act (H.R. 2630/S.652) Safe Step Act (H.R. 3800) Chronic Disease Flexible Coverage Act (H.R. 3029) Primary Care Enhancement Act (H.R. 5378) Lower Cost More Transparency Act (H.R. 2584) Safety from Violence for Healthcare Employees Act (H.R. 4392/S.2188) PrEP Access and Coverage Act (H.R. 6067) Early Childhood Nutrition Improvement Act (S. 3295/H.R. 5569) Child Care Nutrition Enhancement Act (H.R. 1117) Advancing Safe Medications for Moms and Babies Act (H.R. 5909) Care for Grieving Families Act (H.R. 1616/S.807) Comprehensive Access to Resources and Education (CARE) for Long COVID Act (H.R. 3258) Targeting Resources for Equitable Access to Treatment (TREAT) Long COVID Act (S. 2560) Long COVID Support Act (H.R. 6038/S.3108) Teen E-Cigarette and Tobacco Addition (PROTECT) Act (H.R. 6103/S.3137) Support Through Loss Act (S. 3070) Youth Prevention and Recovery Reauthorization Act (H.R. 7381) - Healthcare Enhancement and Learning Through Harnessing Artificial Intelligence Act (S. Res. 597) - A Resolution Creating a Health Workforce Well-Being Day of Awareness (S. 3740) STRONGER Act (H.R. 6965) - EPIPEN Act (S.3779) - Child Suicide Prevention and Lethal Means Safety Act (S. 3679/H.R. 7153) - Lorna Breen Reauthorization Act (H.R. 3752) Parity Enforcement Act",
"foreign_entity_issues": "",
"lobbyists": [],
"government_entities": [
{
"id": 34,
"name": "Health & Human Services, Dept of (HHS)"
},
{
"id": 2,
"name": "HOUSE OF REPRESENTATIVES"
},
{
"id": 1,
"name": "SENATE"
}
]
},
{
"general_issue_code": "MMM",
"general_issue_code_display": "Medicare/Medicaid",
"description": "No Bill No. - Congressional Primary Care Caucus No Bill No. - Black Maternal Health Momnibus Act No Bill No. - Medicare Physician Payment Reform No Bill No. - MACRA Implementation No Bill No. - CY2024 Medicare Physician Fee Schedule No Bill No. - CY 2024 Medicare Inpatient Prospective Payment System No Bill No. - Site Neutrality and Consolidation No Bill No. - CMS Prior Authorization Rules No Bill No. - Tobacco Users Quiet Act No Bill No. - G2211 Code (Physician Fee Schedule) No Bill No. - Reducing Medically Unnecessary Delays in Care Act No Bill No. - G2211 implementation/modifier 25 (H.R. 952) Kids Access to Primary Care Act (H.R. 2400/S. 1165) The Reentry Act (H.R. 3074) Due Process Continuity of Care Act (H.R. 3766) Extending Access to Addiction Treatment Act (H.R. 4950/S. 2841) Improve Addiction Care Act (H.R. 4771) Children's Health Insurance Program Permanency Act (H.R. 4968) GOLD Card Act of 2023 (S. 2556) Improving Care for Youth Act (H.R. 5013) Value in Health Care Act (S. 2816) Medicaid for Every Child Act (H.R. 6545) Physician Fee Schedule Update and Improvements Act (H.R. 5434/S.3138) Stabilize Medicaid and CHIP Coverage Act (H.R. 5395) SURS Extension Act (H.R. 3487/S. 3805) No Fees for EFTs Act (S. 1316) Save Children's Coverage Act (H.R. 6997/S. 3010) Nutrition CARE Act (H.R. 6780/S. 2133) - Medically Tailored Home-Delivered Meals Demonstration Pilot Act",
"foreign_entity_issues": "",
"lobbyists": [],
"government_entities": [
{
"id": 136,
"name": "Centers For Medicare and Medicaid Services (CMS)"
},
{
"id": 34,
"name": "Health & Human Services, Dept of (HHS)"
},
{
"id": 2,
"name": "HOUSE OF REPRESENTATIVES"
},
{
"id": 1,
"name": "SENATE"
}
]
},
{
"general_issue_code": "IMM",
"general_issue_code_display": "Immigration",
"description": "(S. 665) Conrad 30 and Physician Access Act (S. 2719) Directing Our Country's Transfer of Residency Slots (H.R. 6298/S. 3247) Stop Shackling and Detaining Pregnant Women Act (H.R. 6205/S.3211) Healthcare Workforce Resilience Act",
"foreign_entity_issues": "",
"lobbyists": [],
"government_entities": [
{
"id": 2,
"name": "HOUSE OF REPRESENTATIVES"
},
{
"id": 1,
"name": "SENATE"
}
]
}
],
"conviction_disclosures": [],
"foreign_entities": [],
"affiliated_organizations": []
}

View File

@@ -12,6 +12,7 @@ MODULES = [
"market.seed",
"market.edgar",
"market.tiingo",
"market.lda",
]
_PROBE = """

405
tests/market/test_lda.py Normal file
View File

@@ -0,0 +1,405 @@
"""market.lda: lda.gov filings, amounts, the supersede rule, name matching."""
from __future__ import annotations
import json
import os
import time
from dataclasses import replace
from datetime import datetime
from pathlib import Path
import duckdb
import httpx
import pytest
from market import http
from market import lda as L
from market import tables as T
FX = Path(__file__).parent / "fixtures"
def aafp() -> dict:
return json.loads((FX / "lda_aafp_2024_q1.json").read_text())
@pytest.fixture
def con():
c = duckdb.connect(":memory:")
T.ensure_tables(c)
yield c
c.close()
class Pacer:
def __init__(self):
self.n = 0
def wait(self):
self.n += 1
def row(
uuid,
typ,
posted,
*,
reg=1,
cli=2,
year=2024,
period="first_quarter",
amount=100.0,
entity="AAFP",
superseded=False,
income=None,
expenses=None,
):
return T.LdaFilingRow(
uuid,
typ,
year,
period,
datetime.fromisoformat(posted),
reg,
"REG",
cli,
"CLI",
income,
expenses,
amount,
superseded,
"u",
entity,
"client" if entity else "",
"f.json",
)
def page(results, nxt=None, count=None):
return {
"count": count if count is not None else len(results),
"next": nxt,
"previous": None,
"results": results,
}
# ── transport ────────────────────────────────────────────────────────
def test_lda_requests_go_to_lda_gov():
assert L.LDA_API == "https://lda.gov/api/v1/"
seen = []
def handler(request):
seen.append(request)
return httpx.Response(200, json=page([aafp()]))
cl = httpx.Client(transport=httpx.MockTransport(handler))
out = list(L.query_pages(cl, {"client_name": "X"}, pacer=Pacer()))
assert len(out) == 1
assert [r.url.host for r in seen] == ["lda.gov"]
assert "lda.senate.gov" not in str(seen[0].url)
assert seen[0].url.params["page_size"] == "25"
assert seen[0].url.path == "/api/v1/filings/"
def test_lda_pacer_anonymous_and_keyed():
assert L.new_pacer(None).min_interval == 4.2
assert L.new_pacer("k").min_interval == 0.55
anon = http.client("lda", None)
keyed = http.client("lda", "k")
try:
assert "authorization" not in anon.headers
assert keyed.headers["Authorization"] == "Token k"
assert anon.headers["User-Agent"] == http.USER_AGENT
finally:
anon.close()
keyed.close()
def test_query_pages_follows_next():
seen = []
p2 = "https://lda.gov/api/v1/filings/?client_name=X&page=2&page_size=25"
def handler(request):
seen.append(request)
if request.url.params.get("page") == "2":
return httpx.Response(200, json=page([{"filing_uuid": "b"}]))
return httpx.Response(200, json=page([{"filing_uuid": "a"}], nxt=p2))
pacer = Pacer()
cl = httpx.Client(transport=httpx.MockTransport(handler))
out = list(L.query_pages(cl, {"client_name": "X"}, pacer=pacer))
assert [r["filing_uuid"] for r in out] == ["a", "b"]
assert len(seen) == 2 and pacer.n == 2
def test_query_pages_refuses_a_foreign_next_and_non_json():
def foreign(request):
return httpx.Response(
200, json=page([], nxt="https://evil.example/api/v1/filings/?page=2")
)
cl = httpx.Client(transport=httpx.MockTransport(foreign))
with pytest.raises(http.Refused):
list(L.query_pages(cl, {"client_name": "X"}, pacer=Pacer()))
def bot(request):
return httpx.Response(200, text="<html>Just a moment...</html>")
cl = httpx.Client(transport=httpx.MockTransport(bot))
with pytest.raises(http.Refused) as e:
list(L.query_pages(cl, {"client_name": "X"}, pacer=Pacer()))
assert "not JSON" in str(e.value)
def listy(request):
return httpx.Response(200, json=[1, 2])
cl = httpx.Client(transport=httpx.MockTransport(listy))
with pytest.raises(http.Refused):
list(L.query_pages(cl, {"client_name": "X"}, pacer=Pacer()))
def test_query_pages_hoards_and_reuses(tmp_path, monkeypatch):
monkeypatch.setattr(http, "hoard_root", lambda: tmp_path)
calls = []
def handler(request):
calls.append(request)
return httpx.Response(200, json=page([aafp()]))
cl = httpx.Client(transport=httpx.MockTransport(handler))
d = tmp_path / "lda" / "2024"
kw = dict(pacer=Pacer(), cache_dir=d, stem="q")
first = list(L.query_pages(cl, {"client_name": "X"}, **kw))
again = list(L.query_pages(cl, {"client_name": "X"}, **kw))
assert len(calls) == 1 and len(first) == len(again) == 1
assert first[0]["_source_file"].endswith("lda/2024/q.1.json")
manifest = (tmp_path / http.MANIFEST).read_text()
assert "lda/2024/q.1.json" in manifest and "client_name" in manifest
assert "Authorization" not in manifest
def test_query_pages_stale_refetch_never_overwrites(tmp_path, monkeypatch):
monkeypatch.setattr(http, "hoard_root", lambda: tmp_path)
bodies = [
page([{"filing_uuid": "a"}]),
page([{"filing_uuid": "a"}, {"filing_uuid": "b"}]),
]
calls = []
def handler(request):
calls.append(request)
return httpx.Response(200, json=bodies[min(len(calls) - 1, 1)])
cl = httpx.Client(transport=httpx.MockTransport(handler))
d = tmp_path / "lda" / "all"
kw = dict(pacer=Pacer(), cache_dir=d, stem="q", stale_after=3600.0)
list(L.query_pages(cl, {"client_name": "X"}, **kw))
old = d / "q.1.json"
os.utime(old, (time.time() - 7200, time.time() - 7200))
got = list(L.query_pages(cl, {"client_name": "X"}, **kw))
assert len(calls) == 2 and [r["filing_uuid"] for r in got] == ["a", "b"]
assert json.loads(old.read_text())["results"] == [{"filing_uuid": "a"}]
assert len(list(d.glob("q.1.*.json"))) == 1 # the new body landed beside
# a stale page that comes back identical is touched, so it is fresh again
os.utime(old, (time.time() - 7200, time.time() - 7200))
calls.clear()
bodies[:] = [bodies[0], bodies[0]]
list(L.query_pages(cl, {"client_name": "Y"}, **kw))
list(L.query_pages(cl, {"client_name": "Y"}, **kw))
assert len(calls) <= 2
def test_query_pages_stops_at_the_request_budget():
nxt = "https://lda.gov/api/v1/filings/?client_name=X&page=2&page_size=25"
def handler(request):
return httpx.Response(200, json=page([{"filing_uuid": "a"}], nxt=nxt))
cl = httpx.Client(transport=httpx.MockTransport(handler))
budget = L.Budget(1)
out = list(L.query_pages(cl, {"client_name": "X"}, pacer=Pacer(), budget=budget))
assert len(out) == 1 and budget.exhausted and budget.used == 1
# a spent budget fetches nothing at all
assert (
list(L.query_pages(cl, {"client_name": "X"}, pacer=Pacer(), budget=budget))
== []
)
unlimited = L.Budget(0)
assert unlimited.take() and not unlimited.exhausted
# ── rows ─────────────────────────────────────────────────────────────
def test_to_filing_amounts():
f, issues = L.to_filing(
aafp(), entity_key="AAFP", matched_by="client", source_file="s"
)
assert f.filing_uuid == "df5f17c4-62a7-4d7f-8ebe-aeb15147f396"
assert f.filing_type == "Q1" and f.filing_period == "first_quarter"
assert f.filing_year == 2024
assert f.amount == 825016.0 and f.income is None and f.expenses == 825016.0
assert (f.registrant_id, f.client_id) == (1342, 102605)
assert f.client_name == "AMERICAN ACADEMY OF FAMILY PHYSICIANS"
assert f.dt_posted == datetime(2024, 4, 15, 19, 36, 27) # UTC
assert f.superseded is False and (f.entity_key, f.matched_by) == ("AAFP", "client")
assert f.document_url.startswith("https://lda.gov/filings/public/filing/")
assert "BUD" in {i.general_issue_code for i in issues}
assert {i.general_issue_code for i in issues} >= {"HCR", "MMM"}
assert all(i.filing_uuid == f.filing_uuid for i in issues)
# no lobbyist, no contact is carried into any row
assert "QUINN" not in repr((f, issues)) and "TULLY" not in repr((f, issues))
def test_to_filing_income_beats_expenses_and_null_fields():
rec = aafp()
rec.update(income="60000.00", expenses=None, filing_period=None, dt_posted=None)
rec["lobbying_activities"] = None
f, issues = L.to_filing(rec, entity_key="", matched_by="", source_file="s")
assert f.amount == 60000.0 and f.income == 60000.0 and f.expenses is None
assert f.filing_period == "" and issues == []
assert f.dt_posted == datetime(1970, 1, 1)
rec.update(income="10.00", expenses="99.00")
assert (
L.to_filing(rec, entity_key="", matched_by="", source_file="s")[0].amount
== 10.0
)
@pytest.mark.parametrize("kind", ["RR", "RA"])
def test_registration_has_no_amount(kind):
rec = aafp()
rec.update(filing_type=kind, expenses="100.00", income=None)
f, _ = L.to_filing(rec, entity_key="", matched_by="", source_file="s")
assert f.amount is None and f.expenses == 100.0
# ── supersede ────────────────────────────────────────────────────────
def test_amendment_supersedes_original():
q1 = row("q1", "Q1", "2024-04-15T12:00:00")
a1 = row("a1", "1A", "2024-05-01T12:00:00")
assert L.supersede([q1, a1]) == {"q1"}
assert L.supersede([a1, q1]) == {"q1"}
other = row("q2", "Q2", "2024-07-01T00:00:00", period="second_quarter")
third = row("p3", "Q1", "2024-04-20T00:00:00", reg=9)
assert L.supersede([q1, a1, other, third]) == {"q1"}
def test_supersede_ties_and_registrations():
a = row("a", "Q1", "2024-04-15T12:00:00")
b = row("b", "1A", "2024-04-15T12:00:00")
assert L.supersede([a, b]) == {"a"} # equal posting: the later uuid wins
rr = row("r1", "RR", "2024-01-01T00:00:00", amount=None, period="")
ra = row("r2", "RA", "2024-02-01T00:00:00", amount=None, period="")
assert L.supersede([rr, ra]) == set()
assert L.supersede([]) == set()
def test_issue_codes_never_split_amount(con):
f = row("u", "Q1", "2024-04-15T00:00:00", amount=300.0)
issues = [T.LdaIssueRow("u", c, "d") for c in ("HCR", "MMM", "BUD")]
L.write_lda(con, [f], issues)
assert L.spend_by_year(con, "AAFP") == {2024: 300.0}
assert L.spend_by_year(con, "NOPE") == {}
def test_spend_ignores_superseded_and_unamounted(con):
rows = [
row("q1", "Q1", "2024-04-15T00:00:00", amount=100.0),
row("a1", "1A", "2024-05-01T00:00:00", amount=150.0),
row("n", "Q2", "2024-07-01T00:00:00", amount=None, period="second_quarter"),
row("y25", "Q1", "2025-04-01T00:00:00", amount=7.0, year=2025),
]
L.write_lda(con, rows, [])
assert L.spend_by_year(con, "AAFP") == {2024: 150.0, 2025: 7.0}
def test_write_lda_resupersedes_with_stored_rows(con):
q1 = row("q1", "Q1", "2024-04-15T00:00:00")
L.write_lda(con, [q1], [T.LdaIssueRow("q1", "HCR", "x")])
assert not T.read_lda_filings(con)[0].superseded
a1 = row("a1", "1A", "2024-05-01T00:00:00", amount=120.0)
L.write_lda(con, [a1], [T.LdaIssueRow("a1", "MMM", "y")])
got = {r.filing_uuid: r.superseded for r in T.read_lda_filings(con)}
assert got == {"q1": True, "a1": False}
assert {i.filing_uuid for i in T.read_lda_issues(con)} == {"q1", "a1"}
# writing the old one again does not resurrect it
L.write_lda(con, [q1], [T.LdaIssueRow("q1", "HCR", "x")])
got = {r.filing_uuid: r.superseded for r in T.read_lda_filings(con)}
assert got == {"q1": True, "a1": False}
assert L.spend_by_year(con, "AAFP") == {2024: 120.0}
def test_write_lda_keeps_a_stored_entity_and_replaces_issues(con):
f = row("u", "Q1", "2024-04-15T00:00:00")
L.write_lda(
con, [f], [T.LdaIssueRow("u", "HCR", "x"), T.LdaIssueRow("u", "BUD", "z")]
)
blind = replace(f, entity_key="", matched_by="")
n = L.write_lda(con, [blind], [T.LdaIssueRow("u", "MMM", "y")])
got = T.read_lda_filings(con)
assert n == 1 and len(got) == 1 and got[0].entity_key == "AAFP"
assert got[0].matched_by == "client"
assert [i.general_issue_code for i in T.read_lda_issues(con)] == ["MMM"]
assert L.write_lda(con, [], []) == 0
def test_write_lda_registration_is_never_superseded(con):
rr = row("r1", "RR", "2024-01-01T00:00:00", amount=None, period="")
ra = row("r2", "RA", "2024-02-01T00:00:00", amount=None, period="")
L.write_lda(con, [rr, ra], [])
assert [r.superseded for r in T.read_lda_filings(con)] == [False, False]
def test_filings_by_issue(con):
a = row("a", "Q1", "2024-04-15T00:00:00")
b = row("b", "Q2", "2024-07-15T00:00:00", period="second_quarter")
L.write_lda(
con,
[a, b],
[
T.LdaIssueRow("a", "HCR", "x"),
T.LdaIssueRow("a", "HCR", "again"),
T.LdaIssueRow("b", "BUD", "y"),
],
)
assert L.filings_by_issue(con, "AAFP", "HCR") == ["a"]
assert L.filings_by_issue(con, "AAFP", "BUD") == ["b"]
assert L.filings_by_issue(con, "AAFP", "TAX") == []
assert L.filings_by_issue(con, "OTHER", "HCR") == []
# ── name matching ────────────────────────────────────────────────────
def test_name_post_filter_drops_foundation():
index = L.alias_index(
[
(
"AAFP",
[
"American Academy of Family Physicians",
"AMERICAN ACADEMY OF FAMILY PHYSICIANS",
],
)
]
)
assert L.match_client("AMERICAN ACADEMY OF FAMILY PHYSICIANS", index) == "AAFP"
assert (
L.match_client("American Academy of Family Physicians, Inc.", index) == "AAFP"
)
assert (
L.match_client("AMERICAN ACADEMY OF FAMILY PHYSICIANS FOUNDATION", index) == ""
)
assert L.match_client("", index) == ""
def test_alias_index_first_key_wins_and_skips_blank():
index = L.alias_index([("B", ["Same Name", ""]), ("A", ["SAME NAME"])])
assert L.match_client("same name", index) == "A" # keys are taken in sorted order

View File

@@ -41,6 +41,8 @@ def test_ensure_tables_idempotent():
"source_gap",
"price_daily",
"series",
"lda_filing",
"lda_issue",
}
@@ -119,9 +121,39 @@ PRICE = TI.PriceRow(
date(2026, 11, 12),
"eod/OSH/x.json",
)
LDA_FILING = T.LdaFilingRow(
"df5f17c4-62a7-4d7f-8ebe-aeb15147f396",
"Q1",
2024,
"first_quarter",
dt.datetime(2024, 4, 15, 19, 36, 27),
1342,
"AMERICAN ACADEMY OF FAMILY PHYSICIANS",
102605,
"AMERICAN ACADEMY OF FAMILY PHYSICIANS",
None,
825016.0,
825016.0,
False,
"https://lda.gov/filings/public/filing/df5f/print/",
"AAFP",
"client",
"f.json",
)
LDA_ISSUE = T.LdaIssueRow(LDA_FILING.filing_uuid, "BUD", "No Bill No.")
SERIES = TI.MonthlyRow("tiingo:OSH:tri", "OSH", "tiingo", 2021, 1, 101.5, "KEY")
ROUNDTRIP = {
"lda_filing": (
LDA_FILING,
lambda c, r: T.write_lda_filings(c, [r]),
lambda c: T.read_lda_filings(c),
),
"lda_issue": (
LDA_ISSUE,
lambda c, r: T.write_lda_issues(c, [r]),
lambda c: T.read_lda_issues(c),
),
"entity": (
ENTITY,
lambda c, r: T.write_entities(c, [r]),
@@ -178,6 +210,27 @@ def test_write_empty_is_noop(con):
assert T.write_entities(con, []) == 0
assert T.write_filings(con, "1", []) == 0
assert T.write_securities(con, "1", []) == 0
assert T.write_lda_filings(con, []) == 0
assert T.write_lda_issues(con, []) == 0
def test_lda_readers_filter_by_entity(con):
other = replace_entity(LDA_FILING, "uuid-2", "OTHER")
T.write_lda_filings(con, [LDA_FILING, other])
assert [r.entity_key for r in T.read_lda_filings(con, "OTHER")] == ["OTHER"]
assert len(T.read_lda_filings(con)) == 2
T.write_lda_issues(con, [LDA_ISSUE, T.LdaIssueRow("uuid-2", "HCR", "x")])
T.write_lda_issues(con, [T.LdaIssueRow(LDA_FILING.filing_uuid, "MMM", "y")])
assert sorted(i.general_issue_code for i in T.read_lda_issues(con)) == [
"HCR",
"MMM",
]
def replace_entity(row, uuid, entity):
import dataclasses
return dataclasses.replace(row, filing_uuid=uuid, entity_key=entity)
def test_entities_replace_by_key_and_filter_by_kind(con):