How your bank spots a stolen card: the code

These are the files that do most of the work. The comments explain why each part works the way it does. If anything is unclear, or you would do it differently, tell me. I will also send you the full code for free, with nothing to sign up for. Ask for the full code

src/core/model.ts

The learned score. A logistic regression written from scratch, fitted by Newton's method, whose parts add up to the score the panel shows. 99 lines

import { FEATURES, type Feature, type Vector } from "./features.ts";
import { PARAMS } from "./params.ts";

export interface Model {
  bias: number;
  weights: Record<Feature, number>;
}

export type Part = { feature: Feature; value: number; points: number };

// The score is in log-odds, so the parts add up to it exactly.
export function score(m: Model, v: Vector): number {
  let s = m.bias;
  for (const k of FEATURES) s += m.weights[k] * v[k];
  return s;
}

export function parts(m: Model, v: Vector): Part[] {
  return FEATURES.filter((k) => v[k] !== 0 && m.weights[k] !== 0)
    .map((k) => ({ feature: k, value: v[k], points: m.weights[k] * v[k] }))
    .sort((a, b) => Math.abs(b.points) - Math.abs(a.points));
}

export const chance = (s: number) => 1 / (1 + Math.exp(-s));

function solve(a: number[][], b: number[]): number[] {
  const n = b.length;
  const m = a.map((row, i) => [...row, b[i]]);
  for (let c = 0; c < n; c++) {
    let p = c;
    for (let r = c + 1; r < n; r++) if (Math.abs(m[r][c]) > Math.abs(m[p][c])) p = r;
    [m[c], m[p]] = [m[p], m[c]];
    for (let r = 0; r < n; r++) {
      if (r === c) continue;
      const k = m[r][c] / m[c][c];
      for (let j = c; j <= n; j++) m[r][j] -= k * m[c][j];
    }
  }
  return m.map((row, i) => row[n] / m[i][i]);
}

// Logistic regression fitted by Newton's method, with a small ridge penalty so a signal seen only on fraud stays finite.
export function train(X: Vector[], y: boolean[]): Model {
  const { iterations, l2 } = PARAMS.model;
  const d = FEATURES.length + 1;
  const rows = X.map((v) => [1, ...FEATURES.map((k) => v[k])]);
  const pos = y.filter(Boolean).length;
  let w = new Array(d).fill(0);
  w[0] = Math.log((pos + 0.5) / (y.length - pos + 0.5));
  const loss = (w: number[]) => {
    let l = 0;
    for (let i = 0; i < rows.length; i++) {
      let z = 0;
      for (let j = 0; j < d; j++) z += w[j] * rows[i][j];
      l += Math.log1p(Math.exp(-Math.abs(z))) + Math.max(0, y[i] ? -z : z);
    }
    for (let j = 1; j < d; j++) l += (l2 / 2) * w[j] * w[j];
    return l;
  };
  let current = loss(w);
  for (let it = 0; it < iterations; it++) {
    const g = new Array(d).fill(0);
    const H = Array.from({ length: d }, () => new Array(d).fill(0));
    for (let i = 0; i < rows.length; i++) {
      const x = rows[i];
      let z = 0;
      for (let j = 0; j < d; j++) z += w[j] * x[j];
      const p = 1 / (1 + Math.exp(-z));
      const r = p - (y[i] ? 1 : 0);
      const s = p * (1 - p);
      for (let j = 0; j < d; j++) {
        if (x[j] === 0) continue;
        g[j] += r * x[j];
        const sx = s * x[j];
        for (let k = j; k < d; k++) if (x[k] !== 0) H[j][k] += sx * x[k];
      }
    }
    for (let j = 0; j < d; j++) {
      for (let k = 0; k < j; k++) H[j][k] = H[k][j];
      if (j > 0) {
        g[j] += l2 * w[j];
        H[j][j] += l2;
      }
    }
    const step = solve(H, g);
    // A full Newton step overshoots when fraud is this rare, so halve it until the loss falls.
    for (let t = 1; t > 1e-6; t /= 2) {
      const next = w.map((x, j) => x - t * step[j]);
      const l = loss(next);
      if (l < current) {
        w = next;
        current = l;
        break;
      }
    }
  }
  const round = (x: number) => Math.round(x * 1000) / 1000;
  return { bias: round(w[0]), weights: Object.fromEntries(FEATURES.map((k, i) => [k, round(w[i + 1])])) as Record<Feature, number> };
}

