"""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.
Pipeline (one micro-batch at a time):
Kafka topic (or a folder of JSON files) one message per ticker per trading day
-> parse with the `master` contract, event time = trading day at 00:00 UTC
-> watermark of WATERMARK_DELAY
-> join each stock row to SPY's row for the same day (stream-stream join) for mkt_ret
-> per ticker, applyInPandasWithState runs streaming/signals.py: daily alerts from a
rolling market model and attention z-score; event windows from the calendar, each
with one market model fitted before the window, as in the batch study
-> foreachBatch writes data/stream/signals/ and data/stream/event_car/ and prints alerts
-> if a trained big-move model exists (src/ml/train.py, decision 0007), it scores each
day's rows and writes data/stream/predictions/: the chance of a big move tomorrow
-> with --publish-live, each finished batch also goes to the hosted dashboard's live feed
(decision 0013, src/hosting/live.py)
Run locally on files (make them first with src/producers/replay_to_files.py):
python3 src/streaming/job.py --source files --once --fresh
Run on the cluster against Kafka while replay_master.py is sending (the course cluster
runs Spark 3.5.8 with Scala 2.13 on YARN; `spark-submit --version` shows yours):
PYTHONPATH=src spark-submit --packages org.apache.spark:spark-sql-kafka-0-10_2.13:3.5.8 \\
src/streaming/job.py --source kafka --out calendar-effects/stream \\
--checkpoint calendar-effects/checkpoint
spark-submit starts Spark before this script runs, so the Kafka connector must be on its
command line (--packages); the script's own --kafka-package only applies when the job is
started with python3, as on a laptop. On YARN, --out and --checkpoint are HDFS paths
(relative ones land in your HDFS home), and --fresh does not clear them: use
`hdfs dfs -rm -r` instead.
"""
import argparse, json, os, shutil, signal, sys, tempfile, threading, time, zipfile
from datetime import date, datetime, timezone
from pathlib import Path
SRC = Path(__file__).resolve().parents[1]
# spark-submit on the cluster may run without `pip install -e .`
sys.path.insert(0, str(SRC))
# Spark's pandas code reads the local time zone from TZ; without it, it falls back to
# dateutil and crashes. Our data is all UTC anyway. Set before Spark starts.
os.environ["TZ"] = "UTC"
time.tzset()
import json
import pandas as pd
import pyspark
from pyspark.sql import SparkSession, functions as F
from pyspark.sql.streaming import StreamingQueryListener
from pyspark.sql.streaming.state import GroupStateTimeout
from common.contracts import KAFKA_TOPICS, expand_events, spark_schema
from common.settings import (BIG_MOVE_MODEL, BIG_MOVE_MODEL_INFO, CHECKPOINT_DIR, KAFKA_BOOTSTRAP,
REPLAY_DIR, STREAM_DIR, STREAM_SUBDIRS)
from common.study import MARKET_TICKER, STUDY_END_YEAR, STUDY_START_YEAR
from ml.features import add_features, calendar_table, retailer_table
from streaming import signals
# How far behind the newest trading day a message may arrive and still be used.
# replay_master.py's late test sends messages 3 trading days late; around weekends
# and holidays that is up to 6 calendar days, so 7 days keeps them all. Spark only
# promises one direction: anything newer than the watermark is kept, anything older
# may be dropped (and then counted as "dropped by watermark"). Decision 0004.
WATERMARK_DELAY = "7 days"
STATE_SCHEMA = "state_json string"
# applyInPandasWithState has one output schema, so daily signals and CAR rows share it;
# `kind` says which is which and foreachBatch splits them.
OUTPUT_FIELDS = {"kind": "string",
**{f.name: f.dataType.simpleString() for f in spark_schema("stream_signals").fields},
**{f.name: f.dataType.simpleString() for f in spark_schema("stream_event_car").fields}}
OUTPUT_FIELDS.pop("timestamp_utc")
OUTPUT_SCHEMA = ", ".join(f"{name} {kind}" for name, kind in OUTPUT_FIELDS.items())
parser = argparse.ArgumentParser()
parser.add_argument("--source", choices=["kafka", "files"], default="kafka")
parser.add_argument("--bootstrap", default=KAFKA_BOOTSTRAP, help="comma-separated Kafka servers")
parser.add_argument("--topic", default=KAFKA_TOPICS["master"])
parser.add_argument("--max-per-trigger", type=int,
help="Kafka messages per micro-batch (one message per ticker per trading day)")
parser.add_argument("--input-dir", default=str(REPLAY_DIR), help="JSON files for --source files")
parser.add_argument("--out", default=str(STREAM_DIR))
parser.add_argument("--checkpoint", default=str(CHECKPOINT_DIR / "streaming-signals"))
parser.add_argument("--trigger", default="5 seconds", help="time between micro-batches")
parser.add_argument("--once", action="store_true",
help="process everything available, then stop (for tests)")
parser.add_argument("--fresh", action="store_true",
help="delete this query's checkpoint and output first, to start over")
parser.add_argument("--partitions", type=int, default=4,
help="shuffle partitions; Spark's default of 200 is far too many for 10 tickers")
parser.add_argument("--kafka-package")
parser.add_argument("--model", default=str(BIG_MOVE_MODEL),
help="trained big-move model (src/ml/train.py); skipped if the folder is missing")
parser.add_argument("--no-model", action="store_true", help="do not score the big-move model")
parser.add_argument("--publish-live", action="store_true",
help="also publish each finished micro-batch to the hosted dashboard's live feed "
"(src/hosting/live.py, decision 0013); needs a Hugging Face login with write access")
parser.add_argument("--publish-every", type=float, default=15.0, help="seconds between live-feed uploads")
parser.add_argument("--stop-when-idle", type=float, default=0, metavar="SECONDS",
help="stop once no new data has come for this long (a replay has run out); 0: never")
args = parser.parse_args()
if args.fresh:
for path in (args.checkpoint, args.out):
shutil.rmtree(path, ignore_errors=True)
# Workers must run the same Python as this driver (the project .venv has pyarrow).
os.environ.setdefault("PYSPARK_PYTHON", sys.executable)
builder = (SparkSession.builder.appName("calendar-effects-streaming")
.config("spark.sql.session.timeZone", "UTC")
.config("spark.executorEnv.TZ", "UTC")
.config("spark.sql.shuffle.partitions", args.partitions))
if args.source == "kafka":
scala = "2.13" if int(pyspark.__version__.split(".")[0]) >= 4 else "2.12"
builder = builder.config("spark.jars.packages", args.kafka_package or
f"org.apache.spark:spark-sql-kafka-0-10_{scala}:{pyspark.__version__}")
spark = builder.getOrCreate()
spark.sparkContext.setLogLevel("WARN")
# Workers import streaming.signals and common.study by name, so ship both packages
# as a zip; this works the same in local mode and on the cluster.
zip_path = os.path.join(tempfile.mkdtemp(), "calendar_effects_src.zip")
with zipfile.ZipFile(zip_path, "w") as z:
for package in ("common", "streaming"):
for file in (SRC / package).glob("*.py"):
z.write(file, f"{package}/{file.name}")
spark.sparkContext.addPyFile(zip_path)
# Events come from the shared calendar, not from master's event_type column, so events
# on weekends and market holidays still get a window (signals.py moves them to day 0).
EVENTS = [{**e, "event_date": e["event_date"].isoformat(), "event_end_date": e["event_end_date"].isoformat()}
for e in expand_events(STUDY_START_YEAR, STUDY_END_YEAR)]
# The big-move model (decision 0007), loaded once. It scores each micro-batch's daily rows
# with the same features it was trained on (ml.features), entirely in Spark's JVM, so the
# workers need no extra Python code.
MODEL = None
if not args.no_model and Path(args.model).exists() and BIG_MOVE_MODEL_INFO.exists():
from pyspark.ml import PipelineModel
from pyspark.ml.functions import vector_to_array
MODEL = PipelineModel.load(args.model)
MODEL_CUTOFF = json.loads(BIG_MOVE_MODEL_INFO.read_text())["alert_cutoff"]
CALENDAR = spark.createDataFrame(calendar_table()).cache() # add_features broadcasts it
RETAILERS = spark.createDataFrame(retailer_table()).cache()
print(f"big-move model loaded from {args.model}; alert when p >= {MODEL_CUTOFF:.4f}")
else:
print("no big-move model: run src/ml/train.py to add live predictions")
# --- source ---------------------------------------------------------------
# FAILFAST stops the job on a message that breaks the master contract; Spark's default
# would quietly turn a wrongly typed field into null. Spark only parses the fields the
# job uses, so a bad `volume` or `adj_close` is not caught here.
schema = spark_schema("master")
if args.source == "kafka":
reader = (spark.readStream.format("kafka")
.option("kafka.bootstrap.servers", args.bootstrap)
.option("subscribe", args.topic)
.option("startingOffsets", "earliest"))
if args.max_per_trigger:
reader = reader.option("maxOffsetsPerTrigger", args.max_per_trigger)
messages = (reader.load()
.select(F.from_json(F.col("value").cast("string"), schema, {"mode": "FAILFAST"}).alias("m"))
.select("m.*"))
else:
# One file per micro-batch, so late rows in later files really arrive late.
messages = (spark.readStream.schema(schema).option("mode", "FAILFAST")
.option("maxFilesPerTrigger", 1).json(args.input_dir))
# Event time: daily bars have no clock time, so each trading day is 00:00 UTC.
messages = (messages
.withColumn("timestamp_utc", F.col("date").cast("timestamp"))
.withWatermark("timestamp_utc", WATERMARK_DELAY))
# --- market return: stream-stream join of each stock row to SPY's row for that day ---
# Joining on the watermarked event time lets Spark drop a day's join state once the
# watermark has passed it. Spark 4 allows one event-time column after the join, so
# the market side's copy is dropped.
stocks = messages.filter(F.col("ticker") != MARKET_TICKER)
market = messages.filter(F.col("ticker") == MARKET_TICKER).select(
F.col("timestamp_utc").alias("market_ts"), F.col("ret").alias("mkt_ret"))
joined = (stocks.join(market, F.expr("timestamp_utc = market_ts"))
.drop("market_ts")
.select("ticker", "date", "timestamp_utc", "ret", "mkt_ret", "views", "vol_ratio", "event_type"))
# --- per-ticker state ------------------------------------------------------
def run_ticker(key, batches, state):
"""Called by Spark for one ticker per micro-batch, or when its timeout fires."""
ticker = key[0]
st = json.loads(state.get[0]) if state.exists else signals.new_state()
rows = [r for batch in batches for r in batch.to_dict("records")]
watermark_ms = state.getCurrentWatermarkMs()
watermark = (datetime.fromtimestamp(watermark_ms / 1000, tz=timezone.utc).date().isoformat()
if watermark_ms > 0 else None)
daily, cars = signals.update(st, ticker, rows, watermark, EVENTS)
state.update((json.dumps(st),))
if st["pending"]:
# Wake this ticker up once the watermark passes its newest waiting row, even if
# no new rows come for it (other tickers can still move the watermark).
newest = datetime.fromisoformat(st["pending"][-1]["date"]).replace(tzinfo=timezone.utc)
state.setTimeoutTimestamp(int(newest.timestamp() * 1000))
out = [{"kind": "daily", **r} for r in daily] + [{"kind": "car", **r} for r in cars]
if out:
pdf = pd.DataFrame(out, columns=list(OUTPUT_FIELDS))
for name, kind in OUTPUT_FIELDS.items():
if kind == "date":
pdf[name] = [date.fromisoformat(d) if isinstance(d, str) else None for d in pdf[name]]
elif kind == "int":
pdf[name] = pdf[name].astype("Int32")
yield pdf
results = joined.groupBy("ticker").applyInPandasWithState(
run_ticker, OUTPUT_SCHEMA, STATE_SCHEMA, "append", GroupStateTimeout.EventTimeTimeout)
# --- sinks ---------------------------------------------------------------
class DropCounter(StreamingQueryListener):
"""Adds up rows that arrived behind the watermark and were dropped."""
dropped = 0
def onQueryStarted(self, event): pass
def onQueryIdle(self, event): pass
def onQueryTerminated(self, event): pass
def onQueryProgress(self, event):
DropCounter.dropped += sum(op.numRowsDroppedByWatermark for op in event.progress.stateOperators)
def write_batch(batch, batch_id):
"""Split one micro-batch into the two outputs. Each batch gets its own folder and
overwrites it, so if Spark retries a batch after a crash the result is the same."""
batch.persist()
daily = (batch.filter("kind = 'daily'")
.withColumn("timestamp_utc", F.col("date").cast("timestamp"))
.select([F.col(f.name).cast(f.dataType) for f in spark_schema("stream_signals").fields]))
cars = (batch.filter("kind = 'car'")
.select([F.col(f.name).cast(f.dataType) for f in spark_schema("stream_event_car").fields]))
for df, dataset in ((daily, "stream_signals"), (cars, "stream_event_car")):
if not df.isEmpty():
df.write.mode("overwrite").parquet(f"{args.out}/{STREAM_SUBDIRS[dataset]}/batch_id={batch_id}")
summary = daily.agg(F.min("date"), F.max("date"), F.count("*"),
F.sum("abnormal_return"), F.sum("attention_spike")).first()
if summary[2]:
LAST_DATA[0] = time.time()
print(f"batch {batch_id}: {summary[0]} to {summary[1]}, {summary[2]} rows, "
f"{summary[3] or 0} abnormal returns, {summary[4] or 0} attention spikes, "
f"{DropCounter.dropped} late rows dropped so far")
if not cars.isEmpty():
cars.select("ticker", "event_type", "day0_date", F.round("car", 4).alias("car"),
F.round("car_z", 2).alias("car_z"), "n_abnormal_days", "n_spike_days").show(50, False)
if MODEL is not None and not daily.isEmpty():
preds = (MODEL.transform(add_features(daily, CALENDAR, RETAILERS))
.withColumn("p_big_move_next", vector_to_array("probability")[1])
.withColumn("big_move_alert", (F.col("p_big_move_next") >= MODEL_CUTOFF).cast("int"))
.select([F.col(f.name).cast(f.dataType) for f in spark_schema("stream_predictions").fields]))
preds.write.mode("overwrite").parquet(
f"{args.out}/{STREAM_SUBDIRS['stream_predictions']}/batch_id={batch_id}")
flagged = preds.filter("big_move_alert = 1").orderBy(F.desc("p_big_move_next")).limit(5).collect()
if flagged:
print(" big move likely tomorrow: " + ", ".join(
f"{r['ticker']} ({r['date']}, p={r['p_big_move_next']:.2f})" for r in flagged))
batch.unpersist()
if LIVE is not None:
LIVE.add(batch_id)
# The hosted dashboard's live feed (decision 0013), only with --publish-live: finished batches are
# uploaded in the background. It checks first that this computer can publish (signed in to Hugging
# Face with write access, writing to a local folder rather than HDFS) and stops with the reason if not.
LIVE = None
if args.publish_live:
local = spark.sparkContext.master.startswith("local") and "://" not in args.out
if local:
from hosting.live import LivePublisher, publish_check
can, why = publish_check()
else:
can, why = False, "this run writes to the cluster's HDFS, not a local folder"
if not can:
raise SystemExit(f"--publish-live: cannot publish, because {why}")
# Without --fresh, a restarted job carries on the run it was publishing.
LIVE = LivePublisher(args.out, every=args.publish_every, resume=not args.fresh)
listener = DropCounter()
spark.streams.addListener(listener)
writer = (results.writeStream
.foreachBatch(write_batch)
.option("checkpointLocation", args.checkpoint)
.queryName("streaming-signals"))
writer = writer.trigger(availableNow=True) if args.once else writer.trigger(processingTime=args.trigger)
# Ctrl-C ends a run cleanly. PySpark's own Ctrl-C handler calls into the JVM from inside the
# signal, which collides with the call waiting on the query and fails with py4j errors; this one
# only sets a flag, and the loop below stops the query.
# SIGTERM too: GitHub Actions sends it when Ctrl-C has not ended a cancelled run quickly enough.
STOP = threading.Event()
for sig in (signal.SIGINT, signal.SIGTERM):
signal.signal(sig, lambda *_: STOP.set())
LAST_DATA = [time.time()] # when the last micro-batch with rows came (or the start)
ran_out = False
query = writer.start()
try:
while query.isActive and not STOP.is_set() and not ran_out:
query.awaitTermination(1) # seconds; returns when the query ends or time is up
ran_out = 0 < args.stop_when_idle < time.time() - LAST_DATA[0]
if STOP.is_set() or ran_out:
print("stopping (Ctrl-C)" if STOP.is_set() else
f"stopping: no new data for {args.stop_when_idle:.0f} s, the replay has run out")
query.stop()
finally:
if LIVE is not None: # publish what is left and mark the run finished
LIVE.close(complete=ran_out)
# The last days of a replay (the watermark delay plus about one micro-batch) stay
# pending: nothing newer arrives to move the watermark past them. They come out if the
# replay continues later with the same checkpoint.
print(f"done; {DropCounter.dropped} late rows dropped by the watermark")
spark.streams.removeListener(listener)
spark.stop()