> ## 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/producers/replay_master.py

> Replay clean/master.parquet into Kafka, one trading day at a time, as if the past ten years were happening live.

`src/producers/replay_master.py` · chapter [Replaying the data](https://calendar-effects.mintlify.site/tour/04-replaying.md), file 3 · 83 lines · [open in the repository](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/producers/replay_master.py)

## What it does

Replay clean/master.parquet into Kafka, one trading day at a time, as if the
past ten years were happening live.

Run on the course cluster:

```bash theme={null}
python3 src/producers/replay_master.py
```

Faster or slower:   --seconds-per-day 0.05   (2,514 trading days x 0.1 s = about 4 minutes)
Local Kafka:        --bootstrap localhost:9092   (or set KAFKA\_BOOTSTRAP)

Each message is one row of the master table as JSON, keyed by ticker:

```text theme={null}
{"ticker": "WMT", "date": "2024-11-29", "adj_close": 92.1, "volume": 12000000,
 "ret": 0.012, "vol_ratio": 1.4, "views": 6500.0, "event_type": "black_friday",
 "country": "US", "retailer_type": "store"}
```

Empty values (SPY's views, ordinary days' event\_type) are sent as null.

Testing late and out-of-order data (for the streaming job's watermark):

```text theme={null}
--late-fraction 0.02 --late-days 3
```

holds back about 2% of messages and sends them 3 trading days late. The choice
is random but repeatable (--seed), so the same test can be re-run.

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

## Source

```python title="src/producers/replay_master.py" lines expandable theme={null}
"""Replay clean/master.parquet into Kafka, one trading day at a time, as if the
past ten years were happening live.

Run on the course cluster:
    python3 src/producers/replay_master.py
Faster or slower:   --seconds-per-day 0.05   (2,514 trading days x 0.1 s = about 4 minutes)
Local Kafka:        --bootstrap localhost:9092   (or set KAFKA_BOOTSTRAP)

Each message is one row of the master table as JSON, keyed by ticker:
    {"ticker": "WMT", "date": "2024-11-29", "adj_close": 92.1, "volume": 12000000,
     "ret": 0.012, "vol_ratio": 1.4, "views": 6500.0, "event_type": "black_friday",
     "country": "US", "retailer_type": "store"}
Empty values (SPY's views, ordinary days' event_type) are sent as null.

Testing late and out-of-order data (for the streaming job's watermark):
    --late-fraction 0.02 --late-days 3
holds back about 2% of messages and sends them 3 trading days late. The choice
is random but repeatable (--seed), so the same test can be re-run.
"""
import argparse, json, random, time
from collections import defaultdict

import pandas as pd
from kafka import KafkaProducer

from common.contracts import KAFKA_TOPICS
from common.settings import KAFKA_BOOTSTRAP, clean_path

parser = argparse.ArgumentParser()
parser.add_argument('--bootstrap', default=KAFKA_BOOTSTRAP, help='comma-separated Kafka servers')
parser.add_argument('--topic', default=KAFKA_TOPICS['master'])
parser.add_argument('--input', default=str(clean_path('master')))
parser.add_argument('--seconds-per-day', type=float, default=0.1,
                    help='real seconds to wait between trading days')
parser.add_argument('--start', help='first date to replay, e.g. 2024-01-01 (default: all)')
parser.add_argument('--late-fraction', type=float, default=0.0)
parser.add_argument('--late-days', type=int, default=3)
parser.add_argument('--seed', type=int, default=732)
args = parser.parse_args()

df = pd.read_parquet(args.input)
df['date'] = pd.to_datetime(df['date']).dt.strftime('%Y-%m-%d')
if args.start:
    df = df[df['date'] >= args.start]
df = df.sort_values(['date', 'ticker'])
# NaN -> None so json.dumps writes null instead of NaN (NaN is not valid JSON)
records = df.astype(object).where(df.notna(), None).to_dict('records')

producer = KafkaProducer(
    bootstrap_servers=args.bootstrap.split(','),
    key_serializer=lambda k: k.encode('utf-8'),
    value_serializer=lambda v: json.dumps(v).encode('utf-8'),
)

rng = random.Random(args.seed)
by_day = defaultdict(list)
for r in records:
    by_day[r['date']].append(r)
days = sorted(by_day)

held_back = defaultdict(list)   # day index -> late messages to send on that day
sent = late = 0
for i, day in enumerate(days):
    batch = held_back.pop(i, [])            # late messages from earlier days go first
    for r in by_day[day]:
        if rng.random() < args.late_fraction:
            held_back[i + args.late_days].append(r)
            late += 1
        else:
            batch.append(r)
    for r in batch:
        producer.send(args.topic, key=r['ticker'], value=r)
    sent += len(batch)
    if i % 250 == 0:
        print(f'{day}: {sent} messages sent')
    time.sleep(args.seconds_per_day)

for msgs in held_back.values():            # anything still held at the very end
    for r in msgs:
        producer.send(args.topic, key=r['ticker'], value=r)
        sent += 1
producer.flush()
print(f'done: {sent} messages to {args.topic} ({late} sent late)')
```


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