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

# Data contracts

**Status: AGREED 2026-11-25.** The contracts below describe the files as built (decisions 0005, 0006, 0007, 0010). Change one only together with `src/common/contracts.py` and a decision record (AGENTS.md rule 1).

**To change a contract,** edit this file **and** `src/common/contracts.py` in the same commit. `tests/test_contracts.py` fails if they disagree. The tables between the `contract:` markers are read by that test, so keep each row as ``| `column` | type | meaning |``.

**Four kinds of dataset,** each in its own place:

| Kind | Where | Committed | Made by |
| - | - | - | - |
| Registries: *what* is studied | `config/*.csv` | yes | people, by adding rows |
| Clean tables | `clean/<dataset>.parquet` | yes (small) | the scripts in `etl/` |
| Raw downloads | `raw/` | never | the download scripts in `etl/` |
| Run outputs (replay files, stream output, results) | `data/`, `checkpoints/` | never | producers, the streaming job, the event study |

*How* it is studied (years, market index, windows, thresholds) is in `src/common/study.py`, and file locations and Kafka servers are in `src/common/settings.py`. Code reads all of them from there and never types them in (decision 0005; `tests/test_no_hardcoding.py` checks).

## Rules for every dataset

* **Types:** `string`, `long` (64-bit integer), `int` (32-bit), `double`, `date`, `timestamp`.
* **Time:** timestamps are UTC, and their column names end in `_utc`. Dates are calendar dates with no time zone. Spark sessions set `spark.sql.session.timeZone=UTC`.
* **Tickers:** Yahoo Finance symbols in capitals, for example `WMT`, `AMZN`, or `L.TO` for TSX listings.
* **Countries and regions:** two-letter codes (`US`, `CA`, `CN`), or `global`, so a retailer's `country` can be matched to an event's `region`.
* **Validate before writing.** Every script that writes a dataset calls `common.contracts.require_contract(dataset, pandas_columns(df))` first. `tests/test_clean_files.py` checks the committed clean files against their contracts and against `config/`.
* **Kafka:** one JSON object per message, with field names exactly as below and dates as `YYYY-MM-DD` strings.

## Registries (`config/`)

Each file's header must be exactly its contract's columns, in order; the loaders in `common.contracts` (`load_event_types`, `load_retailers`, `load_wiki_articles`, `load_retail_series`) refuse anything else. `tests/test_config.py` and `tests/test_event_calendar.py` check every row, so adding a row can't silently break anything.

### Event calendar (expandable)

Events are data, not code (decision 0003). Three things work together:

1. **`config/event_types.csv`** (the registry): one row per kind of event, with a rule for computing its dates. Add an event by adding a row.
2. **`config/event_dates.csv`**: dates for events whose rule is `listed`, such as lunar-calendar holidays or announced sales. Each row needs a source.
3. **The `events` table:** every occurrence of every in-scope event over the study period, computed from the two files by `common.contracts.expand_events(STUDY_START_YEAR, STUDY_END_YEAR)`. Code calls that function instead of reading a stored copy, so it can never be out of date.

**Date rules** in `date_rule` (checked by `tests/test_event_calendar.py`):

| Rule | Meaning | Example |
| - | - | - |
| `fixed:MM-DD` | Same date every year | Halloween `fixed:10-31` |
| `nth_weekday:MM:<mon..sun>:N` | The N-th weekday of a month (`-1` = last) | US Thanksgiving `nth_weekday:11:thu:4` |
| `offset:<event_type>:+D` | D days after (or `-D` before) another event | Black Friday `offset:us_thanksgiving:+1` |
| `listed` | Dates come from `config/event_dates.csv` | Chinese New Year, Prime Day |

#### event\_types

Owner: Anushiya (rows agreed in a meeting or a decision record). Stored at `config/event_types.csv`.

| column | type | meaning |
| - | - | - |
| `event_type` | string | Unique snake\_case id, e.g. `black_friday`, `chinese_new_year` |
| `name` | string | Display name for charts and the report |
| `category` | string | `shopping`, `holiday` or `cultural` (add more if needed) |
| `region` | string | Where it is observed: `US`, `CA`, `CN`, `global`; several separated by `;` |
| `date_rule` | string | How dates are computed (rules above) |
| `in_scope` | string | `yes` if the pipeline uses it now, `no` for candidates |
| `notes` | string | Source or caveats |

