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

# scripts/compare_stream_batch.py

> Streaming vs batch: does the stream reproduce the batch event study's answer key? (task #9)

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

## What it does

Streaming vs batch: does the stream reproduce the batch event study's answer key? (task #9)

Joins the streaming job's event CARs (data/stream/event\_car/) to the batch study's
(data/results/batch\_event\_car.parquet) on ticker, event\_type and event\_date, and
compares every column. Decisions 0004 and 0006 expect equal values, so any difference
beyond rounding error is a failure. See streaming/compare.py for the rules.

Run from anywhere, after the streaming job and the batch study:

```bash theme={null}
python3 src/eventstudy/car.py
python3 scripts/compare_stream_batch.py [--stream FOLDER] [--batch FILE]
```

\--stream is the job's output folder (the one holding signals/ and event\_car/).
Exits with code 1 if the two disagree.

## Connections

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

## Source

```python title="scripts/compare_stream_batch.py" lines expandable theme={null}
"""Streaming vs batch: does the stream reproduce the batch event study's answer key? (task #9)

Joins the streaming job's event CARs (data/stream/event_car/) to the batch study's
(data/results/batch_event_car.parquet) on ticker, event_type and event_date, and
compares every column. Decisions 0004 and 0006 expect equal values, so any difference
beyond rounding error is a failure. See streaming/compare.py for the rules.

Run from anywhere, after the streaming job and the batch study:
    python3 src/eventstudy/car.py
    python3 scripts/compare_stream_batch.py [--stream FOLDER] [--batch FILE]
--stream is the job's output folder (the one holding signals/ and event_car/).
Exits with code 1 if the two disagree.
"""
import argparse
import sys
from pathlib import Path

import pandas as pd

from common.contracts import parquet_columns, require_contract
from common.settings import STREAM_DIR, STREAM_SUBDIRS, clean_path
from common.study import ABNORMAL_RETURN_Z
from eventstudy.car import OUTPUT as BATCH_OUTPUT
from streaming.compare import KEYS, TOLERANCE, compare

parser = argparse.ArgumentParser()
parser.add_argument("--stream", default=str(STREAM_DIR), help="the streaming job's output folder")
parser.add_argument("--batch", default=str(BATCH_OUTPUT), help="the batch study's answer key")
args = parser.parse_args()

event_car = Path(args.stream) / STREAM_SUBDIRS["stream_event_car"]
signals = Path(args.stream) / STREAM_SUBDIRS["stream_signals"]
for dataset, path in (("stream_event_car", event_car), ("stream_signals", signals),
                      ("batch_event_car", Path(args.batch))):
    require_contract(dataset, parquet_columns(path))
stream = pd.read_parquet(event_car)
batch = pd.read_parquet(args.batch)
# The last trading day the stream processed, and the trading calendar, decide which
# windows missing from the stream are only still open.
stream_end = pd.to_datetime(pd.read_parquet(signals, columns=["date"])["date"]).max()
trading_days = pd.read_parquet(clean_path("master"), columns=["date"])["date"]

r = compare(stream, batch, stream_end=stream_end, trading_days=trading_days)
print(f"stream: {r['n_stream']} event windows ({event_car}), last trading day {stream_end.date()}")
print(f"batch:  {r['n_batch']} event windows ({args.batch})")
print(f"joined on {', '.join(KEYS)}: {r['n_both']} in both, {len(r['only_stream'])} only in the "
      f"stream, {len(r['only_batch'])} only in the batch ({len(r['still_open'])} still open in the stream)")
if any(r["duplicates"].values()):
    print(f"repeated keys: {r['duplicates']['stream']} in the stream, {r['duplicates']['batch']} in the batch")
for name, keys in (("only in the stream", r["only_stream"]),
                   ("missing from the stream (already closed there)", r["missing_from_stream"])):
    if len(keys):
        print(f"\n{name}:\n{keys.head(10).to_string(index=False)}")

print(f"\n{'column':<16} {'mismatches':>10}  largest difference (tolerance {TOLERANCE:g})")
for col, c in r["columns"].items():
    diff = "exact" if c["max_diff"] is None else f"{c['max_diff']:.2e}"
    print(f"{col:<16} {c['n_mismatch']:>10}  {diff}")

share = r["n_same_call"] / r["n_called"] if r["n_called"] else float("nan")
print(f"\nsame call |car_z| >= {ABNORMAL_RETURN_Z} (the alert threshold, not the report's clustered "
      f"test) in {r['n_same_call']} of {r['n_called']} windows with a CAR ({share:.1%})")
print(f"\n{r['by_event'].round(4).to_string()}")

if r["ok"]:
    print("\nOK: the stream matches the batch answer key")
else:
    print("\nFAILED: the stream and the batch answer key disagree (see above)")
    sys.exit(1)
```


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