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

# 5. The streaming job

> Spark Structured Streaming turns each day's rows into abnormal returns, attention spikes and event CARs.

This is the heart of the project. `job.py` is the Spark plumbing; `signals.py` is the logic for one stock, written in plain Python so it can be tested without Spark.

## The big idea

Each micro-batch:

1. **Parse** the messages with the `master` contract (rows that do not fit fail loudly: `FAILFAST`), and set **event time** to the trading day.
2. **Watermark** of 7 days: Spark may wait up to 7 days for late messages, then drops anything older, which also lets it forget old state.
3. **Join** each stock's row to SPY's row for the same day (a **stream-stream join**), to get the market return.
4. **Per ticker, with state** (`applyInPandasWithState`): `signals.update` holds rows until the watermark passes them (so days come out in order), re-fits the market model every day on the 120 days ending 10 days earlier, scores the abnormal return and the attention z-score, opens a window on each event's day 0 and closes it on day +5 with its CAR. The state (recent history, open windows) is kept as JSON between batches.
5. **Write** with `foreachBatch`: each micro-batch goes to its own `batch_id=N` folder, so a batch that is re-run after a crash overwrites itself instead of duplicating rows (**idempotent** output). If a trained model exists, it also scores tomorrow's big-move chance.

`scripts/check_streaming.py` then recomputes every daily value and CAR directly with numpy, with none of the streaming machinery, and checks they match.

## Words you will meet

> [accordion] Micro-batch
>
> A small slice of the stream that Spark processes as one batch job. Here, a few trading days' messages.

> [accordion] Watermark
>
> How late data may be. With 7 days, after Spark has seen day D, it drops messages for days before D − 7 and can discard state older than that.

> [accordion] Stateful processing
>
> Remembering things between micro-batches. `applyInPandasWithState` gives each ticker its own state and calls our function with that ticker's new rows.

> [accordion] Checkpoint
>
> Where Spark records its progress (offsets and state), so a restarted job continues where it stopped.

> [accordion] z-score
>
> How many standard deviations a value is from its usual level. `z_ar` is the abnormal return divided by its usual size; `z_views` is views against their recent mean.

### The picture: Inside the streaming job (src/streaming/job.py + signals.py)

