> ## 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.

# src/streaming/compare.py

> Compare the streaming job's event CARs with the batch event study's answer key (task #9).

`src/streaming/compare.py` · chapter [Comparing the answers](https://calendar-effects.mintlify.site/tour/07-comparing.md), file 1 · 133 lines · [open in the repository](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/compare.py)

## What it does

Compare the streaming job's event CARs with the batch event study's answer key (task #9).

stream\_event\_car and batch\_event\_car have the same columns (decision 0006) and both
sides use the settings in common.study (decision 0004), so every value should agree
to rounding error. The two are written independently (day-by-day state in
streaming.signals, whole arrays in eventstudy.car), so agreement checks both.

The stream writes a window only once its day +5 has been processed and the watermark
has passed it, so a replay's last windows can still be open when it stops. A window
missing from the stream counts as still open only if its day +5 is after the last
trading day the stream processed (stream\_end); any other missing window is a failure.

Significance here is the per-window call |car\_z| >= ABNORMAL\_RETURN\_Z, the same
threshold as the daily alerts. It is a check that both sides flag the same windows,
not the report's test (stats.py's clustered test at common.study.CONFIDENCE).

Usage:

```text theme={null}
from streaming.compare import compare
result = compare(stream_df, batch_df, stream_end=last_day, trading_days=days)
result["ok"]
```

## What is inside

* **`KEYS`** · [line 30](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/compare.py#L30)
* **`TOLERANCE`** · [line 33](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/compare.py#L33): Largest difference between two doubles that still counts as rounding error. The two sides add the same numbers in a different order, which leaves about 1e-16.
* **`_normalise(df, types)`** · [line 36](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/compare.py#L36): The contract's columns only, with one dtype per contract type, so the sides compare.
* **`_window_ends(day0, trading_days)`** · [line 49](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/compare.py#L49): Day +5 of each window; NaT when it falls after the last trading day given.
* **`compare(stream, batch, stream_end, trading_days, tolerance)`** · [line 56](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/compare.py#L56): Join the two on KEYS and compare every other contract column.

## 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)

**Used by:** [`scripts/compare_stream_batch.py`](https://calendar-effects.mintlify.site/reference/scripts/compare_stream_batch), [`tests/test_compare.py`](https://calendar-effects.mintlify.site/reference/tests/test_compare)

## Source

```python title="src/streaming/compare.py" lines expandable theme={null}
"""Compare the streaming job's event CARs with the batch event study's answer key (task #9).

stream_event_car and batch_event_car have the same columns (decision 0006) and both
sides use the settings in common.study (decision 0004), so every value should agree
to rounding error. The two are written independently (day-by-day state in
streaming.signals, whole arrays in eventstudy.car), so agreement checks both.

The stream writes a window only once its day +5 has been processed and the watermark
has passed it, so a replay's last windows can still be open when it stops. A window
missing from the stream counts as still open only if its day +5 is after the last
trading day the stream processed (stream_end); any other missing window is a failure.

Significance here is the per-window call |car_z| >= ABNORMAL_RETURN_Z, the same
threshold as the daily alerts. It is a check that both sides flag the same windows,
not the report's test (stats.py's clustered test at common.study.CONFIDENCE).

Usage:
    from streaming.compare import compare
    result = compare(stream_df, batch_df, stream_end=last_day, trading_days=days)
    result["ok"]
"""
from __future__ import annotations

import numpy as np
import pandas as pd

from common.contracts import CONTRACTS
from common.study import ABNORMAL_RETURN_Z, EVENT_WINDOW

KEYS = ["ticker", "event_type", "event_date"]
# Largest difference between two doubles that still counts as rounding error.
# The two sides add the same numbers in a different order, which leaves about 1e-16.
TOLERANCE = 1e-9


def _normalise(df: pd.DataFrame, types: dict[str, str]) -> pd.DataFrame:
    """The contract's columns only, with one dtype per contract type, so the sides compare."""
    out = df[list(types)].copy()
    for col, kind in types.items():
        if kind == "date":
            out[col] = pd.to_datetime(out[col])
        elif kind == "int":
            out[col] = out[col].astype("Int64")
        elif kind == "double":
            out[col] = out[col].astype("float64")
    return out


def _window_ends(day0: pd.Series, trading_days: pd.DatetimeIndex) -> pd.Series:
    """Day +5 of each window; NaT when it falls after the last trading day given."""
    pos = trading_days.searchsorted(day0.to_numpy()) + EVENT_WINDOW[1]
    ends = [trading_days[p] if p < len(trading_days) else pd.NaT for p in pos]
    return pd.Series(ends, index=day0.index, dtype="datetime64[ns]")


def compare(stream: pd.DataFrame, batch: pd.DataFrame, stream_end=None, trading_days=None,
            tolerance: float = TOLERANCE) -> dict:
    """Join the two on KEYS and compare every other contract column.

    stream_end    last trading day the stream processed (the latest date in its daily
                  output); with trading_days (every trading day, e.g. master's dates) it
                  decides which missing windows are still open. Without them, none are.

    Returns a dict with:
      n_stream, n_batch, n_both    window counts
      duplicates    {"stream": n, "batch": n} rows whose keys appear more than once
      only_stream, only_batch      keys found on one side only (DataFrames). only_batch splits
                                   into still_open (day +5 after stream_end) and
                                   missing_from_stream (the stream should have it)
      columns     {column: {"n_mismatch": int, "max_diff": float or None (non-doubles)}}
      n_called, n_same_call   windows with a CAR on both sides, and how many of them get
                              the same |car_z| >= ABNORMAL_RETURN_Z call
      by_event    per event type: windows, mean CAR on each side, significant windows
      ok          True when there is something to compare, no keys repeat, no column
                  differs and every window is matched or still open
    """
    types = CONTRACTS["stream_event_car"]
    s, b = _normalise(stream, types), _normalise(batch, types)
    duplicates = {"stream": int(s.duplicated(KEYS).sum()), "batch": int(b.duplicated(KEYS).sum())}
    joined = s.merge(b, on=KEYS, how="outer", suffixes=("_stream", "_batch"), indicator=True)

    only_stream = joined.loc[joined["_merge"] == "left_only", KEYS].reset_index(drop=True)
    only_batch = joined.loc[joined["_merge"] == "right_only", KEYS + ["day0_date_batch"]]
    if stream_end is not None and trading_days is not None:
        days = pd.DatetimeIndex(sorted(pd.to_datetime(pd.Series(trading_days)).unique()))
        ends = _window_ends(only_batch["day0_date_batch"], days)
        open_mask = ends.isna() | (ends > pd.Timestamp(stream_end))
    else:
        open_mask = pd.Series(False, index=only_batch.index)
    still_open = only_batch.loc[open_mask, KEYS].reset_index(drop=True)
    missing_from_stream = only_batch.loc[~open_mask, KEYS].reset_index(drop=True)
    only_batch = only_batch[KEYS].reset_index(drop=True)
    both = joined[joined["_merge"] == "both"]

    columns = {}
    for col, kind in types.items():
        if col in KEYS:
            continue
        a, c = both[f"{col}_stream"], both[f"{col}_batch"]
        both_missing = a.isna() & c.isna()
        if kind == "double":
            diff = (a - c).abs()
            same = (diff <= tolerance) | both_missing
            max_diff = float(diff.max()) if diff.notna().any() else 0.0
        else:
            same = (a == c).fillna(False).astype(bool) | both_missing
            max_diff = None
        columns[col] = {"n_mismatch": int((~same).sum()), "max_diff": max_diff}

    called = both[(both["n_days_stream"] > 0) & (both["n_days_batch"] > 0)]
    sig_stream = called["car_z_stream"].abs() >= ABNORMAL_RETURN_Z
    sig_batch = called["car_z_batch"].abs() >= ABNORMAL_RETURN_Z
    by_event = (called.assign(sig_stream=sig_stream, sig_batch=sig_batch)
                .groupby("event_type").agg(
                    windows=("ticker", "size"),
                    mean_car_stream=("car_stream", "mean"),
                    mean_car_batch=("car_batch", "mean"),
                    significant_stream=("sig_stream", "sum"),
                    significant_batch=("sig_batch", "sum")))

    ok = (len(both) > 0
          and not any(duplicates.values())
          and all(c["n_mismatch"] == 0 for c in columns.values())
          and only_stream.empty and missing_from_stream.empty)
    return {
        "n_stream": len(s), "n_batch": len(b), "n_both": len(both), "duplicates": duplicates,
        "only_stream": only_stream, "only_batch": only_batch,
        "still_open": still_open, "missing_from_stream": missing_from_stream,
        "columns": columns,
        "n_called": len(called), "n_same_call": int(np.sum(sig_stream == sig_batch)),
        "by_event": by_event,
        "ok": ok,
    }
```


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