Skip to content
LeetQuant
QD10 System Design and Code Review

QD10 · System Design and Code Review · Lesson 4 of 5

Code Review

What to check in a review (correctness, edge cases, concurrency, error handling, performance, readability), in what order, and a full review of a short buggy position-tracking function with each issue reproduced.

16 min

Why firms test it

Many quant developer loops include a review exercise: here is 30 lines of code, what is wrong with it? It tests the habit that matters most in production trading code, which is finding the bug before it runs with real positions. Interviewers score coverage (did you find the serious issues?), prioritisation (did you lead with the one that loses money, not the variable name?) and fixes (can you say exactly what to change?).

A review order that finds the important bugs first

PassQuestions to ask
1. IntentWhat is this supposed to do? Does the docstring or name match the behaviour? What are the inputs' units and sign conventions?
2. CorrectnessTrace one normal input by hand. Is every formula right? Are the boundary conditions of loops and slices right?
3. Edge casesEmpty input, one element, zero, negative values, duplicates, NaN, very large values, unsorted input, a position going flat or flipping sign
4. State and concurrencyShared mutable state, mutable default arguments, globals, read-modify-write sequences without a lock, iteration over a container being mutated
5. Error handlingAre failures raised, logged or swallowed? Does a bare except hide bugs? Are resources closed on every path?
6. PerformanceComplexity in the input size, work inside loops that could move outside, copies of large data, I/O in a hot loop
7. Readability and testsNames, magic numbers, dead code, and whether a test would have caught each bug found above

Report findings ranked by severity: wrong results or lost money, then crashes, then performance, then style. A review that leads with formatting and misses a sign error has failed.

Things that are wrong more often than you expect

  • Sign conventions. Is a sell a negative quantity or a positive quantity with a side flag? Mixing them silently inverts positions.
  • Off-by-one in windows. Rolling windows that drop the last element, or include the current bar in a feature meant to use only the past (look-ahead).
  • Integer and float handling. Money as binary floats compared with ==; integer division where a ratio was intended.
  • Mutable defaults in Python. def f(x, cache={}) creates one dictionary when the function is defined and shares it across every call.
  • Time. Naive versus timezone-aware timestamps, exchange local time versus UTC, daylight-saving gaps.

Worked example

review a position tracker

Review this function. It is meant to return each symbol's net position and average entry price from a list of fills, where a positive qty is a buy and a negative qty a sell.

def position_summary(fills, positions={}):
    """Net position and average entry price per symbol."""
    for f in fills:
        sym, qty, px = f["sym"], f["qty"], f["px"]  # qty > 0 buy, < 0 sell
        pos, avg = positions.get(sym, (0, 0.0))
        new_pos = pos + qty
        avg = (avg * pos + px * qty) / new_pos
        positions[sym] = (new_pos, avg)
    return positions
Show solution

Trace a normal input first. Buy 100 at 10, buy 100 at 12, sell 50 at 20. After the two buys the position is 200 at an average of 11, which is right. Then run the code to check the rest and probe the edge cases:

day1 = [
    {"sym": "XYZ", "qty": 100, "px": 10.0},
    {"sym": "XYZ", "qty": 100, "px": 12.0},
    {"sym": "XYZ", "qty": -50, "px": 20.0},
]
print(position_summary(day1))
print(position_summary([{"sym": "ABC", "qty": 10, "px": 5.0}]))
try:
    position_summary([{"sym": "XYZ", "qty": -150, "px": 20.0}])
except ZeroDivisionError as e:
    print("ZeroDivisionError:", e)
{'XYZ': (150, 8.0)}
{'XYZ': (150, 8.0), 'ABC': (10, 5.0)}
ZeroDivisionError: float division by zero

Findings, most severe first:

  1. Wrong average price after a sell (wrong results). Selling 50 at 20 moved the average entry from 11 to (11×200−20×50)/150=8(11 \times 200 - 20 \times 50)/150 = 8. Reducing a position should leave the entry price at 11; only adding to the position should re-average it, and crossing through zero should start a new average at the fill price. Every P&L figure computed from this average is wrong.
  2. Mutable default argument (state leaks between calls). positions={} is created once, so the second call, about a different book, returned XYZ from the first call. In a long-running service this silently merges accounts or days. It is also shared across threads, so concurrent calls race on the read-modify-write of positions[sym].
  3. Crash when the position goes flat. Selling the remaining 150 makes new_pos zero and divides by it. Going flat is the most common event in trading, not an edge case.
  4. Returns internal state. Even with the default fixed, returning the dictionary the function mutates invites callers to modify it. Build and return a new dictionary per call.
  5. No validation. A zero-quantity fill or a missing key fails late or not at all. Reject bad input at the boundary with a clear error.

A fixed version:

def position_summary(fills):
    """Net position and average entry price per symbol.

    qty > 0 is a buy, qty < 0 a sell. Reducing a position keeps the
    average entry price; flipping through zero starts a new one at px.
    """
    positions: dict[str, tuple[int, float]] = {}
    for f in fills:
        sym, qty, px = f["sym"], f["qty"], f["px"]
        if qty == 0:
            raise ValueError(f"zero-quantity fill for {sym}")
        pos, avg = positions.get(sym, (0, 0.0))
        new_pos = pos + qty
        if new_pos == 0:
            avg = 0.0                          # flat: no entry price
        elif pos == 0 or (pos > 0) != (new_pos > 0):
            avg = px                           # opened or flipped
        elif (pos > 0) == (qty > 0):
            avg = (avg * pos + px * qty) / new_pos  # added to the position
        # else: reduced, average entry unchanged
        positions[sym] = (new_pos, avg)
    return positions

Run on the same cases, plus going flat and flipping short:

print(position_summary(fills))
print(position_summary([{"sym": "ABC", "qty": 10, "px": 5.0}]))
print(position_summary(fills + [{"sym": "XYZ", "qty": -150, "px": 20.0}]))
print(position_summary(fills + [{"sym": "XYZ", "qty": -200, "px": 20.0}]))
{'XYZ': (150, 11.0)}
{'ABC': (10, 5.0)}
{'XYZ': (0, 0.0)}
{'XYZ': (-50, 20.0)}

(Here fills is the same three fills as day1.) The average stays at 11 after the partial sell, calls no longer share state, flat is handled, and selling 200 from long 150 opens a short of 50 at 20. Each of these four lines is a unit test you would add with the fix.

Knowledge check

In a review you find: a misleading variable name, an O(n^2) loop over a list of 1,000 items run once a day, and a sign error that books sells as buys. In what order should you report them?

Knowledge check

What does this print?

def log_fill(fill, seen=[]):
    seen.append(fill)
    return len(seen)

print(log_fill("a"), log_fill("b"), log_fill("c", []))

Knowledge check

Two threads call a function that does positions[sym] = positions.get(sym, 0) + qty on a shared dictionary. Each line runs without raising. What is the risk?

Key takeaways

  • Review in passes: intent, correctness, edge cases, state and concurrency, error handling, performance, readability.
  • Trace one normal input by hand, then run the edge cases: empty, zero, flat, sign flip, duplicates.
  • Rank findings by consequence: wrong results first, crashes next, then performance and style.
  • Give each finding a triggering input, its effect and a concrete fix, and turn it into a test.
  • Watch for mutable defaults, shared state without locks, sign conventions and window boundaries; they cause most real trading-code bugs.

Practice problems

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).