gcp spark quickstart 2 - fraud detector

Let's create another python script that we can run with our serverless spark cluster.

Some preliminary setup here :-

gcloud services enable dataproc.googleapis.com bigquery.googleapis.com

export BUCKET=$(gcloud config get-value project)-fraud-demo
gcloud storage buckets create gs://$BUCKET --location=us-central1
bq mk --location=US fraud



And next we will create the requires tables in bigquery - all these command are ran from the command line 


bq query --use_legacy_sql=false <<'SQL'
CREATE OR REPLACE TABLE fraud.transactions AS
WITH normal AS (
  SELECT
    GENERATE_UUID() AS txn_id,
    CONCAT('card_', CAST(1 + CAST(FLOOR(RAND() * 5000) AS INT64) AS STRING)) AS card_id,
    ROUND(5 + 100 * POW(RAND(), 3), 2) AS amount,
    TIMESTAMP_ADD(TIMESTAMP('2026-11-01'),
                  INTERVAL CAST(FLOOR(RAND() * 30 * 24 * 3600) AS INT64) SECOND) AS txn_ts,
    'AU' AS country,
    ['grocery','fuel','restaurant','retail','travel'][OFFSET(CAST(FLOOR(RAND() * 5) AS INT64))] AS merchant_category,
    FALSE AS is_fraud
  FROM UNNEST(GENERATE_ARRAY(1, 200000))
),
compromised AS (
  SELECT
    CONCAT('card_', CAST(c AS STRING)) AS card_id,
    TIMESTAMP_ADD(TIMESTAMP('2026-11-01'),
                  INTERVAL CAST(FLOOR(RAND() * 29 * 24 * 3600) AS INT64) SECOND) AS start_ts
  FROM UNNEST(GENERATE_ARRAY(1, 60)) AS c
),
fraud AS (
  SELECT
    GENERATE_UUID(),
    k.card_id,
    ROUND(300 + RAND() * 1700, 2),
    TIMESTAMP_ADD(k.start_ts, INTERVAL CAST(FLOOR(RAND() * 600) AS INT64) SECOND),
    'NG',
    'electronics',
    TRUE
  FROM compromised k, UNNEST(GENERATE_ARRAY(1, 8))
)
SELECT * FROM normal
UNION ALL
SELECT * FROM fraud;
SQL


 And we will create a python file call fraud_detector.py


import sys
from pyspark.sql import SparkSession, Window, functions as F

bucket = sys.argv[1]
spark = SparkSession.builder.appName("mini-fraud-detector").getOrCreate()
spark.conf.set("temporaryGcsBucket", bucket)   # staging area for the BigQuery write

# READ
txns = (spark.read.format("bigquery")
        .option("table", "fraud.transactions")
        .load()
        .withColumn("ts_sec", F.col("txn_ts").cast("long")))

# FEATURES: what has this card done recently / historically?
by_card         = Window.partitionBy("card_id").orderBy("ts_sec")
last_10m        = by_card.rangeBetween(-600, 0)                          # past 10 minutes
history         = by_card.rowsBetween(Window.unboundedPreceding, -1)     # everything before now
country_history = (Window.partitionBy("card_id", "country").orderBy("ts_sec")
                   .rowsBetween(Window.unboundedPreceding, -1))

features = (txns
    .withColumn("txns_last_10m",    F.count("*").over(last_10m))
    .withColumn("prior_txns",       F.count("*").over(history))
    .withColumn("prior_avg_amount", F.avg("amount").over(history))
    .withColumn("prior_in_country", F.count("*").over(country_history)))

# RULES
velocity     = F.col("txns_last_10m") >= 3
amount_spike = ((F.col("prior_txns") >= 5) & (F.col("amount") > 100) &
                (F.col("amount") > 5 * F.col("prior_avg_amount")))
new_country  = (F.col("prior_txns") > 0) & (F.col("prior_in_country") == 0)

scored = (features
    .withColumn("risk_score",
                40 * velocity.cast("int") + 30 * amount_spike.cast("int") + 30 * new_country.cast("int"))
    .withColumn("reasons",
                F.concat_ws(",",
                            F.when(velocity, "velocity"),
                            F.when(amount_spike, "amount_spike"),
                            F.when(new_country, "new_country"))))

# ALERTS = score of 60 or more
alerts = (scored.filter(F.col("risk_score") >= 60)
          .select("txn_id", "card_id", "amount", "country", "merchant_category",
                  "txn_ts", "risk_score", "reasons"))

alerts.orderBy(F.desc("risk_score")).show(10, truncate=False)   # quick look in the terminal

# WRITE
(alerts.write.format("bigquery")
    .option("table", "fraud.alerts")
    .mode("overwrite")
    .save())

And finally it is time to submit our job:-



gcloud dataproc batches submit pyspark fraud_detector.py \
  --region=us-central1 \
  --deps-bucket=$BUCKET \
  --properties=dataproc.tier=standard,spark.dynamicAllocation.maxExecutors=4 \
  -- $BUCKET


And examining out alerts table 


bq query --use_legacy_sql=false '
SELECT card_id, COUNT(*) AS alerts, ROUND(SUM(amount),2) AS amount_at_risk, MIN(txn_ts) AS first_alert
FROM fraud.alerts
GROUP BY card_id
ORDER BY amount_at_risk DESC
LIMIT 10'



And this is the output from our table :-


Comments

Popular posts from this blog

NodeJS: Error: spawn EINVAL in window for node version 20.20 and 18.20

android build issue with version compatibility with agp and hilt : An exception occurred applying plugin request [id: 'com.google.dagger.hilt.android', version: '2.52']