464 lines
14 KiB
Python
464 lines
14 KiB
Python
"""market.tables: DDL, writers, readers, district helpers."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import datetime as dt
|
|
from datetime import date
|
|
|
|
import duckdb
|
|
import pytest
|
|
|
|
from market import tables as T
|
|
from market import tiingo as TI
|
|
|
|
|
|
@pytest.fixture
|
|
def con():
|
|
c = duckdb.connect(":memory:")
|
|
T.ensure_tables(c)
|
|
yield c
|
|
c.close()
|
|
|
|
|
|
def test_ensure_tables_idempotent():
|
|
c = duckdb.connect(":memory:")
|
|
T.ensure_tables(c)
|
|
T.ensure_tables(c)
|
|
names = {
|
|
r[0]
|
|
for r in c.execute(
|
|
"SELECT table_name FROM information_schema.tables "
|
|
"WHERE table_schema = 'market'"
|
|
).fetchall()
|
|
}
|
|
assert names == {
|
|
"entity",
|
|
"security",
|
|
"entity_link",
|
|
"filing",
|
|
"filing_hit",
|
|
"filing_passage",
|
|
"source_gap",
|
|
"price_daily",
|
|
"series",
|
|
"lda_filing",
|
|
"lda_issue",
|
|
}
|
|
|
|
|
|
ENTITY = T.EntityRow(
|
|
"0001564406",
|
|
"Oak Street Health, Inc.",
|
|
"company",
|
|
"0001564406",
|
|
"8000",
|
|
"Services-Health Services",
|
|
"acquired",
|
|
date(2023, 5, 2),
|
|
"0000064803",
|
|
"",
|
|
"",
|
|
"OAK STREET HEALTH",
|
|
"https://x/",
|
|
"ABCD1234",
|
|
)
|
|
SECURITY = T.SecurityRow(
|
|
"0001564406", "OSH", "NYSE", date(2020, 8, 6), date(2023, 5, 2), "seed"
|
|
)
|
|
LINK = T.LinkRow(
|
|
"0001564406", "program", "APM", "curated", "curated", "adsh", "0001-23-1", "", "K"
|
|
)
|
|
FILING = T.FilingRow(
|
|
"0001564406",
|
|
"0001193125-23-132570",
|
|
"8-K",
|
|
date(2023, 5, 2),
|
|
"2023-05-02T20:42:01.000Z",
|
|
None,
|
|
"2.01,3.01",
|
|
"d.htm",
|
|
)
|
|
GAP = T.GapRow("sec-edgar:entities", "403", dt.date.today())
|
|
HIT = T.HitRow(
|
|
"RBRVS",
|
|
"program",
|
|
"PFS",
|
|
"0000790526",
|
|
"0000790526-23-000003",
|
|
"rdnt-20221231.htm",
|
|
"10-K",
|
|
date(2023, 3, 1),
|
|
date(2022, 12, 31),
|
|
"8071",
|
|
"RadNet, Inc. (RDNT)",
|
|
)
|
|
PASSAGE = T.PassageRow(
|
|
"0000790526-23-000003:rdnt-20221231.htm:42",
|
|
"0000790526",
|
|
"0000790526-23-000003",
|
|
"rdnt-20221231.htm",
|
|
"RBRVS",
|
|
42,
|
|
"Our pay follows RBRVS rules.",
|
|
"revenue_exposure",
|
|
"model-reading exposure-v1 m",
|
|
"K",
|
|
)
|
|
|
|
PRICE = TI.PriceRow(
|
|
"OSH",
|
|
date(2021, 1, 4),
|
|
10.0,
|
|
11.0,
|
|
9.5,
|
|
10.5,
|
|
1000.0,
|
|
10.4,
|
|
0.0,
|
|
1.0,
|
|
0.01,
|
|
0.012,
|
|
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]),
|
|
lambda c: T.read_entities(c),
|
|
),
|
|
"security": (
|
|
SECURITY,
|
|
lambda c, r: T.write_securities(c, r.entity_key, [r]),
|
|
lambda c: T.read_securities(c),
|
|
),
|
|
"link": (LINK, lambda c, r: T.write_links(c, [r]), lambda c: T.read_links(c)),
|
|
"filing": (
|
|
FILING,
|
|
lambda c, r: T.write_filings(c, r.cik, [r]),
|
|
lambda c: T.read_filings(c, "0001564406"),
|
|
),
|
|
"price_daily": (
|
|
PRICE,
|
|
lambda c, r: TI.write_prices(c, r.ticker, [r]),
|
|
lambda c: TI.read_prices(c, "OSH"),
|
|
),
|
|
"series": (
|
|
SERIES,
|
|
lambda c, r: TI.write_series(c, r.series_id, [r]),
|
|
lambda c: TI.read_series(c, ["OSH"]),
|
|
),
|
|
"filing_hit": (
|
|
HIT,
|
|
lambda c, r: T.write_hits(c, [r]),
|
|
lambda c: T.read_hits(c),
|
|
),
|
|
"filing_passage": (
|
|
PASSAGE,
|
|
lambda c, r: T.write_passages(c, [r]),
|
|
lambda c: T.read_passages(c),
|
|
),
|
|
"gap": (
|
|
GAP,
|
|
lambda c, r: T.write_gap(c, r.source, r.note),
|
|
lambda c: T.read_gaps(c),
|
|
),
|
|
}
|
|
|
|
|
|
@pytest.mark.parametrize("name", sorted(ROUNDTRIP))
|
|
def test_roundtrip(con, name):
|
|
row, write, read = ROUNDTRIP[name]
|
|
write(con, row)
|
|
write(con, row) # idempotent
|
|
assert read(con) == [row]
|
|
|
|
|
|
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):
|
|
org = T.EntityRow("AAFP", "AAFP", "organization")
|
|
T.write_entities(con, [ENTITY, org])
|
|
T.write_entities(con, [T.EntityRow(ENTITY.key, "Renamed", "company")])
|
|
assert [e.name for e in T.read_entities(con, "company")] == ["Renamed"]
|
|
assert [e.key for e in T.read_entities(con)] == [ENTITY.key, "AAFP"]
|
|
assert [e.key for e in T.read_entities(con, "organization")] == ["AAFP"]
|
|
|
|
|
|
def test_securities_replace_per_entity(con):
|
|
other = T.SecurityRow("2", "ZZ", "", None, None, "sec")
|
|
T.write_securities(con, "2", [other])
|
|
T.write_securities(con, SECURITY.entity_key, [SECURITY])
|
|
T.write_securities(con, SECURITY.entity_key, [SECURITY, SECURITY])
|
|
assert len(T.read_securities(con, SECURITY.entity_key)) == 2
|
|
assert T.read_securities(con, "2") == [other]
|
|
|
|
|
|
def test_write_links_upserts_and_never_wipes_other_basis(con):
|
|
sic = T.LinkRow("1", "sector", "8082", "sic", "sector", "url", "u")
|
|
cur = T.LinkRow("1", "program", "APM", "curated", "curated", "adsh", "a")
|
|
T.write_links(con, [sic])
|
|
T.write_links(con, [cur])
|
|
T.write_links(con, [T.LinkRow("1", "sector", "8082", "sic", "strong", "url", "u")])
|
|
rows = T.read_links(con)
|
|
assert len(rows) == 2
|
|
assert {r.basis: r.strength for r in rows} == {
|
|
"sic": "strong",
|
|
"curated": "curated",
|
|
}
|
|
assert [r.target for r in T.read_links(con, scope="program")] == ["APM"]
|
|
assert [r.target for r in T.read_links(con, target="8082", basis="sic")] == ["8082"]
|
|
|
|
|
|
def test_retire_curated_links(con):
|
|
a = T.LinkRow("1", "program", "APM", "curated", "curated", "adsh", "a")
|
|
b = T.LinkRow("1", "program", "PFS", "curated", "curated", "adsh", "a")
|
|
sic = T.LinkRow("1", "sector", "8082", "sic", "sector", "url", "u")
|
|
T.write_links(con, [a, b, sic])
|
|
n = T.retire_links(con, "curated", ["1"], {("1", "program", "APM")})
|
|
assert n == 1
|
|
assert {(r.basis, r.target) for r in T.read_links(con)} == {
|
|
("curated", "APM"),
|
|
("sic", "8082"),
|
|
}
|
|
|
|
|
|
def test_filings_upsert_and_form_filter(con):
|
|
k = T.FilingRow("1", "A-1", "10-K", date(2023, 1, 1), "", None, "", "")
|
|
q = T.FilingRow(
|
|
"1", "A-2", "10-Q", date(2023, 2, 1), "", date(2022, 12, 31), "", ""
|
|
)
|
|
T.write_filings(con, "1", [k, q])
|
|
T.write_filings(con, "1", [q])
|
|
assert [f.adsh for f in T.read_filings(con, "1")] == ["A-1", "A-2"]
|
|
assert [f.adsh for f in T.read_filings(con, "1", ["10-K"])] == ["A-1"]
|
|
|
|
|
|
def test_gap_replaced_and_cleared(con):
|
|
T.write_gap(con, "s", "one")
|
|
T.write_gap(con, "s", "two")
|
|
assert [g.note for g in T.read_gaps(con)] == ["two"]
|
|
T.clear_gap(con, "s")
|
|
assert T.read_gaps(con) == []
|
|
|
|
|
|
def test_district_id():
|
|
assert T.district_id("MI", 12) == "MI-12"
|
|
assert T.district_id("ak", 0) == "AK-00"
|
|
assert T.district_id("AK", None) == "AK-00"
|
|
assert T.district_id("AK", "At Large") == "AK-00"
|
|
assert T.district_id("AK", "00") == "AK-00"
|
|
assert T.district_id("CA", "7") == "CA-07"
|
|
|
|
|
|
def test_state_codes():
|
|
c = duckdb.connect(":memory:")
|
|
c.execute("CREATE SCHEMA reference_data")
|
|
c.execute(
|
|
"CREATE TABLE reference_data.ansi_fips_state (ansi_fips_state_code VARCHAR, "
|
|
"ansi_fips_state_abbreviation VARCHAR, ansi_fips_state_name VARCHAR)"
|
|
)
|
|
c.execute(
|
|
"INSERT INTO reference_data.ansi_fips_state VALUES ('26','MI','Michigan')"
|
|
)
|
|
codes = T.state_codes(c)
|
|
assert codes["26"] == codes["MI"] == codes["Michigan"] == ("26", "MI", "Michigan")
|
|
c.close()
|
|
|
|
|
|
def test_entity_pseudo_flag_roundtrips(con):
|
|
pseudo = T.EntityRow("P", "P", "organization", pseudo=True)
|
|
T.write_entities(con, [pseudo, T.EntityRow("Q", "Q", "organization")])
|
|
assert {e.key: e.pseudo for e in T.read_entities(con)} == {"P": True, "Q": False}
|
|
|
|
|
|
def test_ensure_tables_adds_pseudo_to_an_existing_entity_table():
|
|
c = duckdb.connect(":memory:")
|
|
c.execute("CREATE SCHEMA market")
|
|
c.execute(
|
|
"CREATE TABLE market.entity (key VARCHAR, name VARCHAR, kind VARCHAR, cik VARCHAR, "
|
|
"sic VARCHAR, sic_desc VARCHAR, status VARCHAR, ended_on DATE, successor VARCHAR, "
|
|
"specialty VARCHAR, org_type VARCHAR, aliases VARCHAR, source_url VARCHAR, item_key VARCHAR)"
|
|
)
|
|
T.ensure_tables(c)
|
|
T.write_entities(c, [T.EntityRow("P", "P", "organization", pseudo=True)])
|
|
assert T.read_entities(c)[0].pseudo is True
|
|
c.close()
|
|
|
|
|
|
def test_write_links_batches_its_deletes(con):
|
|
rows = [
|
|
T.LinkRow("1", "sector", str(i), "sic", "sector", "url", "u")
|
|
for i in range(1200)
|
|
]
|
|
T.write_links(con, rows)
|
|
seen = []
|
|
|
|
class Spy:
|
|
def __init__(self, c):
|
|
self.c = c
|
|
|
|
def execute(self, sql, *a):
|
|
seen.append(sql.split()[0])
|
|
return self.c.execute(sql, *a)
|
|
|
|
T.write_links(Spy(con), rows)
|
|
assert seen.count("DELETE") <= 4 and len(T.read_links(con)) == 1200
|
|
|
|
|
|
def test_retire_organizations_removes_entities_and_links(con):
|
|
T.write_entities(
|
|
con,
|
|
[
|
|
T.EntityRow("A", "A", "organization"),
|
|
T.EntityRow("B", "B", "organization"),
|
|
ENTITY,
|
|
],
|
|
)
|
|
T.write_links(
|
|
con,
|
|
[
|
|
T.LinkRow("A", "specialty", "X", "curated", "curated", "item_key", "K"),
|
|
T.LinkRow("B", "specialty", "Y", "curated", "curated", "item_key", "K"),
|
|
],
|
|
)
|
|
assert T.retire_organizations(con, ["A"]) == 1
|
|
assert [e.key for e in T.read_entities(con)] == [ENTITY.key, "A"]
|
|
assert [l.entity_key for l in T.read_links(con)] == ["A"]
|
|
|
|
|
|
def test_link_dates_roundtrip(con):
|
|
row = T.LinkRow(
|
|
"1",
|
|
"program",
|
|
"APM",
|
|
"curated",
|
|
"curated",
|
|
"adsh",
|
|
"a",
|
|
valid_from=date(2021, 1, 1),
|
|
valid_to=date(2023, 12, 31),
|
|
)
|
|
T.write_links(con, [row])
|
|
assert T.read_links(con) == [row]
|
|
|
|
|
|
def test_ensure_tables_adds_dates_to_an_existing_link_table():
|
|
c = duckdb.connect(":memory:")
|
|
c.execute("CREATE SCHEMA market")
|
|
c.execute(
|
|
"CREATE TABLE market.entity_link (entity_key VARCHAR, scope VARCHAR, target VARCHAR, "
|
|
"basis VARCHAR, strength VARCHAR, cite_kind VARCHAR, cite_ref VARCHAR, "
|
|
"passage_id VARCHAR, item_key VARCHAR)"
|
|
)
|
|
c.execute(
|
|
"INSERT INTO market.entity_link VALUES ('1','program','APM','curated','c','adsh','a','','')"
|
|
)
|
|
T.ensure_tables(c)
|
|
(old,) = T.read_links(c)
|
|
assert old.valid_from is None and old.valid_to is None
|
|
c.close()
|
|
|
|
|
|
def test_security_priced_flag_roundtrips_and_old_rows_read_as_priced(con):
|
|
sym = T.SecurityRow("1", "ANTM", "NYSE", None, date(2022, 6, 27), "seed", False)
|
|
T.write_securities(
|
|
con, "1", [sym, T.SecurityRow("1", "ELV", "NYSE", None, None, "seed")]
|
|
)
|
|
assert [(s.ticker, s.priced) for s in T.read_securities(con, "1")] == [
|
|
("ANTM", False),
|
|
("ELV", True),
|
|
]
|
|
|
|
|
|
def test_ensure_tables_adds_priced_to_an_existing_security_table():
|
|
c = duckdb.connect(":memory:")
|
|
c.execute("CREATE SCHEMA market")
|
|
c.execute(
|
|
"CREATE TABLE market.security (entity_key VARCHAR, ticker VARCHAR, exchange VARCHAR, "
|
|
"valid_from DATE, valid_to DATE, source VARCHAR)"
|
|
)
|
|
c.execute("INSERT INTO market.security VALUES ('1','OLD','NYSE',NULL,NULL,'sec')")
|
|
T.ensure_tables(c)
|
|
(old,) = T.read_securities(c)
|
|
assert old.priced is True
|
|
c.close()
|
|
|
|
|
|
def test_hits_and_passages_upsert_by_their_keys(con):
|
|
T.write_hits(con, [HIT, dataclasses_replace(HIT, term="x")])
|
|
T.write_hits(con, [dataclasses_replace(HIT, sics="8082")])
|
|
assert sorted((h.term, h.sics) for h in T.read_hits(con)) == [
|
|
("RBRVS", "8082"),
|
|
("x", "8071"),
|
|
]
|
|
sibling = dataclasses_replace(PASSAGE, term="x", label="")
|
|
T.write_passages(con, [PASSAGE, sibling])
|
|
T.write_passages(con, [dataclasses_replace(PASSAGE, passage="new text", label="")])
|
|
got = {p.term: p.passage for p in T.read_passages(con)}
|
|
assert got == {"RBRVS": "new text", "x": PASSAGE.passage}
|
|
assert T.write_hits(con, []) == 0 and T.write_passages(con, []) == 0
|
|
|
|
|
|
def dataclasses_replace(row, **kw):
|
|
import dataclasses
|
|
|
|
return dataclasses.replace(row, **kw)
|