#### event\_dates

Owner: Anushiya, with a source for every row. Stored at `config/event_dates.csv`. Only for `listed` events.

| column | type | meaning |
| - | - | - |
| `event_type` | string | Must be an event whose rule is `listed` |
| `event_date` | date | First day |
| `event_end_date` | date | Last day; same as `event_date` for one-day events |
| `source` | string | URL or citation the date came from |

#### events

Computed by `expand_events`, not stored (`etl/build_events.py` writes a copy to `data/events.parquet` for browsing). It returns a list of dicts with the columns below, dates as Python `date` objects. The streaming job and the batch study take event windows from here, not from `master.event_type`.

| column | type | meaning |
| - | - | - |
| `event_type` | string | An `event_type` from `config/event_types.csv` (bonus: `earnings` with a specific ticker) |
| `event_date` | date | First day of this occurrence |
| `event_end_date` | date | Last day; same as `event_date` for one-day events (Prime Day spans several) |
| `ticker` | string | Affected ticker, or `ALL` for market-wide events |

**Open question:** should regional events (e.g., Boxing Day for TSX stocks) apply only to retailers whose `country` is in the event's `region`?

### retailers

Owner: Anushiya. Stored at `config/retailers.csv`. The stocks the project studies: the downloads, the join and the streaming job cover exactly the in-scope rows. The market index (`common.study.MARKET_TICKER`) is downloaded with them but is not a retailer, so it is not listed. `etl/join_master.py` copies each retailer's `country` and `retailer_type` into `master`, so analyses can read them there; this file stays the one place they are typed.

| column | type | meaning |
| - | - | - |
| `ticker` | string | Yahoo Finance symbol, unique |
| `company` | string | Company name |
| `country` | string | Where the company is based: `US`, `CA`, `CN` |
| `retailer_type` | string | `online` or `store` |
| `in_scope` | string | `yes` if the pipeline uses it now, `no` for candidates |
| `notes` | string | Listing details or caveats |

### wiki\_articles

Owner: Sanchi. Stored at `config/wiki_articles.csv`. Every in-scope retailer needs at least one title. When an article was renamed, list both titles: Wikipedia counts views under the title readers asked for, and `etl/pageviews_clean.py` adds them together per ticker and day.

| column | type | meaning |
| - | - | - |
| `article` | string | English Wikipedia title, spaces as underscores, e.g. `Best_Buy` |
| `ticker` | string | A ticker from `config/retailers.csv` |
| `notes` | string | E.g. when the title was renamed |

### retail\_series

Owner: Areej. Stored at `config/retail_series.csv`. US Census monthly retail sales series, downloaded from FRED as `raw/census/<series_id>.csv`.

| column | type | meaning |
| - | - | - |
| `series_id` | string | FRED series code, e.g. `RSXFS` |
| `category` | string | Unique snake\_case name used in `retail_sales`, e.g. `all_retail` |
| `notes` | string | What the series covers |

## Clean tables (`clean/`)

Built by `etl/` from `raw/` and `config/`, one row per key listed, over the study period in `common.study`. The original plan's hourly `prices` and `attention` tables were replaced by these daily tables in the ETL phase (decisions 0004 and 0005).

### prices

Owner: Mahad (`etl/prices_download.py`, `etl/prices_clean.py`). One row per ticker per trading day, for every in-scope retailer plus the market index.

| column | type | meaning |
| - | - | - |
| `ticker` | string | Stock symbol |
| `date` | date | Trading day |
| `adj_close` | double | Closing price adjusted for splits and dividends |
| `volume` | long | Shares traded |
| `ret` | double | Simple return, `adj_close` / previous `adj_close` − 1; null on each ticker's first day |
| `vol_ratio` | double | `volume` / mean volume of the previous 20 trading days (fewer at the start of the data); null on each ticker's first day |

### pageviews

Owner: Sanchi (`etl/pageviews_download.py`, `etl/pageviews_clean.py`). One row per in-scope retailer per calendar day; days with no data are 0.

| column | type | meaning |
| - | - | - |
| `article` | string | The ticker's current title (the one with the most views in the latest year) |
| `ticker` | string | Stock symbol |
| `date` | date | Calendar day |
| `views` | int | Views by people (no bots), all titles of the ticker added together |

### retail\_sales

