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

> Train and test the big-move model with Spark MLlib (decision 0007).

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

## What it does

Train and test the big-move model with Spark MLlib (decision 0007).

The question: from what the stream knows about a retailer today, can a model tell which
retailers will make a big move tomorrow (tomorrow's |z\_ar| >= ABNORMAL\_RETURN\_Z)? Daily
returns are mostly noise, so accuracy is the wrong yardstick (always saying "no" is
right \~95% of the time). The model is judged on how well it ranks tomorrow's big movers:
ROC-AUC (0.5 = chance), PR-AUC against the base rate, and the hit rate of the days it
would flag.

Steps:

1. Read the streaming job's daily output, add the features (src/ml/features.py) and the
   label (tomorrow's abnormal\_return), and drop days the stream had no model for yet.
2. Split by time (common.study): train on the years up to ML\_TRAIN\_END\_YEAR, choose the
   model on ML\_VALIDATION\_YEAR, report on ML\_TEST\_START\_YEAR onwards. Never a random
   split, which would let the model learn from days after the ones it is tested on. The
   split is also purged: a row whose "tomorrow" falls in the next period is dropped.
3. Try two MLlib pipelines on the validation year, each with a small grid: logistic
   regression on scaled features (a transparent baseline) and gradient-boosted trees
   (non-linear effects, interactions). Big moves are rare, so each class gets equal
   total weight.
4. Refit the best on train + validation and score the test years, next to:
   * the same model without the attention features: what does Wikipedia add?
   * a baseline with no model that ranks by today's |z\_ar|: do big moves just cluster?
5. Save the model for the streaming job with the probability cut-off that flags the top
   ML\_ALERT\_TOP\_SHARE of stock-days, and write the tables and charts for the report.

Run from anywhere after the streaming job:

```bash theme={null}
python3 src/ml/train.py
```

Output: data/models/big\_move/ (+ big\_move.json), and in data/results/: ml\_metrics.csv,
ml\_test\_predictions.parquet, ml\_feature\_importance.csv, charts/ml\_\*.png

## What is inside

* **`METRICS`** · [line 58](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/train.py#L58)
* **`TEST_PREDICTIONS`** · [line 59](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/train.py#L59)
* **`IMPORTANCE`** · [line 60](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/train.py#L60)
* **`CHARTS_DIR`** · [line 61](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/train.py#L61)
* **`CANDIDATES`** · [line 65](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/train.py#L65): Small grids: the aim is a fair comparison of two kinds of model, not squeezing out the last 0.001 of AUC on one year of validation data.
* **`GBT_TREES`** · [line 69](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/train.py#L69)
* **`SEED`** · [line 70](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/train.py#L70): fixed so a rerun gives the same trees
* **`pipeline(kind, params, features)`** · [line 73](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/train.py#L73): An MLlib pipeline: features -> vector -> (scale) -> classifier.
* **`with_weights(df)`** · [line 89](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/train.py#L89): Weight each class to the same total, so rare big moves are not ignored.
* **`score(model, df)`** · [line 95](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/train.py#L95): The model's probability of a big move tomorrow, as a plain column.
* **`evaluate(scored, score_col, model, params, features, split)`** · [line 100](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/train.py#L100): One ml\_metrics row: AUCs from MLlib, precision of the top ML\_ALERT\_TOP\_SHARE in pandas.
* **`importances(model, kind, features)`** · [line 115](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/train.py#L115): How much each feature drives the model: tree importances, or |scaled coefficient|.
* **`curve_points(y, s)`** · [line 125](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/train.py#L125): ROC (false and true positive rates) and precision-recall points for one score.
* **`charts(curves, base_rate, imp)`** · [line 135](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/train.py#L135): ml\_roc\_pr.png (the test years) and ml\_feature\_importance.png.
* **`main()`** · [line 165](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/src/ml/train.py#L165)

## Connections

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

## Source

```python title="src/ml/train.py" lines expandable theme={null}
"""Train and test the big-move model with Spark MLlib (decision 0007).

The question: from what the stream knows about a retailer today, can a model tell which
retailers will make a big move tomorrow (tomorrow's |z_ar| >= ABNORMAL_RETURN_Z)? Daily
returns are mostly noise, so accuracy is the wrong yardstick (always saying "no" is
right ~95% of the time). The model is judged on how well it ranks tomorrow's big movers:
ROC-AUC (0.5 = chance), PR-AUC against the base rate, and the hit rate of the days it
would flag.

Steps:
1. Read the streaming job's daily output, add the features (src/ml/features.py) and the
   label (tomorrow's abnormal_return), and drop days the stream had no model for yet.
2. Split by time (common.study): train on the years up to ML_TRAIN_END_YEAR, choose the
   model on ML_VALIDATION_YEAR, report on ML_TEST_START_YEAR onwards. Never a random
   split, which would let the model learn from days after the ones it is tested on. The
   split is also purged: a row whose "tomorrow" falls in the next period is dropped.
3. Try two MLlib pipelines on the validation year, each with a small grid: logistic
   regression on scaled features (a transparent baseline) and gradient-boosted trees
   (non-linear effects, interactions). Big moves are rare, so each class gets equal
   total weight.
4. Refit the best on train + validation and score the test years, next to:
   - the same model without the attention features: what does Wikipedia add?
   - a baseline with no model that ranks by today's |z_ar|: do big moves just cluster?
5. Save the model for the streaming job with the probability cut-off that flags the top
   ML_ALERT_TOP_SHARE of stock-days, and write the tables and charts for the report.

Run from anywhere after the streaming job:
    python3 src/ml/train.py
Output: data/models/big_move/ (+ big_move.json), and in data/results/: ml_metrics.csv,
        ml_test_predictions.parquet, ml_feature_importance.csv, charts/ml_*.png
"""
from __future__ import annotations

import argparse
import json
from datetime import datetime, timezone
from pathlib import Path

import numpy as np
import pandas as pd
from pyspark.ml import Pipeline
from pyspark.ml.classification import GBTClassifier, LogisticRegression
from pyspark.ml.evaluation import BinaryClassificationEvaluator
from pyspark.ml.feature import StandardScaler, VectorAssembler
from pyspark.ml.functions import vector_to_array
from pyspark.sql import SparkSession, functions as F
from pyspark.sql.window import Window

from common.contracts import pandas_columns, parquet_columns, require_contract
from common.settings import (BIG_MOVE_MODEL, BIG_MOVE_MODEL_INFO, RESULTS_DIR, STREAM_DIR,
                             STREAM_SUBDIRS)
from common.study import (ML_ALERT_TOP_SHARE, ML_TEST_START_YEAR, ML_TRAIN_END_YEAR,
                          ML_VALIDATION_YEAR)
from eventstudy.car import code_version
from ml.features import (ATTENTION_FEATURES, FEATURES, LABEL, add_features, add_label,
                         calendar_table, retailer_table)

METRICS = RESULTS_DIR / "ml_metrics.csv"
TEST_PREDICTIONS = RESULTS_DIR / "ml_test_predictions.parquet"
IMPORTANCE = RESULTS_DIR / "ml_feature_importance.csv"
CHARTS_DIR = RESULTS_DIR / "charts"

# Small grids: the aim is a fair comparison of two kinds of model, not squeezing out the
# last 0.001 of AUC on one year of validation data.
CANDIDATES = {
    "logistic": [{"regParam": r} for r in (0.0, 0.01, 0.1)],
    "gbt": [{"maxDepth": d} for d in (3, 5)],
}
GBT_TREES = 60
SEED = 732  # fixed so a rerun gives the same trees


def pipeline(kind: str, params: dict, features: list[str]) -> Pipeline:
    """An MLlib pipeline: features -> vector -> (scale) -> classifier."""
    # handleInvalid="skip": a row with a missing feature is not scored, in training or live
    assemble = VectorAssembler(inputCols=features, outputCol="features", handleInvalid="skip")
    if kind == "logistic":
        return Pipeline(stages=[
            assemble,
            StandardScaler(inputCol="features", outputCol="scaled", withMean=True, withStd=True),
            LogisticRegression(featuresCol="scaled", labelCol=LABEL, weightCol="weight",
                               maxIter=100, **params)])
    return Pipeline(stages=[
        assemble,
        GBTClassifier(featuresCol="features", labelCol=LABEL, weightCol="weight",
                      maxIter=GBT_TREES, seed=SEED, **params)])


def with_weights(df):
    """Weight each class to the same total, so rare big moves are not ignored."""
    rate = df.agg(F.avg(LABEL)).first()[0]
    return df.withColumn("weight", F.when(F.col(LABEL) == 1, 0.5 / rate).otherwise(0.5 / (1 - rate)))


def score(model, df):
    """The model's probability of a big move tomorrow, as a plain column."""
    return model.transform(df).withColumn("p_big_move_next", vector_to_array("probability")[1])


def evaluate(scored, score_col: str, model: str, params: str, features: str, split: str) -> dict:
    """One ml_metrics row: AUCs from MLlib, precision of the top ML_ALERT_TOP_SHARE in pandas."""
    roc = BinaryClassificationEvaluator(rawPredictionCol=score_col, labelCol=LABEL,
                                        metricName="areaUnderROC").evaluate(scored)
    pr = BinaryClassificationEvaluator(rawPredictionCol=score_col, labelCol=LABEL,
                                       metricName="areaUnderPR").evaluate(scored)
    pdf = scored.select(score_col, LABEL).toPandas()
    base = pdf[LABEL].mean()
    top = pdf[pdf[score_col] >= pdf[score_col].quantile(1 - ML_ALERT_TOP_SHARE)]
    return {"model": model, "params": params, "features": features, "split": split,
            "n_rows": len(pdf), "n_big_moves": int(pdf[LABEL].sum()), "base_rate": base,
            "auc_roc": roc, "auc_pr": pr, "precision_top": top[LABEL].mean(),
            "lift_top": top[LABEL].mean() / base}


def importances(model, kind: str, features: list[str]) -> pd.DataFrame:
    """How much each feature drives the model: tree importances, or |scaled coefficient|."""
    last = model.stages[-1]
    values = (last.featureImportances.toArray() if kind == "gbt"
              else np.abs(last.coefficients.toArray()))
    values = values / values.sum() if values.sum() else values
    return (pd.DataFrame({"model": kind, "feature": features, "importance": values})
            .sort_values("importance", ascending=False).reset_index(drop=True))


def curve_points(y: np.ndarray, s: np.ndarray):
    """ROC (false and true positive rates) and precision-recall points for one score."""
    order = np.argsort(-s)
    y = y[order]
    tp, fp = np.cumsum(y), np.cumsum(1 - y)
    tpr, fpr = tp / max(y.sum(), 1), fp / max((1 - y).sum(), 1)
    precision, recall = tp / np.arange(1, len(y) + 1), tpr
    return fpr, tpr, recall, precision


def charts(curves: dict, base_rate: float, imp: pd.DataFrame):
    """ml_roc_pr.png (the test years) and ml_feature_importance.png."""
    import matplotlib
    matplotlib.use("Agg")
    import matplotlib.pyplot as plt

    CHARTS_DIR.mkdir(parents=True, exist_ok=True)
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4.5))
    for label, (fpr, tpr, recall, precision) in curves.items():
        ax1.plot(fpr, tpr, label=label)
        ax2.plot(recall, precision, label=label)
    ax1.plot([0, 1], [0, 1], color="grey", lw=0.8, ls="--", label="chance")
    ax2.axhline(base_rate, color="grey", lw=0.8, ls="--", label=f"base rate {base_rate:.1%}")
    ax1.set(title="ROC, test years", xlabel="false positive rate", ylabel="true positive rate")
    ax2.set(title="Precision-recall, test years", xlabel="recall", ylabel="precision")
    for ax in (ax1, ax2):
        ax.legend(fontsize=8, frameon=False)
    fig.suptitle("Will a retailer make a big move tomorrow? Spark MLlib on the stream's daily output")
    fig.savefig(CHARTS_DIR / "ml_roc_pr.png", dpi=200, bbox_inches="tight")
    plt.close(fig)

    fig, ax = plt.subplots(figsize=(7, 5))
    shown = imp.iloc[::-1]
    ax.barh(shown["feature"], shown["importance"], color="#378ADD")
    ax.set(title=f"What the {imp['model'].iloc[0]} model relies on", xlabel="share of importance")
    fig.savefig(CHARTS_DIR / "ml_feature_importance.png", dpi=200, bbox_inches="tight")
    plt.close(fig)
    print("wrote", CHARTS_DIR / "ml_roc_pr.png", "and", CHARTS_DIR / "ml_feature_importance.png")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--signals", default=str(STREAM_DIR / STREAM_SUBDIRS["stream_signals"]),
                        help="the streaming job's daily output folder")
    args = parser.parse_args()

    spark = (SparkSession.builder.appName("calendar-effects-ml")
             .config("spark.sql.session.timeZone", "UTC")
             .config("spark.sql.shuffle.partitions", 8)
             .getOrCreate())
    spark.sparkContext.setLogLevel("WARN")

    if Path(args.signals).exists():   # a local folder; on the cluster it is an HDFS path
        require_contract("stream_signals", parquet_columns(args.signals))
    daily = spark.read.parquet(args.signals).drop("batch_id")
    calendar = spark.createDataFrame(calendar_table())
    retailers = spark.createDataFrame(retailer_table())

    next_year = F.year(F.lead("date").over(Window.partitionBy("ticker").orderBy("date")))
    rows = (add_label(add_features(daily, calendar, retailers))
            .withColumn("year", F.year("date"))
            .withColumn("label_year", next_year)
            .dropna(subset=FEATURES + [LABEL])
            .withColumn(LABEL, F.col(LABEL).cast("double"))
            .cache())
    train = with_weights(rows.filter(F.col("label_year") <= ML_TRAIN_END_YEAR))
    valid = rows.filter((F.col("year") == ML_VALIDATION_YEAR) & (F.col("label_year") == ML_VALIDATION_YEAR))
    fit_all = with_weights(rows.filter(F.col("label_year") <= ML_VALIDATION_YEAR))
    test = rows.filter(F.col("year") >= ML_TEST_START_YEAR)
    print(f"rows: train {train.count()}, validation {valid.count()}, test {test.count()}")

    # 1. Choose the model on the validation year
    results, best = [], None
    for kind, grid in CANDIDATES.items():
        for params in grid:
            m = pipeline(kind, params, FEATURES).fit(train)
            row = evaluate(score(m, valid), "p_big_move_next", kind, json.dumps(params), "all", "validation")
            results.append(row)
            print(f"  {kind} {params}: validation ROC-AUC {row['auc_roc']:.3f}, PR-AUC {row['auc_pr']:.3f}")
            if best is None or row["auc_pr"] > best[2]:
                best = (kind, params, row["auc_pr"])
    kind, params, _ = best
    print(f"chosen: {kind} {params}")

    # 2. Refit on train + validation and report on the test years
    final = pipeline(kind, params, FEATURES).fit(fit_all)
    test_scored = score(final, test).cache()
    results.append(evaluate(test_scored, "p_big_move_next", kind, json.dumps(params), "all", "test"))

    no_attention = [f for f in FEATURES if f not in ATTENTION_FEATURES]
    ablation = pipeline(kind, params, no_attention).fit(fit_all)
    ablation_scored = score(ablation, test).cache()
    results.append(evaluate(ablation_scored, "p_big_move_next", kind, json.dumps(params),
                            "no_attention", "test"))
    results.append(evaluate(test, "abs_z_ar", "baseline_abs_z_ar", "{}", "abs_z_ar", "test"))

    metrics = pd.DataFrame(results)
    require_contract("ml_metrics", pandas_columns(metrics))
    RESULTS_DIR.mkdir(parents=True, exist_ok=True)
    metrics.to_csv(METRICS, index=False)

    # 3. Test predictions, importances, charts
    preds = (test_scored.select("ticker", "date", "p_big_move_next", F.col(LABEL).cast("int").alias(LABEL))
             .orderBy("date", "ticker").toPandas())
    require_contract("ml_test_predictions", pandas_columns(preds))
    preds.to_parquet(TEST_PREDICTIONS, index=False)

    imp = importances(final, kind, FEATURES)
    require_contract("ml_feature_importance", pandas_columns(imp))
    imp.to_csv(IMPORTANCE, index=False)

    curves = {}
    for label, scored, col in ((f"{kind}, all features", test_scored, "p_big_move_next"),
                               (f"{kind}, no attention", ablation_scored, "p_big_move_next"),
                               ("baseline: today's |z_ar|", test, "abs_z_ar")):
        pdf = scored.select(col, LABEL).toPandas()
        curves[label] = curve_points(pdf[LABEL].to_numpy(), pdf[col].to_numpy())
    test_row = metrics[(metrics["split"] == "test") & (metrics["features"] == "all")].iloc[0]
    charts(curves, test_row["base_rate"], imp)

    # 4. The model and its alert cut-off, for the streaming job
    cutoff = (score(final, fit_all).approxQuantile("p_big_move_next", [1 - ML_ALERT_TOP_SHARE], 0.001))[0]
    final.write().overwrite().save(str(BIG_MOVE_MODEL))
    BIG_MOVE_MODEL_INFO.write_text(json.dumps({
        "model": kind, "params": params, "features": FEATURES,
        "alert_cutoff": cutoff, "alert_top_share": ML_ALERT_TOP_SHARE,
        "fit_years": [int(rows.agg(F.min("year")).first()[0]), ML_VALIDATION_YEAR],
        "test_years": [ML_TEST_START_YEAR, int(rows.agg(F.max("year")).first()[0])],
        "test": {k: float(test_row[k]) for k in ("base_rate", "auc_roc", "auc_pr", "precision_top", "lift_top")},
        "code_version": code_version(), "trained_at": datetime.now(timezone.utc).isoformat(),
    }, indent=2))

    print()
    print(metrics[metrics["split"] == "test"][["model", "features", "n_rows", "base_rate", "auc_roc",
                                                "auc_pr", "precision_top", "lift_top"]].round(4).to_string(index=False))
    print(f"\nsaved {BIG_MOVE_MODEL}; live alert when p >= {cutoff:.4f} (top {ML_ALERT_TOP_SHARE:.0%})")
    spark.stop()


if __name__ == "__main__":
    main()
```


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