Datasets:
File size: 8,476 Bytes
06a67ad 540c454 06a67ad 540c454 06a67ad 540c454 06a67ad 540c454 06a67ad 540c454 06a67ad 540c454 06a67ad 540c454 06a67ad | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 | """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 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
|