10 Python Exercises for Finance and Production Support Engineers

·

·

Reading time:

8 minutes

Ten Python exercises built around the work production support and platform engineers actually do in banks: parsing logs and FIX messages, handling money correctly, reconciling positions, and writing small tools that fail safely. Each one has an expected output and a hidden solution, so try it yourself first.

Originally published February 2021, rewritten November 2026. All solutions use only the Python standard library and need Python 3.9 or later.

How to use this page

  • Copy the input into a file or a Python shell and write your solution.
  • Compare against the expected output.
  • Only then open Show solution. Read the note under it: that’s usually what interviewers probe.

Exercises


Level 1: Warm-up

1. Count log levels

Given some application log lines, count how many are INFO, WARN and ERROR.

Input:

lines = [
    "2026-11-17 08:00:01 INFO  Pricing engine started",
    "2026-11-17 08:00:05 WARN  Market data feed slow: 450ms",
    "2026-11-17 08:01:12 ERROR Order ORD-1001 rejected: price out of range",
    "2026-11-17 08:01:13 INFO  Order ORD-1002 filled",
    "2026-11-17 08:02:40 ERROR Order ORD-1003 rejected: unknown counterparty",
]

Expected output:

INFO  2
WARN  1
ERROR 2

Hint: line.split() gives you the fields; the level is the third one. Look at collections.Counter.

Show solution
from collections import Counter

counts = Counter(line.split()[2] for line in lines)

for level in ("INFO", "WARN", "ERROR"):
    print(f"{level:<5} {counts[level]}")

Looking up counts["DEBUG"] returns 0 instead of raising a KeyError, which is why Counter is nicer than a plain dict here. For a real multi-gigabyte log, loop over the open file line by line instead of building a list.

2. Parse a FIX message

Turn a FIX message into a dictionary of tag to value, then print a readable summary. Tag 11 is the order ID, 55 the symbol, 54 the side (1 = buy, 2 = sell), 38 the quantity and 44 the price. Real FIX uses the SOH character (\x01) as a delimiter; logs often show it as |.

Input:

msg = "8=FIX.4.4|35=D|11=ORD-1001|55=VOD.L|54=1|38=5000|40=2|44=72.15|"

Expected output:

ORD-1001: BUY 5,000 VOD.L @ 72.15

Hint: Split on the delimiter, then split each field on the first = only.

Show solution
def parse_fix(msg, delim="|"):
    fields = msg.strip(delim).split(delim)
    return dict(f.split("=", 1) for f in fields if f)

f = parse_fix(msg)
side = {"1": "BUY", "2": "SELL"}.get(f["54"], "UNKNOWN")
print(f"{f['11']}: {side} {int(f['38']):,} {f['55']} @ {f['44']}")

split("=", 1) matters: some FIX values (such as free-text tag 58) can contain an equals sign. Note also that a dict keeps only the last value for repeating tags, which real FIX repeating groups use.

3. Money without floating-point errors

Show why floats are wrong for money, then calculate the notional of a bond trade correctly: 1,000,000 nominal at a price of 99.875 (bond prices are quoted per 100 nominal), rounded to 2 decimal places.

Expected output:

0.30000000000000004
2.67
Notional: 998,750.00
Rounded:  2.68

Hint: Use decimal.Decimal, created from strings rather than floats, and quantize to round.

Show solution
from decimal import Decimal, ROUND_HALF_UP

print(0.1 + 0.2)          # not 0.3
print(round(2.675, 2))    # 2.67, because 2.675 is really 2.67499999... as a float

nominal = Decimal("1000000")
price = Decimal("99.875")
notional = (nominal * price / 100).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)

print(f"Notional: {notional:,}")
print(f"Rounded:  {Decimal('2.675').quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)}")

This is one of the most common Python questions in finance interviews. Always build Decimals from strings: Decimal(2.675) inherits the float error. Python’s built-in round also uses banker’s rounding (half to even), which may not match your firm’s convention.


Level 2: Working with data

4. Reconcile positions

Compare our positions with the counterparty’s and report every break: positions missing on either side, and quantity differences larger than a tolerance of 100.

Input:

ours   = {"POS-1": 1_000_000, "POS-2": 250_000, "POS-3": 75_000}
theirs = {"POS-1": 1_000_000, "POS-2": 249_500, "POS-4": 10_000}

Expected output:

('POS-2', 'quantity mismatch', 250000, 249500)
('POS-3', 'missing at counterparty', 75000, None)
('POS-4', 'missing in our books', None, 10000)

