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

`src/streaming/signals.py` · chapter [The streaming job](https://calendar-effects.mintlify.site/tour/05-streaming.md), file 3 · 238 lines · [open in the repository](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/signals.py)

## What it does

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.

What happens to each row (one ticker, one trading day):

1. It waits in `pending` until the watermark passes its date. Rows can arrive late and
   out of order, but Spark drops anything behind the watermark, so rows released this
   way come out in date order, which a rolling baseline needs.
2. Daily alert: a market model (alpha and beta by OLS) on the ESTIMATION\_DAYS trading days
   that end ESTIMATION\_GAP\_DAYS before this day, re-fitted every day.
   Abnormal return (AR) = ret - (alpha + beta \* mkt\_ret).
3. Attention: that day's views against the mean and spread of a baseline with the same gap.
4. Events: when a calendar event's date is reached (day 0), a window opens. It fits one
   market model on the ESTIMATION\_DAYS days before the window (days -125..-6), exactly as
   the batch study does, takes days -5..-1 from history and collects days 0..+5. On day +5
   its CAR, the sum of the window's ARs under that one model, is emitted.

The state is a plain dict that json.dumps can store, because Spark keeps it between
batches as a string. Dates are ISO strings (YYYY-MM-DD) throughout, so they compare
correctly as text.

## What is inside

* **`PRE_DAYS`** · [line 39](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/signals.py#L39)
* **`POST_DAYS`** · [line 40](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/signals.py#L40)
* **`HISTORY_DAYS`** · [line 43](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/signals.py#L43): Processed days kept per ticker: the estimation window plus the gap (daily model) or plus the pre-event days (event model), whichever is longer.
* **`new_state()`** · [line 49](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/signals.py#L49)
* **`_num(x)`** · [line 59](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/signals.py#L59): A float, or None when missing (pandas hands nulls over as NaN).
* **`_iso(d)`** · [line 67](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/signals.py#L67): ISO date string from a date, datetime, pandas Timestamp or string.
* **`_clean(row)`** · [line 72](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/signals.py#L72)
* **`fit_market_model(pairs)`** · [line 84](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/signals.py#L84): OLS of stock returns on market returns. `pairs` is \[(ret, mkt\_ret)], both present.
* **`_fit_on(days)`** · [line 105](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/signals.py#L105): fit\_market\_model on history entries, skipping days without both returns.
* **`_zscore(value, baseline)`** · [line 111](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/signals.py#L111)
* **`_flag(z, threshold, two_sided)`** · [line 119](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/signals.py#L119)
* **`_close_window(ticker, window)`** · [line 125](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/signals.py#L125)
* **`_process_day(state, ticker, row, events, daily, cars)`** · [line 153](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/signals.py#L153)
* **`update(state, ticker, rows, watermark, events)`** · [line 215](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/streaming/signals.py#L215): Add one micro-batch of rows for `ticker`, then process every waiting row the watermark has passed, oldest first.

## Connections

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

## Source

```python title="src/streaming/signals.py" lines expandable theme={null}
"""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.

What happens to each row (one ticker, one trading day):

1. It waits in `pending` until the watermark passes its date. Rows can arrive late and
   out of order, but Spark drops anything behind the watermark, so rows released this
   way come out in date order, which a rolling baseline needs.
2. Daily alert: a market model (alpha and beta by OLS) on the ESTIMATION_DAYS trading days
   that end ESTIMATION_GAP_DAYS before this day, re-fitted every day.
   Abnormal return (AR) = ret - (alpha + beta * mkt_ret).
3. Attention: that day's views against the mean and spread of a baseline with the same gap.
4. Events: when a calendar event's date is reached (day 0), a window opens. It fits one
   market model on the ESTIMATION_DAYS days before the window (days -125..-6), exactly as
   the batch study does, takes days -5..-1 from history and collects days 0..+5. On day +5
   its CAR, the sum of the window's ARs under that one model, is emitted.

The state is a plain dict that json.dumps can store, because Spark keeps it between
batches as a string. Dates are ISO strings (YYYY-MM-DD) throughout, so they compare
correctly as text.
"""
from __future__ import annotations

import math

from common.contracts import MARKET_WIDE_TICKER
from common.study import (
    ABNORMAL_RETURN_Z,
    ATTENTION_BASELINE_DAYS,
    ATTENTION_SPIKE_Z,
    ESTIMATION_DAYS,
    ESTIMATION_GAP_DAYS,
    EVENT_WINDOW,
    MIN_ATTENTION_DAYS,
    MIN_ESTIMATION_DAYS,
)

PRE_DAYS = -EVENT_WINDOW[0]
POST_DAYS = EVENT_WINDOW[1]
# Processed days kept per ticker: the estimation window plus the gap (daily model)
# or plus the pre-event days (event model), whichever is longer.
HISTORY_DAYS = ESTIMATION_DAYS + max(ESTIMATION_GAP_DAYS, PRE_DAYS)

# Positions in a history entry.
DATE, RET, MKT_RET, VIEWS, Z_VIEWS = range(5)


def new_state() -> dict:
    return {
        "last_date": None,   # newest processed trading day
        "history": [],       # processed days, oldest first: [date, ret, mkt_ret, views, z_views]
        "pending": [],       # rows waiting for the watermark, in date order
        "open_windows": [],  # event windows that have not reached day +5 yet
        "skipped": 0,        # rows for a day already processed or already waiting (duplicates)
    }


def _num(x):
    """A float, or None when missing (pandas hands nulls over as NaN)."""
    if x is None:
        return None
    x = float(x)
    return None if math.isnan(x) else x


def _iso(d) -> str:
    """ISO date string from a date, datetime, pandas Timestamp or string."""
    return d if isinstance(d, str) else d.isoformat()[:10]


def _clean(row: dict) -> dict:
    event_type = row.get("event_type")
    return {
        "date": _iso(row["date"]),
        "ret": _num(row.get("ret")),
        "mkt_ret": _num(row.get("mkt_ret")),
        "views": _num(row.get("views")),
        "vol_ratio": _num(row.get("vol_ratio")),
        "event_type": event_type if isinstance(event_type, str) else None,
    }


def fit_market_model(pairs):
    """OLS of stock returns on market returns. `pairs` is [(ret, mkt_ret)], both present.

    Returns (alpha, beta, residual standard deviation, number of days), or None when
    there are fewer than MIN_ESTIMATION_DAYS days or the market never moved.
    """
    n = len(pairs)
    if n < MIN_ESTIMATION_DAYS:
        return None
    mean_r = sum(r for r, _ in pairs) / n
    mean_m = sum(m for _, m in pairs) / n
    sxx = sum((m - mean_m) ** 2 for _, m in pairs)
    if sxx == 0:
        return None
    beta = sum((m - mean_m) * (r - mean_r) for r, m in pairs) / sxx
    alpha = mean_r - beta * mean_m
    sse = sum((r - alpha - beta * m) ** 2 for r, m in pairs)
    # n - 2 because two parameters (alpha, beta) were fitted
    return alpha, beta, math.sqrt(sse / (n - 2)), n


def _fit_on(days):
    """fit_market_model on history entries, skipping days without both returns."""
    return fit_market_model([(h[RET], h[MKT_RET]) for h in days
                             if h[RET] is not None and h[MKT_RET] is not None])


def _zscore(value, baseline):
    if value is None or len(baseline) < MIN_ATTENTION_DAYS:
        return None
    mean = sum(baseline) / len(baseline)
    sd = math.sqrt(sum((b - mean) ** 2 for b in baseline) / (len(baseline) - 1))
    return (value - mean) / sd if sd > 0 else None


def _flag(z, threshold, two_sided):
    if z is None:
        return None
    return int((abs(z) if two_sided else z) >= threshold)


def _close_window(ticker: str, window: dict) -> dict:
    days = window["days"]  # [ret, mkt_ret, z_views] for days -5..+5
    alpha, beta, sd = window["alpha"], window["beta"], window["ar_sd"]
    ars = []
    if alpha is not None:
        ars = [ret - (alpha + beta * mkt) for ret, mkt, _ in days if ret is not None and mkt is not None]
    car = sum(ars) if ars else None
    z_views = [d[2] for d in days if d[2] is not None]
    return {
        "ticker": ticker,
        "event_type": window["event_type"],
        "event_date": window["event_date"],
        "event_end_date": window["event_end_date"],
        "day0_date": window["day0_date"],
        "alpha": alpha,
        "beta": beta,
        "ar_sd": sd,
        "estimation_days": window["estimation_days"],
        "car": car,
        # Under the market model each AR has spread sd, so a sum of n of them has sd * sqrt(n).
        "car_z": car / (sd * math.sqrt(len(ars))) if car is not None and sd else None,
        "n_days": len(ars),
        "n_abnormal_days": sum(1 for ar in ars if sd and abs(ar / sd) >= ABNORMAL_RETURN_Z),
        "max_z_views": max(z_views) if z_views else None,
        "n_spike_days": sum(1 for z in z_views if z >= ATTENTION_SPIKE_Z),
    }


def _process_day(state: dict, ticker: str, row: dict, events: list[dict], daily: list, cars: list):
    day = row["date"]
    history = state["history"]

    # Baseline: the ESTIMATION_DAYS processed days that end ESTIMATION_GAP_DAYS before today.
    end = max(0, len(history) - ESTIMATION_GAP_DAYS)
    baseline = history[max(0, end - ESTIMATION_DAYS):end]

    model = _fit_on(baseline)
    alpha = beta = sd = ar = z_ar = None
    n_est = 0
    if model:
        alpha, beta, sd, n_est = model
        if row["ret"] is not None and row["mkt_ret"] is not None:
            ar = row["ret"] - (alpha + beta * row["mkt_ret"])
            z_ar = ar / sd if sd > 0 else None
    z_views = _zscore(row["views"], [h[VIEWS] for h in baseline[-ATTENTION_BASELINE_DAYS:]
                                     if h[VIEWS] is not None])

    daily.append({
        "ticker": ticker, "date": day, "ret": row["ret"], "mkt_ret": row["mkt_ret"],
        "alpha": alpha, "beta": beta, "ar": ar, "ar_sd": sd, "z_ar": z_ar,
        "abnormal_return": _flag(z_ar, ABNORMAL_RETURN_Z, True),
        "views": row["views"], "z_views": z_views,
        "attention_spike": _flag(z_views, ATTENTION_SPIKE_Z, False),
        "vol_ratio": row["vol_ratio"], "event_type": row["event_type"], "estimation_days": n_est,
    })

    # Events whose date falls after the previous trading day and on or before today
    # start today (day 0); this moves weekend and holiday events to the next open day.
    prev = state["last_date"]
    for e in events:
        if e["ticker"] not in (MARKET_WIDE_TICKER, ticker):
            continue
        if (e["event_date"] == day) if prev is None else (prev < e["event_date"] <= day):
            # One model for the whole window, fitted on the days just before day -5.
            est_end = max(0, len(history) - PRE_DAYS)
            e_alpha, e_beta, e_sd, e_n = (_fit_on(history[max(0, est_end - ESTIMATION_DAYS):est_end])
                                          or (None, None, None, 0))
            state["open_windows"].append({
                "event_type": e["event_type"], "event_date": e["event_date"],
                "event_end_date": e["event_end_date"], "day0_date": day,
                "alpha": e_alpha, "beta": e_beta, "ar_sd": e_sd, "estimation_days": e_n,
                "days": [[h[RET], h[MKT_RET], h[Z_VIEWS]] for h in history[-PRE_DAYS:]],
                "post_days": -1,
            })

    still_open = []
    for w in state["open_windows"]:
        w["days"].append([row["ret"], row["mkt_ret"], z_views])
        w["post_days"] += 1
        if w["post_days"] == POST_DAYS:
            cars.append(_close_window(ticker, w))
        else:
            still_open.append(w)
    state["open_windows"] = still_open

    history.append([day, row["ret"], row["mkt_ret"], row["views"], z_views])
    del history[:-HISTORY_DAYS]
    state["last_date"] = day


def update(state: dict, ticker: str, rows: list[dict], watermark: str | None, events: list[dict]):
    """Add one micro-batch of rows for `ticker`, then process every waiting row the
    watermark has passed, oldest first.

    `watermark` is an ISO date, or None before Spark has one. `events` are rows of the
    events table with ISO-string dates. Changes `state` in place and returns
    (daily signal rows, event-window CAR rows).
    """
    pending = {r["date"]: r for r in state["pending"]}
    for raw in rows:
        row = _clean(raw)
        day = row["date"]
        if day in pending or (state["last_date"] is not None and day <= state["last_date"]):
            state["skipped"] += 1
            continue
        pending[day] = row

    daily, cars = [], []
    for day in sorted(pending):
        if watermark is None or day > watermark:
            break
        _process_day(state, ticker, pending.pop(day), events, daily, cars)
    state["pending"] = [pending[d] for d in sorted(pending)]
    return daily, cars
```


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