"""Features for the big-move model (decision 0007).
The same code builds the features for training (src/ml/train.py, on the stream's daily
output) and for live scoring (src/streaming/job.py), so the model never meets a feature
computed differently from the way it was trained ("training/serving skew").
Every feature uses only today's row, the event calendar and config/retailers.csv, never
a later day:
today's stream row |z_ar|, z_ar, ar_sd, beta, |mkt_ret|, z_views, attention_spike,
log(vol_ratio), abnormal_return
the event calendar days to the next in-scope event day and since the last one
the date day of the week, month
config/retailers.csv is_online
The label, used only in training, is the same stock's abnormal_return on its next
trading day: did tomorrow bring a big move?
Usage:
from ml.features import FEATURES, add_features, calendar_table, retailer_table
rows = add_features(daily_df, spark.createDataFrame(calendar_table()),
spark.createDataFrame(retailer_table()))
"""
from __future__ import annotations
import bisect
from datetime import date, timedelta
import pandas as pd
from common.contracts import expand_events, load_retailers
from common.study import ML_EVENT_DAYS_CAP, STUDY_END_YEAR, STUDY_START_YEAR
FEATURES = [
"abs_z_ar", "z_ar", "ar_sd", "beta", "abs_mkt_ret",
"z_views", "attention_spike", "log_vol_ratio", "abnormal_return",
"days_to_event", "days_since_event", "day_of_week", "month", "is_online",
]
# Dropped together to measure what Wikipedia attention adds to the model.
ATTENTION_FEATURES = ["z_views", "attention_spike"]
LABEL = "big_move_next"
def event_days(start_year: int = STUDY_START_YEAR, end_year: int = STUDY_END_YEAR) -> list[date]:
"""Every calendar day covered by an in-scope event, sorted (Prime Day spans several)."""
days = set()
for e in expand_events(start_year, end_year):
d = e["event_date"]
while d <= e["event_end_date"]:
days.add(d)
d += timedelta(days=1)
return sorted(days)
def calendar_table(start_year: int = STUDY_START_YEAR, end_year: int = STUDY_END_YEAR,
cap: int = ML_EVENT_DAYS_CAP) -> pd.DataFrame:
"""One row per calendar day: days to the next event day and since the last one.
Both are 0 on an event day and capped at `cap`, so a day with no event in sight (or
past the last event in the calendar) gets `cap`.
"""
events = event_days(start_year, end_year)
rows = []
for d in pd.date_range(date(start_year, 1, 1), date(end_year, 12, 31)).date:
i = bisect.bisect_left(events, d) # first event day >= d
to_next = (events[i] - d).days if i < len(events) else cap
j = bisect.bisect_right(events, d) - 1 # last event day <= d
since_last = (d - events[j]).days if j >= 0 else cap
rows.append({"date": d, "days_to_event": min(to_next, cap),
"days_since_event": min(since_last, cap)})
return pd.DataFrame(rows)
def retailer_table() -> pd.DataFrame:
"""ticker -> is_online (1 for online retailers, 0 for store retailers)."""
return pd.DataFrame([{"ticker": r["ticker"], "is_online": int(r["retailer_type"] == "online")}
for r in load_retailers()])
def add_features(df, calendar, retailers):
"""Spark: rows with the stream_signals columns, plus every column in FEATURES.
`calendar` and `retailers` are Spark DataFrames of calendar_table() and
retailer_table(); both are small, so they are broadcast to every worker.
"""
from pyspark.sql import functions as F
return (df.join(F.broadcast(calendar), "date", "left")
.join(F.broadcast(retailers), "ticker", "left")
.withColumn("abs_z_ar", F.abs("z_ar"))
.withColumn("abs_mkt_ret", F.abs("mkt_ret"))
# log keeps a 10x volume day from dominating; null when vol_ratio is missing
.withColumn("log_vol_ratio", F.when(F.col("vol_ratio") > 0, F.log("vol_ratio")))
.withColumn("day_of_week", F.dayofweek("date"))
.withColumn("month", F.month("date")))
def add_label(df):
"""Spark: the label, each stock's abnormal_return on its next trading day."""
from pyspark.sql import functions as F
from pyspark.sql.window import Window
return df.withColumn(LABEL, F.lead("abnormal_return").over(Window.partitionBy("ticker").orderBy("date")))