57 lines
2.3 KiB
Python
57 lines
2.3 KiB
Python
from datetime import UTC, date, datetime
|
|
import dlt
|
|
import pandas as pd
|
|
from sqlalchemy import inspect, text
|
|
from persistance.destination import engine, platform
|
|
|
|
TIMELINE = [
|
|
"person_id",
|
|
"index_date",
|
|
"date",
|
|
"type",
|
|
"value_code",
|
|
"value_num",
|
|
"source_table",
|
|
"source_id",
|
|
"record_number",
|
|
]
|
|
|
|
|
|
def timelines(events: str, cohort: str, as_of: date | None = None) -> pd.DataFrame:
|
|
sql = text(
|
|
f"\n select e.person_id, c.index_date, e.date, e.type, e.value_code, e.value_num,\n e.source_table, e.source_id, n.record_number\n from gold.{events} as e\n join gold.{cohort} as c on c.person_id = e.person_id\n left join (select person_id, min(record_number) as record_number\n from bronze.staged__identity group by person_id) as n\n on n.person_id = e.person_id\n where c.excluded_by is null and e.date <= :as_of\n order by e.person_id, e.date, e.source_table, e.source_id\n "
|
|
)
|
|
with engine().connect() as con:
|
|
found = pd.read_sql(sql, con, params={"as_of": (as_of or date.today()).isoformat()})
|
|
return found.astype({"value_num": float})[TIMELINE]
|
|
|
|
|
|
def person_numbers() -> dict[str, str]:
|
|
sql = text(
|
|
"select distinct person_id, record_number from bronze.staged__identity where person_id is not null and record_number is not null"
|
|
)
|
|
with engine().connect() as con:
|
|
return dict(con.execute(sql).fetchall())
|
|
|
|
|
|
SCORES = "model_scores"
|
|
|
|
|
|
def save_scores(model: str, version: int, scores: pd.DataFrame) -> None:
|
|
with engine().begin() as con:
|
|
if inspect(con).has_table(SCORES, schema="bronze"):
|
|
con.execute(text(f"delete from bronze.{SCORES} where model = :m"), {"m": model})
|
|
rows = scores.assign(model=model, version=version, scored_at=datetime.now(UTC))
|
|
resource = dlt.resource(
|
|
rows.to_dict("records"),
|
|
name=SCORES,
|
|
write_disposition="append",
|
|
columns={
|
|
"ci_low": {"data_type": "double", "nullable": True},
|
|
"ci_high": {"data_type": "double", "nullable": True},
|
|
"scenarios": {"data_type": "text", "nullable": True},
|
|
"index_date": {"data_type": "date"},
|
|
},
|
|
)
|
|
dlt.pipeline(SCORES, destination=platform(), dataset_name="bronze").run(resource)
|