"""The committed clean files (clean/*.parquet) must match their contracts and what
config/ and common.study say should be in them. A file that is out of date, such as
a retailer added to config/retailers.csv without re-running the ETL, fails here with
the script to re-run."""
from __future__ import annotations
from datetime import timedelta
import pandas as pd
import pytest
from common.contracts import (
check_columns,
expand_events,
load_retail_series,
parquet_columns,
price_tickers,
)
from common.settings import clean_path
from common.study import MARKET_TICKER, STUDY_END, STUDY_END_YEAR, STUDY_START, STUDY_START_YEAR
# Markets close for at most a few days in a row, so real data reaches this close to
# both ends of the study period; data from an older, shorter period does not.
EDGE = timedelta(days=7)
REDOWNLOAD = "common.study's period changed? Delete raw/prices/ and raw/wiki/ and re-run the ETL"
def read(dataset: str) -> pd.DataFrame:
return pd.read_parquet(clean_path(dataset))
@pytest.mark.parametrize("dataset", ["prices", "pageviews", "retail_sales", "master"])
def test_clean_file_matches_its_contract(dataset):
problems = check_columns(dataset, parquet_columns(clean_path(dataset)))
assert not problems, f"clean/{dataset}.parquet: {problems}"
def test_prices_cover_the_in_scope_retailers_and_the_market_index():
prices = read("prices")
assert set(prices["ticker"]) == set(price_tickers()), (
"config/retailers.csv changed: re-run etl/prices_download.py, etl/prices_clean.py, etl/join_master.py"
)
assert not prices.duplicated(["ticker", "date"]).any()
assert STUDY_START <= prices["date"].min() and prices["date"].max() <= STUDY_END
assert prices["date"].min() <= STUDY_START + EDGE and prices["date"].max() >= STUDY_END - EDGE, REDOWNLOAD
def test_pageviews_cover_every_in_scope_retailer_on_every_day():
views = read("pageviews")
retailers = set(price_tickers()) - {MARKET_TICKER}
assert set(views["ticker"]) == retailers, (
"config/retailers.csv or config/wiki_articles.csv changed: re-run etl/pageviews_download.py, "
"etl/pageviews_clean.py, etl/join_master.py"
)
days = (STUDY_END - STUDY_START).days + 1
per_ticker = views.groupby("ticker")["date"].agg(["nunique", "min", "max"])
assert (per_ticker["nunique"] == days).all()
assert (per_ticker["min"] == STUDY_START).all() and (per_ticker["max"] == STUDY_END).all()
# pageviews_clean.py fills days with no data with 0, so a stale download shows up as
# empty edges of the period rather than as missing rows.
first = views[views["date"] < STUDY_START + EDGE]["views"].sum()
last = views[views["date"] > STUDY_END - EDGE]["views"].sum()
assert first > 0 and last > 0, REDOWNLOAD
def test_retail_sales_cover_every_series_in_every_month():
sales = read("retail_sales")
assert set(sales["category"]) == {s["category"] for s in load_retail_series()}, (
"config/retail_series.csv changed: download the series and re-run etl/retail_clean.py"
)
months = (STUDY_END.year - STUDY_START.year) * 12 + STUDY_END.month - STUDY_START.month + 1
assert (sales.groupby("category")["month"].nunique() == months).all()
def test_master_has_one_row_per_price_row():
prices, master = read("prices"), read("master")
keys = ["ticker", "date"]
assert master[keys].sort_values(keys).reset_index(drop=True).equals(
prices[keys].sort_values(keys).reset_index(drop=True)
), "re-run etl/join_master.py"
def test_master_labels_exactly_the_calendar_events_on_trading_days():
master = read("master")
trading_days = set(master["date"])
expected = {(d.date(), e["event_type"])
for e in expand_events(STUDY_START_YEAR, STUDY_END_YEAR)
for d in pd.date_range(e["event_date"], e["event_end_date"])
if d.date() in trading_days}
labelled = master.dropna(subset=["event_type"])
actual = set(zip(labelled["date"], labelled["event_type"]))
assert actual == expected, (
"config/event_types.csv or config/event_dates.csv changed: re-run etl/join_master.py "
f"(missing {sorted(expected - actual)[:3]}, unexpected {sorted(actual - expected)[:3]})"
)