> ## Documentation Index
> Fetch the complete documentation index at: https://calendar-effects.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# tests/test_compare.py

> Tests for streaming.compare, the streaming vs batch comparison (task #9).

`tests/test_compare.py` · chapter [Tests and team tooling](https://calendar-effects.mintlify.site/tour/10-tests-and-tooling.md), file 9 · 112 lines · [open in the repository](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_compare.py)

## What it does

Tests for streaming.compare, the streaming vs batch comparison (task #9).

## What is inside

* **`TRADING_DAYS`** · [line 11](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_compare.py#L11): made-up calendar, weekdays only
* **`windows(n, day0, tickers)`** · [line 14](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_compare.py#L14): n made-up event windows that follow the stream\_event\_car contract.
* **`day_plus_5(day0)`** · [line 30](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_compare.py#L30)

## What it checks

* the two contracts have the same columns (line 34)
* identical tables match (line 39)
* rounding error is not a difference (line 46)
* a real difference fails and is counted (line 52)
* missing on both sides counts as equal (line 63)
* a window still open in the stream is not a failure (line 67)
* a truncated stream fails (line 79)
* an empty stream fails (line 86)
* without a stream end nothing counts as open (line 93)
* a window only in the stream fails (line 97)
* repeated keys fail (line 102)
* a flipped significance call is reported (line 108)

## Connections

**Uses:** [`src/common/contracts.py`](https://calendar-effects.mintlify.site/reference/src/common/contracts), [`src/common/study.py`](https://calendar-effects.mintlify.site/reference/src/common/study), [`src/streaming/compare.py`](https://calendar-effects.mintlify.site/reference/src/streaming/compare)

## Source

```python title="tests/test_compare.py" lines expandable theme={null}
"""Tests for streaming.compare, the streaming vs batch comparison (task #9)."""
from datetime import date

import numpy as np
import pandas as pd

from common.contracts import CONTRACTS
from common.study import ABNORMAL_RETURN_Z, EVENT_WINDOW
from streaming.compare import TOLERANCE, compare

TRADING_DAYS = pd.bdate_range("2024-11-01", "2025-01-31")   # made-up calendar, weekdays only


def windows(n=3, day0=date(2024, 11, 29), tickers=None):
    """n made-up event windows that follow the stream_event_car contract."""
    rows = []
    for i, ticker in enumerate(tickers or [f"T{i}" for i in range(n)]):
        rows.append({
            "ticker": ticker, "event_type": "black_friday", "event_date": day0,
            "event_end_date": day0, "day0_date": day0,
            "alpha": 0.001 * i, "beta": 1.0 + i, "ar_sd": 0.01, "estimation_days": 120,
            "car": 0.02 * (i - 1), "car_z": (i - 1) * ABNORMAL_RETURN_Z, "n_days": 11,
            "n_abnormal_days": i, "max_z_views": float("nan") if i == 0 else 2.5, "n_spike_days": 0,
        })
    df = pd.DataFrame(rows)
    assert list(df.columns) == list(CONTRACTS["stream_event_car"])
    return df


def day_plus_5(day0):
    return TRADING_DAYS[TRADING_DAYS.searchsorted(pd.Timestamp(day0)) + EVENT_WINDOW[1]]


def test_the_two_contracts_have_the_same_columns():
    # Decision 0006: the comparison relies on this, and compares the stream's columns.
    assert CONTRACTS["batch_event_car"] == CONTRACTS["stream_event_car"]


def test_identical_tables_match():
    r = compare(windows(), windows())
    assert r["ok"] and r["n_both"] == 3
    assert all(c["n_mismatch"] == 0 for c in r["columns"].values())
    assert r["n_same_call"] == r["n_called"] == 3


def test_rounding_error_is_not_a_difference():
    batch = windows()
    batch["car"] += TOLERANCE / 10
    assert compare(windows(), batch)["ok"]


def test_a_real_difference_fails_and_is_counted():
    batch = windows()
    batch.loc[1, "car"] += 1e-6
    batch.loc[2, "n_abnormal_days"] += 1
    r = compare(windows(), batch)
    assert not r["ok"]
    assert r["columns"]["car"]["n_mismatch"] == 1
    assert np.isclose(r["columns"]["car"]["max_diff"], 1e-6)
    assert r["columns"]["n_abnormal_days"]["n_mismatch"] == 1


def test_missing_on_both_sides_counts_as_equal():
    assert compare(windows(), windows())["columns"]["max_z_views"]["n_mismatch"] == 0


def test_a_window_still_open_in_the_stream_is_not_a_failure():
    late = windows(1, day0=date(2025, 1, 20), tickers=["LATE"])
    batch = pd.concat([windows(), late])
    # The stream stopped before LATE's day +5: still open.
    day_before = TRADING_DAYS[TRADING_DAYS.get_loc(day_plus_5(date(2025, 1, 20))) - 1]
    r = compare(windows(), batch, stream_end=day_before, trading_days=TRADING_DAYS)
    assert r["ok"] and len(r["still_open"]) == 1 and r["missing_from_stream"].empty
    # The stream processed LATE's day +5, so it should have written the window.
    r = compare(windows(), batch, stream_end=day_plus_5(date(2025, 1, 20)), trading_days=TRADING_DAYS)
    assert not r["ok"] and len(r["missing_from_stream"]) == 1


def test_a_truncated_stream_fails():
    # Day 0 later than the stream's last window used to count as open; day +5 is what counts.
    batch = pd.concat([windows(), windows(1, day0=date(2024, 12, 9), tickers=["DEC"])])
    r = compare(windows(), batch, stream_end=pd.Timestamp("2025-01-31"), trading_days=TRADING_DAYS)
    assert not r["ok"] and len(r["missing_from_stream"]) == 1


def test_an_empty_stream_fails():
    r = compare(windows().iloc[0:0], windows(), stream_end=pd.Timestamp("2025-01-31"),
                trading_days=TRADING_DAYS)
    assert not r["ok"] and r["n_both"] == 0
    assert not compare(windows().iloc[0:0], windows())["ok"]


def test_without_a_stream_end_nothing_counts_as_open():
    assert not compare(windows(2), windows(3))["ok"]


def test_a_window_only_in_the_stream_fails():
    r = compare(windows(3), windows(2))
    assert not r["ok"] and len(r["only_stream"]) == 1


def test_repeated_keys_fail():
    stream = pd.concat([windows(), windows().iloc[[1]]])
    r = compare(stream, windows())
    assert not r["ok"] and r["duplicates"] == {"stream": 1, "batch": 0}


def test_a_flipped_significance_call_is_reported():
    batch = windows()
    batch.loc[2, "car_z"] = 0.0                   # was 1.96: significant in the stream only
    r = compare(windows(), batch)
    assert r["n_same_call"] == r["n_called"] - 1
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.