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

> The batch event study (src/eventstudy/) on small hand-made data where the right answer is known in advance.

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

## What it does

The batch event study (src/eventstudy/) on small hand-made data where the right
answer is known in advance.

## What is inside

* **`STOCK`** · [line 17](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_eventstudy.py#L17): a made-up ticker, so the test does not depend on config/
* **`make_master(n_days, jump_on, seed)`** · [line 20](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_eventstudy.py#L20): A stock that follows ret = ALPHA + BETA \* market + tiny noise, plus JUMP on one day.
* **`event(d, name)`** · [line 34](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_eventstudy.py#L34)

## What it checks

* market model recovers alpha and beta (line 38)
* market model needs enough days (line 45)
* car is the jump on day zero (line 50)
* weekend event starts on the next trading day (line 64)
* early event has no model and late event is skipped (line 72)
* output matches its contract (line 80)
* clustered test treats each event date as one observation (line 86)
* summary and trend tables match their contracts (line 96)

## 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/eventstudy/car.py`](https://calendar-effects.mintlify.site/reference/src/eventstudy/car), [`src/eventstudy/stats.py`](https://calendar-effects.mintlify.site/reference/src/eventstudy/stats)

## Source

```python title="tests/test_eventstudy.py" lines expandable theme={null}
"""The batch event study (src/eventstudy/) on small hand-made data where the right
answer is known in advance."""
from __future__ import annotations

from datetime import date

import numpy as np
import pandas as pd
import pytest

from common.contracts import MARKET_WIDE_TICKER, check_columns, pandas_columns
from common.study import ESTIMATION_DAYS, EVENT_WINDOW, MARKET_TICKER, MIN_ESTIMATION_DAYS
from eventstudy.car import compute_cars, fit_market_model
from eventstudy.stats import build_tables, clustered_mean_test

ALPHA, BETA, JUMP = 0.0005, 1.5, 0.02
STOCK = "TEST"  # a made-up ticker, so the test does not depend on config/


def make_master(n_days=300, jump_on=None, seed=0):
    """A stock that follows ret = ALPHA + BETA * market + tiny noise, plus JUMP on one day."""
    rng = np.random.default_rng(seed)
    days = pd.bdate_range("2020-01-01", periods=n_days)  # weekdays only, like trading days
    mkt = rng.normal(0, 0.01, n_days)
    ret = ALPHA + BETA * mkt + rng.normal(0, 1e-6, n_days)
    if jump_on is not None:
        ret[days.get_loc(pd.Timestamp(jump_on))] += JUMP
    rows = []
    for ticker, r in ((MARKET_TICKER, mkt), (STOCK, ret)):
        rows.append(pd.DataFrame({"ticker": ticker, "date": days.date, "ret": r, "views": 100.0}))
    return pd.concat(rows, ignore_index=True), days


def event(d: date, name="test_event"):
    return {"event_type": name, "event_date": d, "event_end_date": d, "ticker": MARKET_WIDE_TICKER}


def test_market_model_recovers_alpha_and_beta():
    rng = np.random.default_rng(1)
    mkt = rng.normal(0, 0.01, ESTIMATION_DAYS)
    fit = fit_market_model(ALPHA + BETA * mkt, mkt)
    assert fit[0] == pytest.approx(ALPHA) and fit[1] == pytest.approx(BETA) and fit[3] == ESTIMATION_DAYS


def test_market_model_needs_enough_days():
    mkt = np.linspace(-0.01, 0.01, MIN_ESTIMATION_DAYS - 1)
    assert fit_market_model(mkt, mkt) is None


def test_car_is_the_jump_on_day_zero():
    master, days = make_master()
    day0 = days[200].date()
    master, _ = make_master(jump_on=day0)
    cars = compute_cars(master, [event(day0)])
    row = cars.iloc[0]
    assert row["day0_date"] == day0
    assert row["n_days"] == EVENT_WINDOW[1] - EVENT_WINDOW[0] + 1
    assert row["estimation_days"] == ESTIMATION_DAYS
    # The model is fitted before the window, so the jump is not in it: CAR is the jump.
    assert row["car"] == pytest.approx(JUMP, abs=1e-4)
    assert row["n_abnormal_days"] >= 1


def test_weekend_event_starts_on_the_next_trading_day():
    master, days = make_master()
    monday = days[200:][days[200:].weekday == 0][0].date()
    saturday = date.fromordinal(monday.toordinal() - 2)
    row = compute_cars(master, [event(saturday)]).iloc[0]
    assert row["event_date"] == saturday and row["day0_date"] == monday


def test_early_event_has_no_model_and_late_event_is_skipped():
    master, days = make_master()
    early, late = days[20].date(), days[-2].date()   # too little history / window not complete
    cars = compute_cars(master, [event(early), event(late)])
    assert len(cars) == 1
    assert cars.iloc[0]["n_days"] == 0 and np.isnan(cars.iloc[0]["car"])


def test_output_matches_its_contract():
    master, days = make_master()
    cars = compute_cars(master, [event(days[200].date())])
    assert not check_columns("batch_event_car", pandas_columns(cars))


def test_clustered_test_treats_each_event_date_as_one_observation():
    # Two event dates, each with identical CARs for 10 stocks: there are only two
    # independent observations, so the clustered test must be far less sure than a
    # test that counts 20 windows.
    car = pd.Series([0.01] * 10 + [0.03] * 10)
    cluster = pd.Series(["a"] * 10 + ["b"] * 10)
    low, high, p = clustered_mean_test(car, cluster)
    assert low < 0.02 < high and p > 0.05


def test_summary_and_trend_tables_match_their_contracts():
    master, days = make_master(n_days=900)
    events = [event(days[i].date(), name) for i in (200, 450, 700) for name in ("e1", "e2")]
    cars = compute_cars(master, events)
    retailers = [{"ticker": STOCK, "retailer_type": "online"}]
    summary, trend = build_tables(cars, retailers)
    assert not check_columns("batch_car_summary", pandas_columns(summary))
    assert not check_columns("batch_car_trend", pandas_columns(trend))
    # e1 and e2 share every window, so "all" counts each window once.
    assert summary.query("event_type == 'all' and group == 'all'")["n_windows"].item() == 3
```


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