Owner: Areej (`etl/retail_clean.py`). One row per series per month. FRED gives the latest revised numbers, not the first release.

| column | type | meaning |
| - | - | - |
| `category` | string | From `config/retail_series.csv` |
| `month` | date | First day of the month |
| `sales` | long | Sales in millions of US dollars |
| `mom_change` | double | Change from the previous month, `sales` / previous − 1 |
| `release_date` | date | About when the number became public (the 15th of the next month, approximate) |

### master (what Kafka carries)

Owner: Sanchi (`etl/join_master.py` builds `clean/master.parquet`; `src/producers/replay_master.py` sends it). Consumer: the streaming job.
Kafka topic `calendar-effects-master` (`KAFKA_TOPICS["master"]`), keyed by `ticker`, one JSON object per row, one row per ticker per trading day (the same rows as `prices`).

| column | type | meaning |
| - | - | - |
| `ticker` | string | Stock symbol; `common.study.MARKET_TICKER` is the market index |
| `date` | date | Trading day, sent as `YYYY-MM-DD` |
| `adj_close` | double | From `prices` |
| `volume` | long | From `prices` |
| `ret` | double | From `prices` |
| `vol_ratio` | double | From `prices` |
| `views` | double | Wikipedia page views that day; null for the market index. A double only because pandas stores nullable counts as floats |
| `event_type` | string | Calendar event on that trading day, or null. Events on non-trading days do not appear here, and two in-scope events on the same day stop `etl/join_master.py` |
| `country` | string | From `config/retailers.csv`; `common.study.MARKET_COUNTRY` for the market index |
| `retailer_type` | string | `online` or `store` from `config/retailers.csv`; `market` (`common.study.MARKET_RETAILER_TYPE`) for the market index |

The streaming job adds `timestamp_utc` (the trading day at 00:00 UTC) as its event time.

## Outputs

The streaming vs batch comparison (`scripts/compare_stream_batch.py`, rules in `src/streaming/compare.py`) joins `stream_event_car` and `batch_event_car` on `ticker`, `event_type`, `event_date` and expects every value to agree within 1e-9. Both sides take the return definition, market index and window lengths from `src/common/study.py` (decision 0004).

### stream\_signals

Owner: Mahad (the streaming job). One row per ticker per trading day, the market index excluded.
Stored as Parquet in `data/stream/signals/batch_id=<N>/`, one folder per micro-batch (rewritten whole if Spark retries the batch, so reruns give the same files).

| column | type | meaning |
| - | - | - |
| `ticker` | string | Stock symbol |
| `date` | date | Trading day |
| `timestamp_utc` | timestamp | `date` at 00:00 UTC, the event time the job windows on |
| `ret` | double | Simple return of the stock |
| `mkt_ret` | double | Simple return of the market index that day |
| `alpha` | double | Market-model intercept, fitted on the estimation window before this day |
| `beta` | double | Market-model slope, same window |
| `ar` | double | Abnormal return, `ret` − (`alpha` + `beta` × `mkt_ret`) |
| `ar_sd` | double | Standard deviation of the model's errors in the estimation window |
| `z_ar` | double | `ar` / `ar_sd` |
| `abnormal_return` | int | 1 if \|`z_ar`\| ≥ `ABNORMAL_RETURN_Z`, 0 if not, null without a model |
| `views` | double | Wikipedia page views |
| `z_views` | double | `views` against the attention baseline, in standard deviations |
| `attention_spike` | int | 1 if `z_views` ≥ `ATTENTION_SPIKE_Z`, 0 if not, null without a baseline |
| `vol_ratio` | double | Passed through from `master` |
| `event_type` | string | Passed through from `master` |
| `estimation_days` | int | Days used to fit the model; 0 means no model yet |

### stream\_event\_car

Owner: Mahad (the streaming job). One row per ticker per event occurrence, emitted when day +5 has been processed.
Stored as Parquet in `data/stream/event_car/batch_id=<N>/`.

Each window has one market model, fitted on the `ESTIMATION_DAYS` trading days before day −5, the same way as the batch study. So with the same data, `car` should equal the batch CAR. (The daily `ar` in `stream_signals` uses a model re-fitted every day, so summing it does not give `car`.) `alpha`, `beta`, `ar_sd`, `car`, `car_z` and `max_z_views` are null when `n_days` = 0, which happens to windows too early in the data to have a model.

