industry-classification / tests /test_sources.py
ZipLime's picture
Update the industry classification
540c454 verified
Raw History Blame Contribute Delete
8.48 kB
"""Parsing the two scraped sources: a web page and a 2008 spreadsheet."""
from __future__ import annotations
import polars as pl
from recipe.sic import DIVISIONS
from recipe.sources import parse_concordance_frame
class _FakePage:
def __init__(self, text: str) -> None:
self._text = text
async def get_text(self, *_args, **_kwargs) -> str:
return self._text
SIC_PAGE = """
<table>
<tr><th>SIC Code</th><th>Office</th><th>Industry Title</th></tr>
<tr><td>100</td><td>Industrial Applications and Services</td>
<td>AGRICULTURAL PRODUCTION-CROPS</td></tr>
<tr><td>2834</td><td>Office of Life Sciences</td><td>PHARMACEUTICAL&nbsp;PREPARATIONS</td></tr>
<tr><td>6770</td><td>Multiple Offices</td><td>BLANK CHECKS</td></tr>
</table>
"""
def test_sic_list_parses_three_column_rows():
from recipe.sources import parse_sic_list
frame = parse_sic_list(SIC_PAGE)
assert frame["sic"].to_list() == ["0100", "2834", "6770"]
assert frame.filter(pl.col("sic") == "2834")["title"].item() == "PHARMACEUTICAL PREPARATIONS"
assert frame.filter(pl.col("sic") == "6770")["sec_office"].item() == "Multiple Offices"
async def test_sic_list_refuses_a_page_that_lost_its_table():
"""A layout change must fail the build, not silently drop 200 titles."""
from recipe.sources import edgar_sic_list
try:
await edgar_sic_list(_FakePage(SIC_PAGE))
except RuntimeError as error:
assert "444" in str(error)
else: # pragma: no cover - the guard is the point of the test
raise AssertionError("a three-row page should not have been accepted")
# The sheet as the reader hands it over: every cell a string, columns already
# named. Built directly rather than round-tripped through a spreadsheet, so
# the tests need no Excel writer -- the first version did, and passed here
# while failing in the job, where `xlsxwriter` is not installed.
CONCORDANCE = pl.DataFrame(
{
"sic": [None, "28", "2834", "2836", "2836", None, "99", "9999"],
"part": [None, None, None, "pt", "pt", None, None, None],
"title": [
"Manufacturing", "Chemicals and allied products", "Pharmaceutical Preparations",
". Vaccines", ". Other", "Nonclassifiable establishments",
"Nonclassifiable", "Nonclassifiable Establishments",
],
"naics": [None, None, "325412", "325414", "325411", None, None, "99999"],
"naics_title": [
None, None, "Pharmaceutical Preparation Manufacturing",
"Biological Product Manufacturing", "Medicinal and Botanical Manufacturing",
None, None, "Unclassified Establishments",
],
}
)
def test_concordance_separates_hierarchy_from_crosswalk():
crosswalk, major_groups, divisions = parse_concordance_frame(CONCORDANCE)
assert divisions == ["Manufacturing", "Nonclassifiable establishments"]
assert major_groups["28"] == "Chemicals and allied products"
# Supplied here because the Census file never prints a header row for them.
assert major_groups["40"] == "Railroad Transportation"
assert set(crosswalk["sic"]) == {"2834", "2836", "9999"}
def test_a_split_industry_keeps_every_candidate():
crosswalk, _, _ = parse_concordance_frame(CONCORDANCE)
split = crosswalk.filter(pl.col("sic") == "2836")
assert split.height == 2
assert split["is_part"].to_list() == [True, True]
assert split["part_description"].to_list() == ["Vaccines", "Other"]
assert set(split["naics_sector"]) == {"32"}
def test_division_ranges_are_ordered_and_do_not_overlap():
"""The letters are asserted in code rather than read from a source, so
the structure they claim has to hold on its own terms."""
previous_high = 0
for letter, low, high, title in DIVISIONS:
assert low <= high, letter
assert low > previous_high, f"division {letter} overlaps the one before it"
assert title.strip() == title and title
previous_high = high
def test_concordance_divisions_are_distinct():
_, _, divisions = parse_concordance_frame(CONCORDANCE)
assert len(set(divisions)) == len(divisions)
assert divisions[0] == "Manufacturing"
def test_a_truncated_archive_is_not_accepted(tmp_path):
"""Half the bug this guards: a partial download that fails as a
`BadZipFile` thousands of lines later instead of at the download."""
import zipfile
from recipe.sources import _is_readable_zip
good = tmp_path / "good.zip"
with zipfile.ZipFile(good, "w") as bundle:
bundle.writestr("CIK0000000001.json", '{"sic": "2834"}')
assert _is_readable_zip(good)
payload = good.read_bytes()
truncated = tmp_path / "truncated.zip"
truncated.write_bytes(payload[: len(payload) // 2])
assert not _is_readable_zip(truncated)
assert not _is_readable_zip(tmp_path / "absent.zip")
def test_an_overlong_archive_still_opens_which_is_why_the_size_is_checked(tmp_path):
"""The other half, and the reason there are two checks rather than one.
The real failure was a `.part` file another process was still writing:
the downloader appended to it and ended up 10 MB past the declared length.
A zip with bytes after its directory still opens -- the reader scans
backwards for the end record -- so only comparing the byte count against
what the server declared catches this.
"""
import zipfile
from recipe.sources import _is_readable_zip
good = tmp_path / "good.zip"
with zipfile.ZipFile(good, "w") as bundle:
bundle.writestr("CIK0000000001.json", '{"sic": "2834"}')
overlong = tmp_path / "overlong.zip"
overlong.write_bytes(good.read_bytes() + b"\x00" * 4096)
assert _is_readable_zip(overlong)
assert overlong.stat().st_size != good.stat().st_size
def test_read_bulk_sic_takes_only_the_metadata_member(tmp_path):
import zipfile
from recipe.sources import read_bulk_sic
archive = tmp_path / "submissions.zip"
with zipfile.ZipFile(archive, "w") as bundle:
bundle.writestr("CIK0000000001.json", '{"sic": "2834", "name": "Pill Co"}')
# The paginated history files beside it hold filings, not metadata.
bundle.writestr("CIK0000000001-submissions-001.json", '{"filings": []}')
bundle.writestr("CIK0000000002.json", '{"sic": "", "name": "No Code Co"}')
bundle.writestr("CIK0000000003.json", "not json at all")
rows, kinds = read_bulk_sic(
archive, ["0000000001", "0000000002", "0000000003", "0000000009"]
)
assert [row["sic"] for row in rows] == ["2834"]
assert rows[0]["is_dated"] is False
assert rows[0]["source"] == "submissions"
assert kinds == []
def test_a_filer_with_no_code_is_identified_by_what_it_files(tmp_path):
"""Sixteen hundred live symbols belong to filers the SEC never assigned an
industry. N-CSR and F-6 say what they are, by definition of the forms."""
import json
import zipfile
from recipe.sources import read_bulk_sic
def record(name, forms, entity="other"):
return json.dumps(
{"sic": "", "name": name, "entityType": entity,
"filings": {"recent": {"form": forms}}}
)
archive = tmp_path / "submissions.zip"
with zipfile.ZipFile(archive, "w") as bundle:
bundle.writestr("CIK0000000001.json", record("A Closed-End Fund", ["N-CSR", "4"]))
bundle.writestr("CIK0000000002.json", record("Foreign Co ADR", ["F-6EF", "SC 13D"]))
bundle.writestr("CIK0000000003.json", record("Dormant Shell", ["4"]))
bundle.writestr("CIK0000000004.json", record("A Fund", [], entity="investment"))
# A fund that also sponsors a receipt programme is still a fund.
bundle.writestr("CIK0000000005.json", record("Both", ["N-2", "F-6"]))
_, kinds = read_bulk_sic(archive, [f"000000000{n}" for n in range(1, 6)])
assert {row["cik"]: row["entity_kind"] for row in kinds} == {
"0000000001": "investment_company",
"0000000002": "depositary_receipt",
"0000000004": "investment_company",
"0000000005": "investment_company",
}
def test_entity_kinds_resolve_to_a_fund_and_a_receipt():
from recipe.taxonomy import classify_entity
assert classify_entity("investment_company").sector_code == "FUND"
assert classify_entity("depositary_receipt").industry_code == "UNCL_ADR"
assert classify_entity(None) is None
assert classify_entity("something else") is None