```mermaid theme={null}
%% Calendar Effects · 5 of 8 · Inside the streaming job (src/streaming/job.py + signals.py) · Mahad, with Anushiya.
%% Paste into Miro: Creation bar > Diagram > Build with code.
flowchart TB
  topic[["Kafka topic or replay files"]]

  read["1 · READ · readStream<br/>a micro-batch = the messages that arrived since the last one<br/>--max-per-trigger 390 = 10 trading days × 39 stocks per batch"]
  parse["2 · PARSE · from_json with the master contract<br/>FAILFAST: a broken message stops the job<br/>instead of silently becoming empty"]
  time["3 · EVENT TIME · timestamp_utc = the trading day at 00:00 UTC<br/>the time the data is ABOUT, not when it arrived"]
  wm["4 · WATERMARK · 7 days<br/>the job's sense of how late a message may be<br/>newest date seen − 7 days; anything older is dropped<br/>and counted by DropCounter"]
  split["5 · SPLIT · SPY rows vs stock rows"]
  joinspy["6 · STREAM-STREAM JOIN<br/>each stock row + SPY's row for the same day<br/>gives mkt_ret, the market's return"]
  group["7 · groupBy ticker + applyInPandasWithState<br/>one call per stock per micro-batch<br/>STATE = that stock's memory, kept between batches<br/>as a JSON string in the checkpoint"]

  subgraph SIGNALS["8 · src/streaming/signals.py · update(), plain Python, tested without Spark"]
    pending["pending · rows wait until the watermark passes their date<br/>so they come out in date order even if they arrived out of order"]
    daily["DAILY ALERT · market model re-fitted every day<br/>OLS on the 120 trading days ending 10 days earlier<br/>ret = alpha + beta × mkt_ret + error<br/>AR, abnormal return = ret − alpha − beta × mkt_ret<br/>z_ar = AR / ar_sd · abnormal_return = 1 if |z_ar| ≥ 1.96"]
    attn["ATTENTION · z_views = views vs the mean and spread<br/>of a 28-trading-day baseline, same 10-day gap<br/>attention_spike = 1 if z_views ≥ 3"]
    window["EVENT WINDOW · opens on day 0<br/>day 0 = first trading day on or after the event date<br/>fits ONE market model on days −125..−6<br/>takes days −5..−1 from history, collects days 0..+5"]
    closewin["on day +5 · CAR = sum of the 11 ARs under that one model<br/>car_z = CAR / (ar_sd × √n_days)<br/>also n_abnormal_days, max_z_views, n_spike_days"]
  end

  timeout["EventTimeTimeout<br/>wakes a stock up when the watermark moves<br/>even if no new rows came for it"]

  sink["9 · WRITE · foreachBatch<br/>each micro-batch to its own batch_id=N folder<br/>overwritten if Spark retries, so results never double<br/>prints alerts and CARs as they happen"]
  out1[("data/stream/signals<br/>one row per stock per day<br/>ret, mkt_ret, alpha, beta, ar, z_ar, abnormal_return,<br/>views, z_views, attention_spike, event_type")]
  out2[("data/stream/event_car<br/>one row per stock per event occurrence<br/>alpha, beta, ar_sd, car, car_z, n_days,<br/>n_abnormal_days, max_z_views, n_spike_days")]
  ckpt[/"checkpoint folder<br/>Kafka offsets + state, so a restart<br/>continues where it stopped"/]

  topic --> read --> parse --> time --> wm --> split --> joinspy --> group --> pending
  pending --> daily
  pending --> attn
  pending --> window --> closewin
  timeout -.-> group
  daily --> sink
  attn --> sink
  closewin --> sink
  sink --> out1
  sink --> out2
  group -.-> ckpt
```

The [full diagram and its guide](https://calendar-effects.mintlify.site/diagrams/05-streaming-job.md) explain every box.

### Read these files in this order

**1. src/streaming/**init**.py**

See the file. [Read it](https://calendar-effects.mintlify.site/reference/src/streaming/init.md)

**2. src/streaming/job.py**

Structured Streaming job: flag abnormal returns and attention spikes as the master table is replayed, and compute each event's CAR the moment its window closes. [Read it](https://calendar-effects.mintlify.site/reference/src/streaming/job.md)

**3. src/streaming/signals.py**

Per-ticker logic of the streaming job, in plain Python so it can be tested without Spark. src/streaming/job.py calls `update` once per ticker per micro-batch (through applyInPandasWithState) and keeps the returned state until the next batch. [Read it](https://calendar-effects.mintlify.site/reference/src/streaming/signals.md)

**4. scripts/check\_streaming.py**

Check the streaming job's output against a direct computation of the same numbers. [Read it](https://calendar-effects.mintlify.site/reference/scripts/check_streaming.md)

## Questions you should be able to answer

> [accordion] Why not just compute everything at the end?
>
> Because the point is to know as soon as the data arrives: an alert on the day it happens, a CAR on the day its window closes. The batch study does the "at the end" version, and the two must agree.

> [accordion] Why hold rows until the watermark passes?
>
> The rolling market model needs days in order. Late messages can arrive after later days; holding each row until the watermark guarantees nothing earlier can still come, so rows are released in date order.

> [accordion] What makes the output safe to re-run?
>
> Each micro-batch writes its own `batch_id=N` folder and replaces it if the batch runs again, and the checkpoint records which batches finished. Readers (the dashboard) only read folders with Spark's `_SUCCESS` marker.

> [accordion] Where does the model run?
>
> Inside the JVM: the saved MLlib pipeline transforms each micro-batch's rows, so no Python is needed on the workers for scoring.

## Ideas to improve it

* Replace the per-ticker pandas state with `transformWithState` (Spark 4) for typed state and timers.
* Stream intraday prices: the same logic with minutes instead of days.


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