| column | type | meaning |
| - | - | - |
| `ticker` | string | Stock symbol |
| `event_type` | string | From the calendar (`common.contracts.expand_events`) |
| `event_date` | date | Calendar date of the event (may be a non-trading day) |
| `event_end_date` | date | Last day of the event |
| `day0_date` | date | First trading day on or after `event_date` |
| `alpha` | double | Event model intercept, fitted on the days before the window |
| `beta` | double | Event model slope |
| `ar_sd` | double | Standard deviation of the event model's errors |
| `estimation_days` | int | Days used to fit the event model; 0 means no model |
| `car` | double | Sum of abnormal returns under the event model, days −5 to +5 |
| `car_z` | double | `car` / (`ar_sd` × √`n_days`) |
| `n_days` | int | Window days with both returns present: 11 when complete, 0 without a model |
| `n_abnormal_days` | int | Window days whose abnormal return / `ar_sd` is at least `ABNORMAL_RETURN_Z` in size |
| `max_z_views` | double | Highest `z_views` in the window |
| `n_spike_days` | int | Window days with `z_views` ≥ `ATTENTION_SPIKE_Z` (`attention_spike` = 1 in `stream_signals`) |

**Reading the outputs:** Spark and pyarrow turn the `batch_id=<N>` folders into a `batch_id` column. Drop it before `check_columns`. The last few trading days of a replay stay behind the watermark and are not written until newer data arrives.

### batch\_event\_car

Owner: Areej (`src/eventstudy/car.py`, the batch event study and answer key). One row per ticker per event occurrence whose window −5..+5 is complete in `clean/master.parquet`.
Stored as Parquet in `data/results/batch_event_car.parquet`, with `batch_event_car.json` next to it recording the code version and time of the run.

Same columns and meanings as `stream_event_car`, computed from the whole of `master` at once with numpy instead of day by day. Events come from `expand_events` (not master's `event_type`), day 0 is the first trading day on or after `event_date`, and the market model is fitted on the `ESTIMATION_DAYS` trading days before day −5. `z_views` follows the stream's attention rule, so `max_z_views` and `n_spike_days` should match too. The comparison joins on `ticker`, `event_type`, `event_date` and expects equal values.

| column | type | meaning |
| - | - | - |
| `ticker` | string | Stock symbol |
| `event_type` | string | From the calendar (`common.contracts.expand_events`) |
| `event_date` | date | Calendar date of the event (may be a non-trading day) |
| `event_end_date` | date | Last day of the event |
| `day0_date` | date | First trading day on or after `event_date` |
| `alpha` | double | Event model intercept, fitted on the days before the window |
| `beta` | double | Event model slope |
| `ar_sd` | double | Standard deviation of the event model's errors |
| `estimation_days` | int | Days used to fit the event model; 0 means no model |
| `car` | double | Sum of abnormal returns under the event model, days −5 to +5 |
| `car_z` | double | `car` / (`ar_sd` × √`n_days`) |
| `n_days` | int | Window days with both returns present: 11 when complete, 0 without a model |
| `n_abnormal_days` | int | Window days whose abnormal return / `ar_sd` is at least `ABNORMAL_RETURN_Z` in size |
| `max_z_views` | double | Highest `z_views` in the window |
| `n_spike_days` | int | Window days with `z_views` ≥ `ATTENTION_SPIKE_Z` (`attention_spike` = 1 in `stream_signals`) |

### batch\_car\_summary

Owner: Areej (`src/eventstudy/stats.py`). Significance of the mean CAR, for the report. One row per event type (plus `all`, where windows shared by two event types, such as US Thanksgiving and Black Friday, count once) per group: `all` retailers, each `retailer_type`, and the difference between the two types (e.g. `online_minus_store`, the per-event-date difference of group means). Only windows with a CAR (`n_days` > 0).
Stored as CSV in `data/results/batch_car_summary.csv`.

| column | type | meaning |
| - | - | - |
| `event_type` | string | Event from the calendar, or `all` |
| `group` | string | `all`, a `retailer_type` from `config/retailers.csv`, or `<type>_minus_<type>` |
| `n_windows` | int | Ticker-event windows used |
| `n_events` | int | Distinct event dates (day 0) |
| `n_tickers` | int | Distinct tickers |
| `mean_car` | double | Mean CAR (for a difference row, mean difference) |
| `median_car` | double | Median CAR |
| `ci_low` | double | Lower end of the 95% confidence interval, clustered by event date |
| `ci_high` | double | Upper end of that interval |
| `pct_positive` | double | Share of CARs (or differences) above 0 |
| `p_t` | double | One-sample t-test of mean = 0, windows treated as independent |
| `p_wilcoxon` | double | Wilcoxon signed-rank test of median = 0 |
| `p_bmp` | double | t-test on `car_z` (BMP-style standardized test); null for difference rows |
| `p_clustered` | double | t-test with standard errors clustered by event date; the main test |

### batch\_car\_trend

Owner: Areej (`src/eventstudy/stats.py`). Does the CAR change over the years? Per event type (and `all`), the mean CAR of each event date regressed on its year.
Stored as CSV in `data/results/batch_car_trend.csv`.

| column | type | meaning |
| - | - | - |
| `event_type` | string | Event from the calendar, or `all` |
| `n_events` | int | Event dates in the regression |
| `n_tickers` | int | Distinct tickers |
| `first_year` | int | Earliest year |
| `last_year` | int | Latest year |
| `slope_per_year` | double | Change in mean CAR per year (OLS slope) |
| `ci_low` | double | Lower end of the slope's 95% confidence interval |
| `ci_high` | double | Upper end |
| `p_value` | double | Test of slope = 0 |

## Machine learning (decision 0007)

The big-move model asks: from today's daily row, will this stock make a big move tomorrow (tomorrow's `abnormal_return` = 1)? `src/ml/train.py` trains it with Spark MLlib on `stream_signals`, using the features in `src/ml/features.py`, and the streaming job scores it live. Owner: Mahad.