Hint: The union of both key sets (a.keys() | b.keys()) gives every position you need to check.

Show solution
def reconcile(a, b, tol=0):
    breaks = []
    for key in sorted(a.keys() | b.keys()):
        if key not in b:
            breaks.append((key, "missing at counterparty", a[key], None))
        elif key not in a:
            breaks.append((key, "missing in our books", None, b[key]))
        elif abs(a[key] - b[key]) > tol:
            breaks.append((key, "quantity mismatch", a[key], b[key]))
    return breaks

for brk in reconcile(ours, theirs, tol=100):
    print(brk)

For large files, the pandas version is a merge with how="outer", indicator=True. Mention both in an interview: plain Python shows you understand the logic, pandas shows you know the right tool at scale.

5. Calculate VWAP

Calculate the volume-weighted average price (VWAP) of a list of executions, given as (price, quantity) pairs. VWAP = sum of price × quantity, divided by total quantity.

Input:

trades = [(101.20, 500), (101.25, 1200), (101.10, 300), (101.30, 1000)]

Expected output:

VWAP: 101.2433

Hint: Two generator expressions inside sum() keep this to a few lines.

Show solution
total_value = sum(price * qty for price, qty in trades)
total_qty = sum(qty for _, qty in trades)
vwap = total_value / total_qty

print(f"VWAP: {vwap:.4f}")

Be ready for the follow-up: what if trades is empty? Guard against dividing by zero. VWAP is also the benchmark for the VWAP execution algorithm, so you can link it back to trading.

6. Summarise trades by counterparty

Read a CSV of trades and print, for each counterparty, the number of trades and the total notional (quantity × price), sorted by notional, highest first.

Input:

trade_id,counterparty,side,quantity,price
T1,BARC,BUY,1000,101.50
T2,HSBC,SELL,500,101.55
T3,BARC,SELL,200,101.60
T4,JPM,BUY,1500,101.45
T5,HSBC,BUY,700,101.50

Expected output:

JPM     1   152,175.00
HSBC    2   121,825.00
BARC    2   121,820.00

Hint: csv.DictReader gives you each row as a dict. collections.defaultdict saves you checking whether a counterparty already exists.

Show solution
import csv
from collections import defaultdict

summary = defaultdict(lambda: {"trades": 0, "notional": 0.0})

with open("trades.csv", newline="") as f:
    for row in csv.DictReader(f):
        s = summary[row["counterparty"]]
        s["trades"] += 1
        s["notional"] += int(row["quantity"]) * float(row["price"])

ranked = sorted(summary.items(), key=lambda kv: kv[1]["notional"], reverse=True)
for cp, s in ranked:
    print(f"{cp:<5} {s['trades']:>3} {s['notional']:>12,.2f}")

Floats are fine for a quick report like this; for anything booked or reported to clients, use Decimal as in exercise 3.

7. Flag trades outside market hours

Trade timestamps arrive in UTC. Convert each to London time and flag any outside the 08:00–16:30 trading session.

Input:

timestamps = ["2026-11-17T07:45:00Z", "2026-11-17T08:30:00Z", "2026-11-17T16:45:00Z"]

Expected output:

07:45 GMT OUTSIDE HOURS
08:30 GMT OK
16:45 GMT OUTSIDE HOURS

Hint: Use zoneinfo.ZoneInfo("Europe/London") and astimezone(). Older Pythons can’t parse the trailing Z, so replace it with +00:00.

Show solution
from datetime import datetime, time
from zoneinfo import ZoneInfo

LONDON = ZoneInfo("Europe/London")
OPEN, CLOSE = time(8, 0), time(16, 30)

for ts in timestamps:
    utc = datetime.fromisoformat(ts.replace("Z", "+00:00"))
    local = utc.astimezone(LONDON)
    status = "OK" if OPEN <= local.time() < CLOSE else "OUTSIDE HOURS"
    print(local.strftime("%H:%M %Z"), status)

Never hard-code a UTC offset: London is UTC+0 in winter and UTC+1 in summer, and the UK, US and EU change clocks on different dates. That mismatch breaks schedulers twice a year.


Level 3: Ops tooling

8. Validate an ISIN

An ISIN identifies a security: 2-letter country code, 9 alphanumeric characters and a check digit. Validate ISINs using the check-digit rule: convert letters to numbers (A=10 … Z=35), then apply the Luhn algorithm to the result.

Input:

