Rebuild a Seven-Day Account Exposure Report from Trade Feeds
SQL & DataAuto-graded · 16 test casesLast updated
Deduplicate late-arriving trade versions, filter by status, window and KYC, then aggregate per account and day into exposure, utilization and breach figures.
Daily Exposure Report
A risk team receives trade records from an upstream feed that can send the same trade more than once. Corrections and cancellations arrive later as new rows. You are given four tables as lists of dictionaries and must build a per-account, per-day exposure summary.
Write compute_daily_exposure(customers, accounts, trades, account_limits).
Input tables
customers: rows withcust_id,cust_name,kyc_status,country.accounts: rows withacct_id,cust_id,product,opened_at.trades: rows withtrade_id,acct_id,trade_dt("YYYY-MM-DD"),asset_class,notional_usd,side,status,ingested_at("YYYY-MM-DD HH:MM:SS").account_limits: rows withacct_id,daily_limit_usd.
Rules
Apply them in this order:
- Keep the latest version of each trade. Among all rows sharing a
trade_id, keep only the one with the greatestingested_at. If several rows share that greatest timestamp, keep the one that appears last in the input list. Do this over the entiretradeslist, before any other filtering. - Drop cancelled trades. Remove any surviving trade whose
statusis"CANCELED". - Date window. Keep only trades with
trade_dtfrom"2025-08-25"to"2025-09-01", both inclusive. - KYC. Keep only trades whose account belongs to a customer with
kyc_status == "PASS". A trade whose account is not inaccounts, or whose customer is not incustomers, is dropped. - Limits. Keep only trades whose account has an entry in
account_limits. Accounts without a limit do not appear in the output.
Output
Group the remaining trades by (acct_id, trade_dt). Return one dictionary per group with these keys:
acct_idtrade_dtgross_notional: the sum ofabs(notional_usd).net_notional: the sum of signed amounts, where a trade with side"BUY"contributes+abs(notional_usd)and any other side contributes-abs(notional_usd).limit_utilization:gross_notional / daily_limit_usd, using true division.breach_flag:Trueiflimit_utilization > 1.0, otherwiseFalse. A utilization of exactly 1 is not a breach.
Return the list sorted by acct_id ascending, then trade_dt ascending. Days with no qualifying trades produce no row. If nothing qualifies, return an empty list.
Constraints
- Each input list has at most 10^5 rows.
notional_usdis an integer and may be negative. Only its absolute value is used.daily_limit_usdis a positive number.- Each
acct_idappears at most once inaccount_limits, and eachcust_idandacct_idat most once incustomersandaccounts. - Date and timestamp strings are zero-padded and in the formats shown, so string comparison matches chronological order.
Examples
Example 1
Input: compute_daily_exposure([{'cust_id': 101, 'cust_name': 'Alpha LLC', 'kyc_status': 'PASS', 'country': 'US'}, {'cust_id': 102, 'cust_name': 'Beta SA', 'kyc_status': 'PASS', 'country': 'FR'}, {'cust_id': 103, 'cust_name': 'Gamma AG', 'kyc_status': 'REVIEW', 'country': 'DE'}], [{'acct_id': 5001, 'cust_id': 101, 'product': 'MARGIN', 'opened_at': '2023-05-10 09:00:00'}, {'acct_id': 5002, 'cust_id': 102, 'product': 'CASH', 'opened_at': '2024-11-01 10:00:00'}], [{'trade_id': 'T1', 'acct_id': 5001, 'trade_dt': '2025-08-26', 'asset_class': 'EQ', 'notional_usd': 1000000, 'side': 'BUY', 'status': 'BOOKED', 'ingested_at': '2025-08-26 12:00:00'}, {'trade_id': 'T1', 'acct_id': 5001, 'trade_dt': '2025-08-26', 'asset_class': 'EQ', 'notional_usd': 1000000, 'side': 'BUY', 'status': 'CANCELED', 'ingested_at': '2025-08-27 08:00:00'}, {'trade_id': 'T2', 'acct_id': 5001, 'trade_dt': '2025-08-28', 'asset_class': 'FI', 'notional_usd': 2500000, 'side': 'SELL', 'status': 'BOOKED', 'ingested_at': '2025-08-28 11:30:00'}, {'trade_id': 'T3', 'acct_id': 5002, 'trade_dt': '2025-08-30', 'asset_class': 'EQ', 'notional_usd': 750000, 'side': 'BUY', 'status': 'BOOKED', 'ingested_at': '2025-09-01 02:00:00'}], [{'acct_id': 5001, 'daily_limit_usd': 2000000}, {'acct_id': 5002, 'daily_limit_usd': 1000000}])
Output: [{'acct_id': 5001, 'trade_dt': '2025-08-28', 'gross_notional': 2500000, 'net_notional': -2500000, 'limit_utilization': 1.25, 'breach_flag': True}, {'acct_id': 5002, 'trade_dt': '2025-08-30', 'gross_notional': 750000, 'net_notional': 750000, 'limit_utilization': 0.75, 'breach_flag': False}]
Example 2
Input: compute_daily_exposure([{'cust_id': 1, 'cust_name': 'A', 'kyc_status': 'PASS', 'country': 'US'}], [{'acct_id': 10, 'cust_id': 1, 'product': 'MARGIN', 'opened_at': '2020-01-01 00:00:00'}], [{'trade_id': 'x', 'acct_id': 10, 'trade_dt': '2025-08-25', 'asset_class': 'EQ', 'notional_usd': 100, 'side': 'BUY', 'status': 'BOOKED', 'ingested_at': '2025-09-01 01:00:00'}], [{'acct_id': 10, 'daily_limit_usd': 100}])
Output: [{'acct_id': 10, 'trade_dt': '2025-08-25', 'gross_notional': 100, 'net_notional': 100, 'limit_utilization': 1, 'breach_flag': False}]
Example 3
Input: compute_daily_exposure([{'cust_id': 1, 'cust_name': 'A', 'kyc_status': 'PASS', 'country': 'US'}, {'cust_id': 2, 'cust_name': 'B', 'kyc_status': 'REVIEW', 'country': 'GB'}], [{'acct_id': 10, 'cust_id': 1, 'product': 'CASH', 'opened_at': '2020-01-01 00:00:00'}, {'acct_id': 20, 'cust_id': 2, 'product': 'CASH', 'opened_at': '2020-01-01 00:00:00'}], [{'trade_id': 'a', 'acct_id': 10, 'trade_dt': '2025-08-31', 'asset_class': 'EQ', 'notional_usd': -300, 'side': 'SELL', 'status': 'BOOKED', 'ingested_at': '2025-08-31 10:00:00'}, {'trade_id': 'b', 'acct_id': 20, 'trade_dt': '2025-08-31', 'asset_class': 'EQ', 'notional_usd': 900, 'side': 'BUY', 'status': 'BOOKED', 'ingested_at': '2025-08-31 10:00:00'}], [{'acct_id': 10, 'daily_limit_usd': 500}, {'acct_id': 20, 'daily_limit_usd': 1000}])
Output: [{'acct_id': 10, 'trade_dt': '2025-08-31', 'gross_notional': 300, 'net_notional': -300, 'limit_utilization': 0.6, 'breach_flag': False}]
Hints
Hint 1
Reduce the trades to one record per trade_id before applying any other filter. A cancelled version can be the newest one, and filtering it out too early would let an older booked version survive.
Hint 2
Precompute lookups: the set of customers with PASS status, the set of accounts owned by them, and a dict from account to daily limit. Then each trade needs only constant-time checks.
Hint 3
Accumulate gross and net sums in a dict keyed by (acct_id, trade_dt), compute utilization once at the end, and sort by (acct_id, trade_dt). Treat any side other than BUY as negative.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The task is an ordered pipeline, and the order matters most.
- Deduplicate first. Scan all trades once and keep, for each
trade_id, the row with the greatestingested_at. Using>=while scanning means that on a timestamp tie the later row in the input wins, which matches the stated rule. This is the dictionary equivalent ofROW_NUMBER() OVER (PARTITION BY trade_id ORDER BY ingested_at DESC). - Then filter. On the surviving rows, drop
CANCELEDtrades, drop those outside the date window, and drop those whose account is not KYC-approved or has no limit. The KYC check uses prebuilt sets, so each check is O(1). - Aggregate. For each
(acct_id, trade_dt)key, accumulate gross (the sum of absolute notionals) and net (BUY positive, anything else negative). - Finish. Divide gross by the account's limit to get utilization, set
breach_flagtoutilization > 1.0, and sort by(acct_id, trade_dt).
Why it is correct
- Deduplicating before the status filter is essential. If a trade was booked and later cancelled, the cancelled version is the newest. After deduplication only that version remains, and it is then removed. Filtering cancellations first would leave the older booked version alive and count exposure that no longer exists.
- Deduplication runs over the full history, not just the window. A trade whose newer version has moved outside the window must not be counted through its stale in-window version.
- Late-arriving rows need no special handling, because the result depends only on the content of the input and not on when rows arrived. Re-running on the same input always gives the same output.
- Sorting the output makes the result deterministic.
Complexity
- Time: O(N + M log M), where N is the total number of input rows and M is the number of output groups, which is dominated by the final sort.
- Space: O(N) for the lookups, deduplicated trades and aggregates.
Reference solution
from typing import List, Dict
def compute_daily_exposure(customers: List[Dict], accounts: List[Dict], trades: List[Dict], account_limits: List[Dict]) -> List[Dict]:
window_start = "2025-08-25"
window_end = "2025-09-01"
kyc_ok_customers = {
c["cust_id"] for c in customers if c.get("kyc_status") == "PASS"
}
eligible_accounts = {
a["acct_id"] for a in accounts if a.get("cust_id") in kyc_ok_customers
}
limit_by_acct = {r["acct_id"]: r["daily_limit_usd"] for r in account_limits}
# Step 1: keep the latest ingested version of each trade (later row wins ties).
latest = {}
for row in trades:
prev = latest.get(row["trade_id"])
if prev is None or row["ingested_at"] >= prev["ingested_at"]:
latest[row["trade_id"]] = row
# Steps 2-5: filter and aggregate.
totals = {}
for row in latest.values():
acct = row["acct_id"]
day = row["trade_dt"]
if row.get("status") == "CANCELED":
continue
if not (window_start <= day <= window_end):
continue
if acct not in eligible_accounts or acct not in limit_by_acct:
continue
gross = abs(row["notional_usd"])
signed = gross if row.get("side") == "BUY" else -gross
acc = totals.setdefault((acct, day), [0, 0])
acc[0] += gross
acc[1] += signed
result = []
for (acct, day), (gross, net) in totals.items():
util = gross / limit_by_acct[acct]
result.append({
"acct_id": acct,
"trade_dt": day,
"gross_notional": gross,
"net_notional": net,
"limit_utilization": util,
"breach_flag": util > 1.0,
})
result.sort(key=lambda r: (r["acct_id"], r["trade_dt"]))
return result