### stream\_predictions

Stored as Parquet in `data/stream/predictions/batch_id=<N>/`, written by the streaming job when a trained model exists in `data/models/big_move/`. One row per retailer per trading day whose features are all present.

| column | type | meaning |
| - | - | - |
| `ticker` | string | Stock symbol |
| `date` | date | The trading day the prediction is made on |
| `timestamp_utc` | timestamp | That day at 00:00 UTC |
| `p_big_move_next` | double | Model probability that the stock's next trading day is a big move |
| `big_move_alert` | int | 1 when `p_big_move_next` is at or above the cut-off that flags the top `ML_ALERT_TOP_SHARE` of stock-days in the training years |

### ml\_metrics

Stored as CSV in `data/results/ml_metrics.csv`. One row per model tried: each candidate on the validation year, then the chosen model, the same model without attention features, and a no-model baseline on the test years.

| column | type | meaning |
| - | - | - |
| `model` | string | `logistic`, `gbt` or `baseline_abs_z_ar` |
| `params` | string | Hyperparameters as JSON |
| `features` | string | `all`, `no_attention` or `abs_z_ar` (the baseline's single score) |
| `split` | string | `validation` (`ML_VALIDATION_YEAR`) or `test` (`ML_TEST_START_YEAR` onwards) |
| `n_rows` | long | Stock-days scored |
| `n_big_moves` | long | Of those, days followed by a big move |
| `base_rate` | double | `n_big_moves` / `n_rows` |
| `auc_roc` | double | ROC area: 0.5 is chance, 1 is perfect ranking |
| `auc_pr` | double | Precision-recall area: compare with `base_rate` |
| `precision_top` | double | Share of big moves among the top `ML_ALERT_TOP_SHARE` of scores |
| `lift_top` | double | `precision_top` / `base_rate` |

### ml\_test\_predictions

Stored as Parquet in `data/results/ml_test_predictions.parquet`: the chosen model's predictions on the test years, for charts and the report.

| column | type | meaning |
| - | - | - |
| `ticker` | string | Stock symbol |
| `date` | date | The trading day the prediction is made on |
| `p_big_move_next` | double | Model probability of a big move on the next trading day |
| `big_move_next` | int | What happened: 1 if the next trading day was a big move |

### ml\_feature\_importance

Stored as CSV in `data/results/ml_feature_importance.csv`. For trees, MLlib's feature importances; for logistic regression, the absolute coefficients on standardized features. Normalized to sum to 1.

| column | type | meaning |
| - | - | - |
| `model` | string | `logistic` or `gbt` |
| `feature` | string | A name from `ml.features.FEATURES` |
| `importance` | double | Its share of the model's importance |


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