Skip to main content
src/streaming/signals.py · chapter The streaming job, file 3 · 238 lines · open in the repository

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
  • POST_DAYS · line 40
  • HISTORY_DAYS · line 43: 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
  • _num(x) · line 59: A float, or None when missing (pandas hands nulls over as NaN).
  • _iso(d) · line 67: ISO date string from a date, datetime, pandas Timestamp or string.
  • _clean(row) · line 72
  • fit_market_model(pairs) · line 84: OLS of stock returns on market returns. pairs is [(ret, mkt_ret)], both present.
  • _fit_on(days) · line 105: fit_market_model on history entries, skipping days without both returns.
  • _zscore(value, baseline) · line 111
  • _flag(z, threshold, two_sided) · line 119
  • _close_window(ticker, window) · line 125
  • _process_day(state, ticker, row, events, daily, cars) · line 153
  • update(state, ticker, rows, watermark, events) · line 215: 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, src/common/study.py

Source

src/streaming/signals.py