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

> Replay clean/master.parquet into a folder of JSON-lines files, for running the streaming job on a laptop without Kafka.

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

## What it does

Replay clean/master.parquet into a folder of JSON-lines files, for running the
streaming job on a laptop without Kafka.

Same messages and the same late-data option as replay\_master.py (one JSON object per
row, null for empty values), but instead of sending to Kafka it writes one file per
\--days-per-file trading days. The job reads one file per micro-batch, so a message
held back into a later file really does arrive late.

Run from anywhere:

```bash theme={null}
python3 src/producers/replay_to_files.py                      (in order)
python3 src/producers/replay_to_files.py --late-fraction 0.02 --late-days 3
```

then:

```bash theme={null}
python3 src/streaming/job.py --source files --once --fresh
```

## Connections

**Uses:** [`src/common/settings.py`](https://calendar-effects.mintlify.site/reference/src/common/settings)

## Source

```python title="src/producers/replay_to_files.py" lines expandable theme={null}
"""Replay clean/master.parquet into a folder of JSON-lines files, for running the
streaming job on a laptop without Kafka.

Same messages and the same late-data option as replay_master.py (one JSON object per
row, null for empty values), but instead of sending to Kafka it writes one file per
--days-per-file trading days. The job reads one file per micro-batch, so a message
held back into a later file really does arrive late.

Run from anywhere:
    python3 src/producers/replay_to_files.py                      (in order)
    python3 src/producers/replay_to_files.py --late-fraction 0.02 --late-days 3
then:
    python3 src/streaming/job.py --source files --once --fresh
"""
import argparse, json, os, random, shutil, time
from collections import defaultdict
from pathlib import Path

import pandas as pd

from common.settings import REPLAY_DIR, clean_path

parser = argparse.ArgumentParser()
parser.add_argument('--input', default=str(clean_path('master')))
parser.add_argument('--out', default=str(REPLAY_DIR))
parser.add_argument('--days-per-file', type=int, default=5)
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')

by_day = defaultdict(list)
for r in records:
    by_day[r['date']].append(r)
days = sorted(by_day)

# Same choice of late messages as replay_master.py for the same --seed.
rng = random.Random(args.seed)
send_on = defaultdict(list)   # day index -> messages sent that day
late = 0
for i, day in enumerate(days):
    for r in by_day[day]:
        if rng.random() < args.late_fraction:
            send_on[min(i + args.late_days, len(days) - 1)].append(r)
            late += 1
        else:
            send_on[i].append(r)

out = Path(args.out)
shutil.rmtree(out, ignore_errors=True)
out.mkdir(parents=True)
files = 0
first_mtime = time.time() - len(days)
for start in range(0, len(days), args.days_per_file):
    batch = [r for i in range(start, min(start + args.days_per_file, len(days))) for r in send_on[i]]
    path = out / f'{files:05d}.json'
    with open(path, 'w') as f:
        for r in batch:
            f.write(json.dumps(r) + '\n')
    # Spark's file source reads files oldest-modified first, not by name, so give each
    # file its own second; files written in the same instant would come in any order.
    os.utime(path, (first_mtime + files, first_mtime + files))
    files += 1
print(f'{len(records)} messages in {files} files under {out} ({late} sent late)')
```


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