Notation: entity e, anchor a (cutoff − latency), events with time t < a.
Recency, frequency, monetary
| Feature | Definition |
|---|---|
days_since_last | (a − max t) in days; missing if no prior events |
days_since_first (tenure) | (a − min t) |
n_<w> | count of events with a − w <= t < a |
active_days_<w> | distinct calendar days with >= 1 event in the window |
sum_<w>, mean_<w>, max_<w> | aggregates of the value |
# pandas, snapshot spine (small/medium data)
def window_aggs(events, spine, w_days):
m = spine.merge(events, on="customer_id", how="left")
m = m[(m.ts < m.anchor) & (m.ts >= m.anchor - pd.Timedelta(days=w_days))]
agg = m.groupby(["customer_id", "anchor"]).agg(**{f"n_{w_days}d": ("ts", "size"),
f"sum_{w_days}d": ("amount", "sum")})
return spine.merge(agg.reset_index(), on=["customer_id", "anchor"], how="left").fillna(
{f"n_{w_days}d": 0, f"sum_{w_days}d": 0})The merge is O(spine x events per entity): fine for millions of rows, use SQL/polars beyond that.
Velocity and burst
| Feature | Definition |
|---|---|
n_1h, n_24h | short-window counts |
burst_1h_7d | n_1h / (n_7d / 168) |
amount_vs_mean_30d | current amount / mean_30d (event-level) |
secs_since_prev | time since the previous event of the entity |
Trend
df["spend_trend"] = df["sum_30d"] / (df["sum_30_60d"] + 1) # sum_30_60d: window [a-60d, a-30d)
df["logins_trend"] = df["n_7d"] / (df["n_30d"] / 30 * 7 + 1e-3)For a slope, aggregate weekly counts over the last 8 weeks and fit a line per entity (numpy polyfit on the week index), or use (last 4 weeks − previous 4 weeks).
Diversity
nuniq_<col>_<w> (merchants, devices, IPs, products). Also entropy of category shares for "spread" of
behaviour.
Exponentially weighted features
df = df.sort_values(["customer_id", "ts"])
df["amount_ewm_prior"] = (df.groupby("customer_id")["amount"]
.transform(lambda s: s.shift().ewm(halflife=5, min_periods=1).mean()))
# time-aware decay: s.shift().ewm(halflife="7D", times=ts_shifted).mean() needs the times per groupRelative to own history
g = df.groupby("card_id")["amount"]
mean_prior = g.transform(lambda s: s.shift().expanding().mean())
std_prior = g.transform(lambda s: s.shift().expanding().std())
df["amount_z_own"] = (df["amount"] - mean_prior) / (std_prior + 1e-6)polars (fast, large data)
import polars as pl
ev = pl.read_csv("txns.csv", try_parse_dates=True).sort("timestamp")
feats = ev.rolling(index_column="timestamp", period="24h", group_by="card_id", closed="left").agg(
pl.len().alias("n_24h"), pl.col("amount").sum().alias("sum_24h"),
pl.col("merchant_category").n_unique().alias("nuniq_merchant_24h"))closed="left" excludes the current row's timestamp (and any events at exactly that instant); with duplicate
timestamps per entity this differs from excluding by event id.
SQL window functions (event-level, row-based)
SELECT txn_id, card_id, ts, amount,
COUNT(*) OVER w24 AS n_24h,
SUM(amount) OVER w24 AS sum_24h
FROM txns
WINDOW w24 AS (PARTITION BY card_id ORDER BY ts
RANGE BETWEEN INTERVAL '24 hours' PRECEDING AND INTERVAL '1 microsecond' PRECEDING);RANGE ... PRECEDING AND <epsilon> PRECEDING excludes the current row (PostgreSQL 11+, DuckDB). BigQuery
needs RANGE BETWEEN 86400 PRECEDING AND 1 PRECEDING over UNIX_SECONDS(ts). gen_window_sql.py uses a
join instead, which works for spines too.
Forecasting lags and rolling statistics
| Feature | Code (horizon h) |
|---|---|
| Lag k (k >= h) | g.shift(k) |
| Rolling mean over w ending h steps ago | g.transform(lambda s: s.shift(h).rolling(w).mean()) |
| Same weekday mean | g.transform(lambda s: s.shift(h).rolling(7*4).apply(lambda x: x[::-7].mean())) |
| Year-ago | g.shift(364) (keeps weekday alignment) |
Calendar features
d = df["date"]
df["dow"], df["month"], df["weekofyear"] = d.dt.day_of_week, d.dt.month, d.dt.isocalendar().week.astype(int)
import holidays
hol = holidays.country_holidays("US", years=range(2020, 2027))
df["is_holiday"] = d.dt.date.map(lambda x: x in hol).astype(int)Add days_to_next_holiday / days_since_last_holiday, paydays (1st/15th, last Friday), school holidays and
promotions known in advance.
anomaly-detection-model-builder
Build and evaluate anomaly detection for tabular, sensor and transaction data with few or no labels: define the anomaly type (point, contextual, collective), choose detectors (robust z-score/MAD and IQR rules, Mahalanobis with robust covariance, k-NN distance, LOF, Isolation Forest, one-class SVM, PCA reconstruction / autoencoders, forecasting residuals for time series), combine them by rank, explain each alert by its deviating features, set thresholds from an alert budget or the score distribution, and evaluate with precision@k, PR-AUC and recall on known incidents, or detector agreement when no labels exist. Includes pure-Python detectors (robust z, Mahalanobis, kNN, Isolation Forest, ensemble) and an evaluation script.
catboost-model-builder
Build CatBoost models that use its strengths correctly: raw categorical columns as cat_features (ordered target statistics, no manual encoding), text_features, Pool construction with NaN-safe categories, ordered boosting and has_time for temporal data, symmetric (oblivious) trees, overfitting detector with eval_set and use_best_model, losses for classification, regression (Quantile, Poisson, Tweedie) and ranking (YetiRank), class weights, monotone constraints, feature importance (PredictionValuesChange, LossFunctionChange) and SHAP values, GPU training and model export. Plans cat/text/numeric columns from a CSV and generates a runnable training script, and checks parameter sets for the conflicts CatBoost rejects (iterations vs n_estimators, Bayesian bootstrap with subsample, multiple class-weight options, depth > 16, use_best_model without eval_set).
categorical-encoding-selector
Choose and implement the right encoding for every categorical column given the model family and the data: one-hot (with infrequent-level grouping and handle_unknown), ordinal with an explicit order, cross-fitted target encoding (scikit-learn TargetEncoder, CatBoost ordered statistics, category_encoders inside CV), frequency/count encoding, feature hashing, native categorical support in LightGBM, HistGradientBoosting, XGBoost and CatBoost, prefix levels for codes (zip3, NAICS-2), and embeddings. Measures cardinality, rare-level share, unseen-level rate on a time-ordered holdout and target signal per column, emits the ColumnTransformer, and quantifies target-encoding leakage (in-sample vs out-of-fold vs holdout AUC).
classification-model-selector
Choose the right classification algorithm for tabular, text or mixed data and prove the choice with a fair bake-off: logistic regression (L2, L1, elastic net), linear SVM, naive Bayes, k-NN, RBF SVM, decision trees, random forest, extra trees, HistGradientBoosting, LightGBM, XGBoost, CatBoost, explainable boosting machines (EBM/GAM), points scorecards and MLPs, matched to data size, width, categorical and high-cardinality share, missingness, class imbalance, text, and constraints such as interpretability, monotonic constraints, calibrated probabilities, latency budgets and tiny deployable models. Ranks candidates with starting hyperparameters and cautions, then generates a bake-off script running every candidate on identical CV folds with per-fold metrics, fit time and prediction latency.
clustering-algorithm-selector
Choose the right clustering algorithm and check that clustering makes sense at all: cluster tendency (Hopkins statistic with a correlated-features caveat, nearest-neighbour isolation), then k-means / MiniBatchKMeans, Gaussian mixtures with BIC, agglomerative (Ward, average, complete, single) with dendrograms, DBSCAN, HDBSCAN, OPTICS, spectral clustering, BIRCH, mean shift, k-prototypes and k-modes for mixed or categorical data, and Gower distance, matched to data size, expected shapes, noise, varying density, known k, soft memberships, hierarchy and streaming. Covers preprocessing (scaling, encoding, dimensionality, distance metrics), validation (internal indices, bootstrap stability, external labels, business profiling) and assigning new points.
collaborative-filtering-implementer
Implement collaborative filtering recommenders that beat popularity: item-based kNN with cosine, Jaccard or asymmetric similarity, shrinkage, neighbourhood size, positive-only or mean-centred rating signals and 'because you liked X' explanations; implicit ALS with confidence weighting, BPR pairwise ranking and the closed-form EASE model in plain NumPy, tuned on a temporal validation split by recall@k and NDCG@k and refit on all data; plus user-kNN, explicit matrix factorisation, the implicit/LightFM libraries, hyperparameter ranges, cold-start fallbacks, scaling with sparse matrices and approximate nearest neighbours. Produces top-k lists in the format of the recommendation evaluator.