src/core/features.ts

The twelve signals, each read from the card's own earlier payments: recent payments, a new device or shop, the amount and the day's spending against usual, the place and the hour. 89 lines

import { PARAMS } from "./params.ts";
import { MINUTES_PER_DAY, type Payment } from "./world.ts";

export const FEATURES = ["burst", "tiny", "newDevice", "newShop", "usualShop", "bigger", "daySpend", "abroad", "otherCity", "quickMove", "night", "online"] as const;
export type Feature = (typeof FEATURES)[number];
export type Vector = Record<Feature, number>;

interface CardState {
  recent: number[];
  lastInPerson: { place: string; t: number } | null;
  visits: Map<string, number>;
  devices: Set<number>;
  amounts: number[];
  times: number[];
}

function median(xs: number[]): number {
  const s = [...xs].sort((a, b) => a - b);
  const m = s.length >> 1;
  return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;
}

// What the bank knows about each card, built only from earlier payments on it.
export class Featurizer {
  private cards = new Map<number, CardState>();

  private state(card: number): CardState {
    let s = this.cards.get(card);
    if (!s) this.cards.set(card, (s = { recent: [], lastInPerson: null, visits: new Map(), devices: new Set(), amounts: [], times: [] }));
    return s;
  }

  usual(card: number): number {
    const s = this.state(card);
    return s.amounts.length >= PARAMS.features.minHistory ? median(s.amounts) : PARAMS.habits.medianAmount;
  }

  // Spending on a usual day, from the history kept; a new card is assumed to spend two usual payments a day.
  usualDay(card: number): number {
    const s = this.state(card);
    const days = s.times.length >= PARAMS.features.minHistory ? (s.times[s.times.length - 1] - s.times[0]) / MINUTES_PER_DAY : 0;
    return days >= 1 ? s.amounts.reduce((a, b) => a + b, 0) / days : 2 * this.usual(card);
  }

  // Features of p from the history so far, then p joins the history.
  next(p: Payment): Vector {
    const f = PARAMS.features;
    const s = this.state(p.card);
    s.recent = s.recent.filter((t) => p.t - t < f.burstMinutes);
    const online = p.place === "online";
    const visits = s.visits.get(p.shop) ?? 0;
    const ratio = p.amount / this.usual(p.card);
    const hour = (p.t % MINUTES_PER_DAY) / 60;
    let today = p.amount;
    for (let i = s.times.length - 1; i >= 0 && p.t - s.times[i] < MINUTES_PER_DAY; i--) today += s.amounts[i];
    const v: Vector = {
      burst: Math.min(f.burstCap, s.recent.length),
      tiny: online && p.amount <= f.tinyAmount ? 1 : 0,
      newDevice: online && !s.devices.has(p.device) ? 1 : 0,
      newShop: visits === 0 ? 1 : 0,
      usualShop: visits >= f.usualVisits ? 1 : 0,
      bigger: Math.min(f.biggerCap, Math.max(0, Math.log2(ratio))),
      daySpend: Math.min(f.biggerCap, Math.max(0, Math.log2(today / this.usualDay(p.card)))),
      abroad: p.place === "abroad" ? 1 : 0,
      otherCity: p.place === "city" ? 1 : 0,
      quickMove: !online && s.lastInPerson && s.lastInPerson.place !== p.place && p.t - s.lastInPerson.t < f.moveMinutes ? 1 : 0,
      night: hour < f.nightBeforeHour ? 1 : 0,
      online: online ? 1 : 0,
    };
    s.recent.push(p.t);
    if (!online) s.lastInPerson = { place: p.place, t: p.t };
    s.visits.set(p.shop, visits + 1);
    if (online) s.devices.add(p.device);
    s.amounts.push(p.amount);
    s.times.push(p.t);
    if (s.amounts.length > f.historyPayments) {
      s.amounts.shift();
      s.times.shift();
    }
    return v;
  }
}