isins = ["US0378331005", "GB0002634946", "GB00BYZJ7G42", "US0378331006", "XX123"]

Expected output:

US0378331005 True
GB0002634946 True
GB00BYZJ7G42 True
US0378331006 False
XX123 False

Hint: int(c, 36) converts both digits and letters in one go. In Luhn, starting from the rightmost digit, double every other digit and subtract 9 from any result over 9.

Show solution
def is_valid_isin(isin):
    isin = isin.strip().upper()
    if (len(isin) != 12 or not isin.isalnum()
            or not isin[:2].isalpha() or not isin[-1].isdigit()):
        return False

    digits = "".join(str(int(c, 36)) for c in isin[:-1])
    total = 0
    for i, d in enumerate(reversed(digits)):
        n = int(d)
        if i % 2 == 0:          # double every other digit from the right
            n *= 2
            if n > 9:
                n -= 9
        total += n

    check = (10 - total % 10) % 10
    return check == int(isin[-1])

for isin in isins:
    print(isin, is_valid_isin(isin))

Validating identifiers before they reach the booking system stops a whole class of trade breaks. Interviewers like candidates who validate input at the edge.

9. Retry with exponential backoff

Write a retry decorator that re-runs a function when it raises a given exception, waiting twice as long after each failure, and gives up after N attempts. Test it on a fake price feed that fails twice and then succeeds.

Input:

calls = {"n": 0}

@retry(times=4, base_delay=0.01, exceptions=(ConnectionError,))
def fetch_prices():
    calls["n"] += 1
    if calls["n"] < 3:
        raise ConnectionError("feed unavailable")
    return {"VOD.L": 72.15}

print(fetch_prices())

Expected output:

attempt 1 failed (feed unavailable); retrying in 0.01s
attempt 2 failed (feed unavailable); retrying in 0.02s
{'VOD.L': 72.15}

Hint: A decorator with arguments is a function that returns a decorator. Use functools.wraps to keep the wrapped function’s name.

Show solution
import functools
import time

def retry(times=3, base_delay=1.0, exceptions=(Exception,)):
    def decorator(fn):
        @functools.wraps(fn)
        def wrapper(*args, **kwargs):
            for attempt in range(1, times + 1):
                try:
                    return fn(*args, **kwargs)
                except exceptions as e:
                    if attempt == times:
                        raise
                    delay = base_delay * 2 ** (attempt - 1)
                    print(f"attempt {attempt} failed ({e}); retrying in {delay}s")
                    time.sleep(delay)
        return wrapper
    return decorator

Only retry errors that are worth retrying, like timeouts or dropped connections. Never blindly retry something like sending an order: if the first attempt actually succeeded, you’ve just traded twice. That’s the idempotency question interviewers often follow up with.

10. Concurrent health check

Check several services at once and exit with code 1 if any are down, so a scheduler or monitoring tool can alert. Here a dictionary simulates each service’s response time; anything over 2 seconds counts as a timeout.

Input:

SERVICES = {"pricing": 0.2, "oms": 0.1, "risk": 2.5, "booking": 0.3}

Expected output:

pricing  UP    200ms
oms      UP    100ms
risk     DOWN  timeout
booking  UP    300ms
exit code: 1

Hint: concurrent.futures.ThreadPoolExecutor runs I/O-bound checks in parallel. pool.map keeps results in input order.

Show solution
import sys
from concurrent.futures import ThreadPoolExecutor

def check(name):
    latency = SERVICES[name]            # in real life: requests.get(url, timeout=2)
    if latency > 2:
        return name, "DOWN", "timeout"
    return name, "UP", f"{int(latency * 1000)}ms"

with ThreadPoolExecutor(max_workers=4) as pool:
    results = list(pool.map(check, SERVICES))

for name, status, detail in results:
    print(f"{name:<8} {status:<5} {detail}")

failed = [r for r in results if r[1] != "UP"]
print(f"exit code: {1 if failed else 0}")
sys.exit(1 if failed else 0)

Threads suit this because the work is waiting on the network, not using CPU (the GIL is released while waiting). Always set a timeout on real HTTP calls: a check that hangs forever is worse than one that fails.


My original 2021 exercises

These are the screenshots from the first version of this page, kept for reference.

Keep going

Rakesh Kadukutty

Senior Production Support Engineer in London with 10+ years supporting Fixed Income and FX trading systems at BNP Paribas and Tradeweb.

About LinkedIn

Get the daily brief

One fintech story every morning, with the interview angle. Free, straight to your inbox.