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

# etl/join_master.py

> Join prices, page views and events into clean/master.parquet, the one table Kafka replays later.

`etl/join_master.py` · chapter [Building a row](https://calendar-effects.mintlify.site/tour/03-building-a-row.md), file 7 · 60 lines · [open in the repository](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/etl/join_master.py)

## What it does

Join prices, page views and events into clean/master.parquet, the one table
Kafka replays later.

Run from anywhere:   python3 etl/join\_master.py
Output: the `master` contract, one row per ticker per trading day (same rows as
clean/prices.parquet), plus:
views        Wikipedia page views that day (empty for the market index, which has no article)
event\_type   the calendar event on that day, empty on ordinary days

Events come straight from the shared calendar (config/event\_types.csv and
config/event\_dates.csv via common.contracts.expand\_events), so adding an event
there adds it here with no code change. Multi-day events such as Prime Day are
spread over every day from event\_date to event\_end\_date.

country and retailer\_type come from config/retailers.csv (the market index gets
common.study's MARKET\_COUNTRY and MARKET\_RETAILER\_TYPE), so an analysis can split
online vs store straight from master while the labels are typed only once.

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

## Source

```python title="etl/join_master.py" lines expandable theme={null}
"""Join prices, page views and events into clean/master.parquet, the one table
Kafka replays later.

Run from anywhere:   python3 etl/join_master.py
Output: the `master` contract, one row per ticker per trading day (same rows as
clean/prices.parquet), plus:
  views        Wikipedia page views that day (empty for the market index, which has no article)
  event_type   the calendar event on that day, empty on ordinary days

Events come straight from the shared calendar (config/event_types.csv and
config/event_dates.csv via common.contracts.expand_events), so adding an event
there adds it here with no code change. Multi-day events such as Prime Day are
spread over every day from event_date to event_end_date.

country and retailer_type come from config/retailers.csv (the market index gets
common.study's MARKET_COUNTRY and MARKET_RETAILER_TYPE), so an analysis can split
online vs store straight from master while the labels are typed only once.
"""
import pandas as pd

from common.contracts import expand_events, load_retailers, pandas_columns, require_contract
from common.settings import clean_path
from common.study import (MARKET_COUNTRY, MARKET_RETAILER_TYPE, MARKET_TICKER,
                          STUDY_END_YEAR, STUDY_START_YEAR)

prices = pd.read_parquet(clean_path('prices'))
views = pd.read_parquet(clean_path('pageviews'))[['ticker', 'date', 'views']]
for df in (prices, views):
    df['date'] = pd.to_datetime(df['date']).dt.date

# One row per event day; all current events are market-wide (ticker ALL).
event_days = []
for e in expand_events(STUDY_START_YEAR, STUDY_END_YEAR):
    for d in pd.date_range(e['event_date'], e['event_end_date']):
        event_days.append({'date': d.date(), 'event_type': e['event_type']})
events = pd.DataFrame(event_days)
clashes = events[events.duplicated('date', keep=False)]
assert clashes.empty, f'two events on the same day would duplicate price rows:\n{clashes}'

labels = pd.DataFrame(
    [{k: r[k] for k in ('ticker', 'country', 'retailer_type')} for r in load_retailers()]
    + [{'ticker': MARKET_TICKER, 'country': MARKET_COUNTRY, 'retailer_type': MARKET_RETAILER_TYPE}])

master = (prices
    .merge(views, on=['ticker', 'date'], how='left')
    .merge(events, on='date', how='left')
    .merge(labels, on='ticker', how='left'))
assert master['retailer_type'].notna().all(), \
    f"tickers missing from config/retailers.csv: {sorted(master.loc[master['retailer_type'].isna(), 'ticker'].unique())}"
master['views'] = master['views'].astype('float64')  # nullable count: empty for the market index

master = master.sort_values(['date', 'ticker']).reset_index(drop=True)
require_contract('master', pandas_columns(master))
master.to_parquet(clean_path('master'), index=False)

# Checks
assert len(master) == len(prices), 'row count must equal prices'
print(len(master), 'rows;', master['event_type'].notna().sum(), 'rows on an event day')
print(master.groupby('event_type')['date'].nunique().rename('trading days matched'))
print('tickers with missing views:', master.loc[master['views'].isna(), 'ticker'].unique())
```


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