export const toArray = (v: Vector) => FEATURES.map((k) => v[k]);

export function featurize(payments: Payment[]): Vector[] {
  const fz = new Featurizer();
  return payments.map((p) => fz.next(p));
}

src/core/policy.ts

Decisions and what the bank knows. It replays any decline line over the simulated payments and works out which frauds are labelled by a given day. 92 lines

import { PARAMS } from "./params.ts";
import { type Episode, MINUTES_PER_DAY, type Payment } from "./world.ts";

export type Decision = "approve" | "confirm" | "decline";

export function decide(score: number, cut = PARAMS.decide): Decision {
  if (score >= cut.declineAt) return "decline";
  if (score >= cut.confirmAt) return "confirm";
  return "approve";
}

export interface Outcome {
  happened: boolean[]; // a stopped fraudster tries nothing more on that card
  stoppedAt: Map<number, number>;
  lastAt: Map<number, number>;
}

// Replays the attempts under any rule that flags payments. A flagged fraud payment stops its episode; a flagged real one is declined.
export function replay(payments: Payment[], flagged: (i: number) => boolean): Outcome {
  const happened = new Array<boolean>(payments.length).fill(true);
  const stoppedAt = new Map<number, number>();
  const lastAt = new Map<number, number>();
  payments.forEach((p, i) => {
    if (!p.fraud) return;
    if (stoppedAt.has(p.episode)) {
      happened[i] = false;
      return;
    }
    lastAt.set(p.episode, p.t);
    if (flagged(i)) stoppedAt.set(p.episode, p.t);
  });
  return { happened, stoppedAt, lastAt };
}

export interface Tally {
  payments: number;
  real: number;
  realFlagged: number;
  fraudAttempts: number;
  fraudHappened: number;
  fraudFlagged: number;
  fraudLost: number;
  fraudAttemptedMoney: number;
  episodes: number;
  episodesStopped: number;
  correct: number;
}

// Counts over payments made in [from, to) minutes; episodes count by their start.
export function tally(payments: Payment[], flagged: (i: number) => boolean, out: Outcome, from = -Infinity, to = Infinity): Tally {
  const t: Tally = { payments: 0, real: 0, realFlagged: 0, fraudAttempts: 0, fraudHappened: 0, fraudFlagged: 0, fraudLost: 0, fraudAttemptedMoney: 0, episodes: 0, episodesStopped: 0, correct: 0 };
  const seen = new Set<number>();
  payments.forEach((p, i) => {
    if (p.t < from || p.t >= to) return;
    if (!p.fraud) {
      t.payments++;
      t.real++;
      if (flagged(i)) t.realFlagged++;
      else t.correct++;
      return;
    }
    t.fraudAttempts++;
    t.fraudAttemptedMoney += p.amount;
    if (!seen.has(p.episode)) {
      seen.add(p.episode);
      t.episodes++;
      if (out.stoppedAt.has(p.episode)) t.episodesStopped++;
    }
    if (!out.happened[i]) return;
    t.payments++;
    t.fraudHappened++;
    if (flagged(i)) {
      t.fraudFlagged++;
      t.correct++;
    } else t.fraudLost += p.amount;
  });
  return t;
}

export const stoppedShare = (t: Tally) => (t.fraudAttemptedMoney ? 1 - t.fraudLost / t.fraudAttemptedMoney : 0);
export const accuracy = (t: Tally) => t.correct / t.payments;

// What the bank believes about each payment at time `at`: fraud only once it was stopped or the cardholder disputed it.
export function labelsAt(payments: Payment[], episodes: Episode[], out: Outcome, at: number): boolean[] {
  return payments.map((p) => {
    if (!p.fraud) return false;
    const stop = out.stoppedAt.get(p.episode);
    if (stop !== undefined) return stop <= at;
    const ep = episodes[p.episode];
    return ep.noticed && (out.lastAt.get(p.episode) ?? Infinity) + ep.delayDays * MINUTES_PER_DAY <= at;
  });
}