Sub topic 8
What an alert contains and when it is created
This chapter assumes you know what a scenario and its parameters are, and that a rule scans transactions over a lookback window. Here we look at the step after evaluation: the moment a rule's result becomes an alert record, and what that record holds.
When an alert is created
A rule does not create an alert while it reads data. It reads transactions, groups them, and tests a condition. An alert is created only when the condition is true for a group of transactions. In the structuring scenario, the condition is that a customer has at least min_count cash deposits between floor and ceiling inside the lookback window.
Two timing points matter:
- Evaluation time. In a batch run, alerts appear when the job finishes, for example overnight. In near-real-time evaluation, an alert can appear moments after the transaction that completed the pattern.
- Trigger point. The alert is created when the count first reaches the threshold. A fourth qualifying deposit does not change the fact that the rule already fired.
What an alert record contains
An alert is a data record. Its job is to let an analyst see why the rule fired without rerunning the rule. A useful alert holds these fields:
| Field | Purpose | Example |
|---|---|---|
| Customer identifier | Who the alert is about | `C1` |
| Scenario name | Which rule fired | `structuring_cash` |
| Window start and end | The period examined | 2 March to 5 March |
| Transaction count | How many transactions matched | 3 |
| Total amount | Combined value of matches | 28500 |
| Supporting transactions | Links to the matching records | three deposit IDs |
The example code in this tutorial stores the first six fields and keeps the matching transactions in memory as hits. A production system would also store a reference to each matching transaction, the parameter values in force, and the run date. Storing the parameters matters because thresholds change over time. Without them, nobody can explain later why a given alert fired.
Reading the alert code
This is the structuring rule from the earlier chapters. Focus on the block that builds the alert.
from collections import defaultdict
from datetime import timedelta
def structuring_alerts(transactions, params):
"""Alert when a customer makes several cash deposits just under a limit
inside a rolling window."""
window = timedelta(days=params["lookback_days"])
by_customer = defaultdict(list)
for t in transactions:
if t["type"] == "cash_deposit" and params["floor"] <= t["amount"] < params["ceiling"]:
by_customer[t["customer_id"]].append(t)
alerts = []
for customer_id, txns in by_customer.items():
txns.sort(key=lambda t: t["timestamp"])
start = 0
for end, current in enumerate(txns):
while current["timestamp"] - txns[start]["timestamp"] > window:
start += 1
hits = txns[start:end + 1]
if len(hits) >= params["min_count"]:
alerts.append({
"customer_id": customer_id,
"scenario": "structuring_cash",
"window_start": hits[0]["timestamp"],
"window_end": hits[-1]["timestamp"],
"txn_count": len(hits),
"total_amount": sum(t["amount"] for t in hits),
})
break # one alert per customer per run
return alertsThe hits slice is the evidence. Its first and last timestamps become the window, its length becomes the count, and its amounts are summed. The break stops the loop after the first alert for a customer in this run.
Running it
from datetime import datetime
PARAMS = {
"retail": {"lookback_days": 7, "min_count": 3, "floor": 8000, "ceiling": 10000},
}
transactions = [
{"customer_id": "C1", "type": "cash_deposit", "amount": 9500, "timestamp": datetime(2026, 3, 2, 10, 0)},
{"customer_id": "C1", "type": "cash_deposit", "amount": 9200, "timestamp": datetime(2026, 3, 3, 15, 30)},
{"customer_id": "C1", "type": "cash_deposit", "amount": 9800, "timestamp": datetime(2026, 3, 5, 9, 15)},
{"customer_id": "C2", "type": "cash_deposit", "amount": 9500, "timestamp": datetime(2026, 3, 2, 11, 0)},
]
alerts = structuring_alerts(transactions, PARAMS["retail"])
for a in alerts:
print(a["customer_id"], a["txn_count"], a["total_amount"])
# C1 3 28500Customer C1 has three qualifying deposits in three days, so one alert is created. Customer C2 has one deposit, so the rule produces nothing for them.
Common errors
- Duplicate alerts. Without the
break, or an equivalent check against existing alerts, a customer could trigger a new alert on every later deposit in the same window. - Missing evidence. An alert with only a customer ID and a score forces analysts to search for the transactions themselves.
- Unrecorded parameters. If thresholds change and the alert does not store the values used, the alert cannot be reproduced.
- Boundary mistakes. The code uses
floor <= amount < ceiling. A deposit of exactly 10000 is excluded. Check that this matches the intended policy.
Exercise
In the example run, a fourth qualifying deposit by C1 arrives on 6 March and the rule runs again over all four deposits. Based on the code, how many alerts does C1 produce in that run, and what are the txn_count and window_start values?
Show answer
One alert, because of the break. The count reaches 3 at the third deposit, so the alert is built from hits at that point: txn_count is 3 and window_start is 2 March 10:00. The fourth deposit is never added to the alert in this run.
Exercise
Name two fields beyond those in the code's alert dictionary that a production alert should store, and say why each is needed.
Show answer
Examples: the IDs of the supporting transactions, so analysts can open the exact deposits; and the parameter values used, so the alert can be explained after thresholds change. A run date or scenario version is also acceptable.