Files
stack/tests/market/test_edgar.py
kert 0d8c9740b1
Some checks failed
CI / lint (push) Successful in 1m53s
CI / notebooks-smoke (push) Successful in 2m15s
Deploy / changes (push) Successful in 20s
CI / test (push) Failing after 6m52s
Infra CI / zotero (push) Successful in 2m26s
Infra CI / notebooks (push) Successful in 4m17s
Infra CI / api (push) Successful in 1m46s
Infra CI / docs (push) Successful in 2m22s
Infra CI / llm (push) Successful in 1m34s
Infra CI / mc (push) Successful in 1m7s
Deploy / notebooks (push) Has been skipped
Infra CI / bcda (push) Successful in 2m50s
Deploy / zotero (push) Has been skipped
Deploy / docs (push) Has been skipped
Deploy / api (push) Successful in 2m42s
Deploy / bcda (push) Successful in 3m39s
Deploy / mc (push) Has been skipped
Deploy / llm (push) Successful in 2m3s
Deploy / report (push) Successful in 19s
fix(market): priced flag on securities (symbol records never priced), ELV PFS link from its 10-K, CI unpriced
2026-11-12 23:52:51 -05:00

482 lines
17 KiB
Python

"""market.edgar: parsing, entity building, curated links, hoarded fetches."""
from __future__ import annotations
import json
from datetime import date
from pathlib import Path
import httpx
import pytest
from bib.store import Store
from market import edgar, http
from market.seed import Cite, SeedCompany, SeedLink, SeedOrg, SeedSecurity, load_seed
from market.tables import EntityRow
FX = Path(__file__).parent / "fixtures"
def _json(name):
return json.loads((FX / name).read_text())
class _Pacer:
def wait(self):
pass
def _seed(handle):
return next(c for c in load_seed()[0] if c.handle == handle)
def test_cik10():
assert edgar.cik10(790526) == "0000790526"
assert edgar.cik10("0000790526") == "0000790526"
def test_parse_tickers():
got = edgar.parse_tickers(_json("company_tickers.json"))
assert got["0000790526"] == ["RDNT"] and len(got) == 3
dup = {
"0": {"cik_str": 1, "ticker": "A", "title": "x"},
"1": {"cik_str": 1, "ticker": "A", "title": "x"},
"2": {"cik_str": 1, "ticker": "B", "title": "x"},
}
assert edgar.parse_tickers(dup) == {"0000000001": ["A", "B"]}
def test_parse_sic_atom():
assert edgar.parse_sic_atom((FX / "sic_8082.atom").read_bytes()) == [
"0001725255",
"0001468328",
]
def test_parse_sic_atom_without_namespace_and_empty_cik():
xml = b"<feed><entry><content><cik>12</cik></content></entry><entry><cik> </cik></entry></feed>"
assert edgar.parse_sic_atom(xml) == []
ns = (
b'<feed xmlns="http://www.w3.org/2005/Atom"><entry><content>'
b"<cik>12</cik></content></entry></feed>"
)
assert edgar.parse_sic_atom(ns) == ["0000000012"]
def test_submission_pages():
assert edgar.submission_pages(_json("submissions_CIK0001564406.json")) == [
"CIK0001564406-submissions-001.json"
]
assert edgar.submission_pages({}) == []
def test_filings_follow_files_pages():
sub = _json("submissions_CIK0001564406.json")
page = _json("CIK0001564406-submissions-001.json")
rows = edgar.filings_from_submissions(sub, [page])
assert len(rows) == 5
row = next(r for r in rows if r.adsh == "0001193125-23-132570")
assert row.items == "1.01,1.02,2.01,3.01,3.03,5.01,5.02,5.03,8.01,9.01"
assert row.accepted == "2023-05-02T20:42:01.000Z"
assert row.cik == "0001564406" and row.filed == date(2023, 5, 2)
assert row.report_date == date(2023, 5, 2)
assert next(r for r in rows if r.form == "15-12G").report_date is None
assert any(r.report_date == date(2023, 3, 31) for r in rows)
# a repeated page adds nothing
assert len(edgar.filings_from_submissions(sub, [page, page])) == 5
assert len(edgar.filings_from_submissions(sub)) == 3
def test_entity_from_osh_submissions():
sub = _json("submissions_CIK0001564406.json")
e = edgar.entity_from_submissions(sub, _seed("OSH"))
assert e.key == e.cik == "0001564406" and e.sic == "8000"
assert e.status == "acquired" and e.ended_on == date(2023, 5, 2)
assert e.aliases == "OAK STREET HEALTH" and e.successor == "0000064803"
assert e.kind == "company" and "0001564406" in e.source_url
def test_entity_without_seed_uses_edgar_names():
sub = {
"cik": "5",
"name": "Foo Health, Inc.",
"sic": "8082",
"sicDescription": "Home Health",
"tickers": ["FOO"],
"formerNames": [{"name": "Foo Care Corp"}, {"name": "Foo Health Inc"}],
}
e = edgar.entity_from_submissions(sub, None)
assert e.aliases == "FOO HEALTH|FOO CARE" and e.status == "listed"
assert e.name == "Foo Health, Inc." and e.ended_on is None
assert edgar.entity_from_submissions({"cik": "5"}, None).status == "unlisted"
def test_entity_from_seed_alone():
e = edgar.entity_from_submissions({}, _seed("HCA"))
assert e.key == "0000860730" and e.sic == "" and e.name.startswith("HCA")
def test_delisted_seed_entity_kept_without_current_ticker():
tickers = edgar.parse_tickers(_json("company_tickers.json"))
assert "0000896262" not in tickers
sub = {"cik": "0000896262", "name": "AMEDISYS INC", "sic": "8082", "tickers": []}
seed = _seed("AMED")
e = edgar.entity_from_submissions(sub, seed)
assert e.key == "0000896262" and e.status == "acquired"
secs = edgar.securities_for(sub, seed, tickers.get("0000896262", []))
assert secs[0] == edgar.SecurityRow(
"0000896262", "AMED", "NASDAQ", None, date(2025, 8, 14), "seed"
)
assert len(secs) == 1
def test_securities_add_current_tickers_the_seed_lacks():
sub = {"cik": "7", "tickers": ["NEW", "OLD"], "exchanges": ["NYSE"]}
seed = SeedCompany(
"X",
"X",
"0000000007",
"listed",
None,
"",
(),
(SeedSecurity("OLD", "NYSE"),),
(),
(),
Cite(url="u"),
)
secs = edgar.securities_for(sub, seed, ["EXTRA"])
assert [(s.ticker, s.exchange, s.source) for s in secs] == [
("OLD", "NYSE", "seed"),
("NEW", "NYSE", "sec"),
("EXTRA", "", "sec"),
]
assert [s.ticker for s in edgar.securities_for({"cik": "7"}, None, ["T"])] == ["T"]
def test_sic_link_only_for_health_sics():
health = EntityRow("1", "H", "company", "1", "8082")
(link,) = edgar.sic_links(health)
assert (link.scope, link.target, link.basis, link.strength) == (
"sector",
"8082",
"sic",
"sector",
)
assert edgar.sic_links(EntityRow("2", "S", "company", "2", "7372")) == []
assert "8082" in edgar.HEALTH_SICS and len(edgar.HEALTH_SICS) == 19
def test_org_entity():
org = SeedOrg(
"AAFP",
"American Academy of Family Physicians",
"specialty_society",
"FAMILY PRACTICE",
("A", "B"),
("C00411553",),
(),
Cite(url="https://aafp.org/"),
)
e = edgar.org_entity(org)
assert (e.kind, e.key, e.specialty, e.aliases, e.source_url) == (
"organization",
"AAFP",
"FAMILY PRACTICE",
"A|B",
"https://aafp.org/",
)
def test_cite_url():
assert edgar.cite_url(Cite(url="https://a/")) == "https://a/"
assert (
edgar.cite_url(Cite(adsh="0001564406-23-000019"), "0001564406")
== "https://www.sec.gov/Archives/edgar/data/1564406/000156440623000019/0001564406-23-000019-index.htm"
)
assert edgar.cite_url(Cite(adsh="0001-23-1")) == ""
assert edgar.cite_url(Cite(filename="a.pdf")) == ""
def test_curated_links_and_cite_registry(tmp_path):
companies, orgs = load_seed()
store = Store(":memory:", storage_dir=tmp_path / "st")
cite = edgar.cite_registry(store)
rows = edgar.curated_links(companies, orgs, cite)
assert all(r.basis == "curated" and r.item_key for r in rows)
spec = [r for r in rows if r.entity_key == "AAFP"]
assert [(r.scope, r.target, r.cite_kind) for r in spec] == [
("specialty", "FAMILY PRACTICE", "item_key")
]
osh = [r for r in rows if r.entity_key == "0001564406"]
assert {r.cite_kind for r in osh} == {"adsh"}
# one bib item per distinct page, reused
assert len({r.item_key for r in osh}) == 1
again = edgar.cite_registry(store)(Cite(adsh="0001564406-23-000019"), "0001564406")
assert again == osh[0].item_key
assert "market" in " ".join(store.get(osh[0].item_key).tags)
bare = edgar.curated_links(companies[:1], orgs[:1])
assert all(r.item_key == "" for r in bare)
store.close()
def test_curated_links_include_org_links():
c = Cite(url="https://a/", title="A")
org = SeedOrg(
"O",
"O",
"trade_group",
"",
(),
(),
(SeedLink("program", "PFS", c),),
c,
)
(row,) = edgar.curated_links([], [org])
assert (row.entity_key, row.scope, row.target, row.cite_kind) == (
"O",
"program",
"PFS",
"url",
)
def test_cite_registry_item_key_and_filename(tmp_path):
store = Store(":memory:", storage_dir=tmp_path / "st")
cite = edgar.cite_registry(store)
assert cite(Cite(item_key="KRWZGMGI")) == "KRWZGMGI"
assert cite(Cite(filename="a.pdf")) == ""
store.close()
# ── fetching ─────────────────────────────────────────────────────────
@pytest.fixture
def hoard(monkeypatch, tmp_path):
monkeypatch.setattr(http, "hoard_root", lambda: tmp_path / "market")
return tmp_path / "market"
def _client(routes: dict[str, bytes], seen: list[str]):
def handler(request: httpx.Request):
seen.append(str(request.url))
for suffix, body in routes.items():
if str(request.url).endswith(suffix) or suffix in str(request.url):
return httpx.Response(200, content=body)
return httpx.Response(404)
return httpx.Client(transport=httpx.MockTransport(handler))
def test_fetch_tickers_hoards_and_reuses(hoard):
seen: list[str] = []
body = (FX / "company_tickers.json").read_bytes()
cl = _client({"company_tickers.json": body}, seen)
got = edgar.fetch_tickers(cl, pacer=_Pacer())
assert (
len(got) == 3 and (hoard / "sec" / "company_tickers.json").read_bytes() == body
)
edgar.fetch_tickers(cl, pacer=_Pacer())
assert len(seen) == 1 # second read is the cache
edgar.fetch_tickers(cl, pacer=_Pacer(), refresh=True)
assert len(seen) == 2
assert edgar.fetch_tickers(None, pacer=_Pacer(), offline=True) == got
def test_fetch_changed_body_lands_beside_old(hoard):
cl1 = _client({"x.json": b'{"cik": "1"}'}, [])
cl2 = _client({"x.json": b'{"cik": "2"}'}, [])
first = edgar.fetch_submissions(cl1, "x.json", pacer=_Pacer())
second = edgar.fetch_submissions(cl2, "x.json", pacer=_Pacer(), refresh=True)
assert first == {"cik": "1"} and second == {"cik": "2"}
assert (hoard / "sec" / "submissions" / "x.json").read_bytes() == b'{"cik": "1"}'
assert len(list((hoard / "sec" / "submissions").iterdir())) == 2
def test_fetch_nothing_cached_offline_or_no_client(hoard):
assert edgar.fetch_submissions(None, "x.json", pacer=_Pacer(), offline=True) is None
assert edgar.fetch_submissions(None, "x.json", pacer=_Pacer()) is None
assert edgar.fetch_tickers(None, pacer=_Pacer(), offline=True) == {}
def test_fetch_sic_ciks_pages_until_short(hoard, monkeypatch):
monkeypatch.setattr(edgar, "PAGE", 2)
atom = (FX / "sic_8082.atom").read_bytes()
seen: list[str] = []
head, first, _ = atom.split(b"<entry", 2)
short = head + b"<entry" + first.replace(b"0001725255", b"0000000009") + b"</feed>"
cl = _client({"start=0": atom, "start=2": short}, seen)
got = edgar.fetch_sic_ciks(cl, "8082", pacer=_Pacer())
assert got == ["0001725255", "0001468328", "0000000009"]
assert len(seen) == 2 and (hoard / "sec" / "sic" / "8082-00000.atom").exists()
assert edgar.fetch_sic_ciks(None, "8082", pacer=_Pacer(), offline=True) == got
assert edgar.fetch_sic_ciks(None, "9999", pacer=_Pacer(), offline=True) == []
def test_new_pacer_is_polite():
p = edgar.new_pacer()
assert p.min_interval == 0.15 and edgar.PACE_SECONDS * 10 > 1.0
# ── M12: quotes must occur in the hoarded filing ─────────────────────
HTML = (
"<html><body><ix:header>hidden</ix:header><p>We bill the Medicare Physician "
"Fee&nbsp;Schedule&#8217;s rates.</p><script>x()</script>"
"<p>Chronic care\n management &#8212; CCM.</p></body></html>"
)
def test_normalize_text_and_quote_in():
text = edgar.normalize_text(HTML)
assert "hidden" not in text and "x()" not in text
assert "Medicare Physician Fee Schedule's rates." in text
assert edgar.quote_in(text, "Chronic care management - CCM.")
assert edgar.quote_in(text, "medicare physician fee schedule") is False
assert not edgar.quote_in(text, "")
def test_fetch_filing_hoards_records_manifest_and_reuses(hoard):
seen: list[str] = []
cl = _client({"d.htm": HTML.encode()}, seen)
text = edgar.fetch_filing(
cl, "0000000007", "0001-23-000001", "d.htm", pacer=_Pacer()
)
assert "Medicare Physician" in text
assert (hoard / "sec" / "filings" / "0000000007" / "0001-23-000001.htm").exists()
assert "/Archives/edgar/data/7/000123000001/d.htm" in seen[0]
again = edgar.fetch_filing(cl, "0000000007", "0001-23-000001", "", pacer=_Pacer())
assert again == text and len(seen) == 1
lines = [json.loads(x) for x in (hoard / "MANIFEST.jsonl").read_text().splitlines()]
assert len(lines) == 1
assert {"url", "path", "sha256", "bytes", "fetched_at"} <= set(lines[0])
assert lines[0]["path"] == "sec/filings/0000000007/0001-23-000001.htm"
def test_fetch_filing_unavailable(hoard):
assert (
edgar.fetch_filing(
None, "0000000007", "A", "d.htm", pacer=_Pacer(), offline=True
)
is None
)
cl = _client({}, [])
assert edgar.fetch_filing(cl, "0000000007", "A", "", pacer=_Pacer()) is None
assert edgar.fetch_filing(cl, "0000000007", "A", "d.htm", pacer=_Pacer()) is None
def test_quote_errors_lists_unsupported_quotes():
text = edgar.normalize_text(HTML)
ok = Cite(adsh="A", quote="Chronic care management - CCM.")
bad = Cite(adsh="A", quote="nothing like this")
co = SeedCompany(
"X",
"X",
"0000000007",
"listed",
None,
"",
(),
(),
(SeedLink("family", "CCM", bad),),
(),
ok,
)
errs = edgar.quote_errors([co], {("0000000007", "A"): text})
assert len(errs) == 1 and errs[0].startswith("X/family:CCM")
web = SeedCompany(
"W",
"W",
"0000000008",
"listed",
None,
"",
(),
(),
(),
(),
Cite(url="https://a/"),
)
assert edgar.quote_errors([web], {}) == []
gone = edgar.quote_errors([co], {})
assert len(gone) == 2 and all("not hoarded" in e for e in gone)
def test_ama_guard_flags_an_eight_word_run():
run = "one two three four five six seven eight nine"
assert edgar.shares_ama_run("we say " + run + " here", [run])
assert not edgar.shares_ama_run("one two three four five six seven", [run])
def _hoarded(cik, adsh):
p = http.hoard("sec", "filings", cik, f"{adsh}.htm")
return p if p.exists() else None
def test_shipped_quotes_occur_in_the_hoarded_filings():
companies, _ = load_seed()
texts = {}
missing = []
for who, c, cite in edgar.filing_cites(companies):
if not cite.adsh:
continue
p = _hoarded(c.cik, cite.adsh)
if p is None:
missing.append((who, cite.adsh))
continue
texts[(c.cik, cite.adsh)] = edgar.normalize_text(p.read_text(errors="replace"))
if missing and not texts:
pytest.skip("no hoarded filings on this machine")
assert not missing, f"cited filings not hoarded: {missing[:5]}"
assert edgar.quote_errors(companies, texts) == []
def test_shipped_quotes_share_no_run_with_ama_descriptors():
import duckdb
replica = http.hoard_root().parent / "replica" / "aco.ro.duckdb"
if not replica.exists():
pytest.skip("no replica")
con = duckdb.connect(str(replica), read_only=True)
try:
descriptors = [
r[0]
for r in con.execute("SELECT descriptor FROM pfs.cpt_code").fetchall()
if r[0]
]
finally:
con.close()
companies, _ = load_seed()
for who, _c, cite in edgar.filing_cites(companies):
assert not edgar.shares_ama_run(cite.quote, descriptors), (who, cite.quote)
def test_curated_links_carry_the_seed_link_dates():
companies, orgs = load_seed()
rows = edgar.curated_links(companies, orgs)
clov = next(r for r in rows if r.entity_key == "0001801170" and r.target == "APM")
assert clov.valid_to == date(2023, 12, 31) and clov.valid_from is None
assert all(r.valid_to is None for r in rows if r.entity_key == "0001564406")
def test_same_cik_rename_gives_one_security_row_per_ticker():
companies, _ = load_seed()
elv = next(c for c in companies if c.handle == "ELV")
sub = {"cik": elv.cik, "tickers": ["ELV"], "exchanges": ["NYSE"]}
secs = edgar.securities_for(sub, elv, ["ELV"])
assert [(s.ticker, s.valid_from, s.valid_to, s.source, s.priced) for s in secs] == [
("ANTM", None, date(2022, 6, 27), "seed", False),
("ELV", None, None, "seed", True),
]
sec_only = edgar.securities_for({"cik": "7", "tickers": ["NEW"]}, None, [])
assert [s.priced for s in sec_only] == [True]
def test_ama_index_is_built_once_and_matches_like_the_list_form():
run = "one two three four five six seven eight nine"
idx = edgar.AmaIndex.of([run, "short"])
assert edgar.shares_ama_run("x " + run, idx)
assert not edgar.shares_ama_run("one two three", idx)
assert not edgar.shares_ama_run("", idx)