> ## 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/ml/features.py

> Features for the big-move model (decision 0007).

`src/ml/features.py` · chapter [The big-move model](https://calendar-effects.mintlify.site/tour/08-machine-learning.md), file 2 · 101 lines · [open in the repository](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/features.py)

## What it does

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:

```text theme={null}
from ml.features import FEATURES, add_features, calendar_table, retailer_table
rows = add_features(daily_df, spark.createDataFrame(calendar_table()),
                    spark.createDataFrame(retailer_table()))
```

## What is inside

* **`FEATURES`** · [line 32](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/features.py#L32)
* **`ATTENTION_FEATURES`** · [line 38](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/features.py#L38): Dropped together to measure what Wikipedia attention adds to the model.
* **`LABEL`** · [line 39](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/features.py#L39)
* **`event_days(start_year, end_year)`** · [line 42](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/features.py#L42): Every calendar day covered by an in-scope event, sorted (Prime Day spans several).
* **`calendar_table(start_year, end_year, cap)`** · [line 53](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/features.py#L53): One row per calendar day: days to the next event day and since the last one.
* **`retailer_table()`** · [line 72](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/features.py#L72): ticker -> is\_online (1 for online retailers, 0 for store retailers).
* **`add_features(df, calendar, retailers)`** · [line 78](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/features.py#L78): Spark: rows with the stream\_signals columns, plus every column in FEATURES.
* **`add_label(df)`** · [line 96](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/features.py#L96): Spark: the label, each stock's abnormal\_return on its next trading day.

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

**Used by:** [`src/streaming/job.py`](https://calendar-effects.mintlify.site/reference/src/streaming/job), [`src/ml/train.py`](https://calendar-effects.mintlify.site/reference/src/ml/train), [`tests/test_ml_features.py`](https://calendar-effects.mintlify.site/reference/tests/test_ml_features)

## Source

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


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