E
edgecase
quant prep

Python Q&A

Questions a quant dev would actually ask. Solutions heavily commented.

23 items
0 of 23 mastered23 unseen
seniordesign

Design a Real-Time Position Tracker

Signal: Tests whether the candidate has thought about fills vs marks, average price, realized vs unrealized P&L. These differences cause real trading desk bugs.

Question

Design a class that tracks a long/short position across multiple fills, maintaining: net position, average entry price, realized P&L (from closed trades), and mark-to-market unrealized P&L given a current price. Be careful when positions flip sign.

What to watch for
  • Candidate uses 'average price' to mean different things in different parts of the code.
  • Candidate's logic breaks when a long position is flipped to short within a single fill.
  • Strong signal: candidate distinguishes 'average cost' (weighted history of opens) from 'VWAP' (volume-weighted).
Tap to reveal solution
middesign

Design a Tick → Bar Aggregator

Signal: Tests whether the candidate can write online / streaming code with state. Avoid materializing the full tick list.

Question

Implement a class that consumes a stream of (timestamp, price, volume) ticks and emits 1-minute OHLCV bars. Calls: aggregator.on_tick(ts, price, vol); aggregator.flush() to force-emit the current bar. The output should be a callback or generator.

What to watch for
  • Candidate buffers all ticks then re-aggregates — defeats the purpose.
  • Candidate's bar boundaries are off-by-one (does a tick at 09:30:00 belong to the 09:30 bar or 09:29 bar?).
  • Strong signal: candidate handles gaps (no ticks in a minute) explicitly — emit empty bar or skip?
Tap to reveal solution
juniorlanguage

Mutable Default Arguments

Signal: Catches whether a candidate has been bitten by a real Python bug. Senior devs answer instantly; juniors who've only done courses won't see it.

Question

What's wrong with this function? What does it print when called three times in a row: add_item('a'), add_item('b'), add_item('c')? def add_item(item, bucket=[]): bucket.append(item) return bucket

What to watch for
  • Candidate says 'each call gets a fresh list' — wrong; this is the trap.
  • Candidate spots the bug but can't explain *why* defaults are evaluated once at function-definition time.
  • Bonus signal: candidate suggests the `None` sentinel fix unprompted.
Tap to reveal solution
midfinance

Implement Black-Scholes

Signal: The single most-asked quant Python interview question. Tests math + numpy + ability to write clean numeric code.

Question

Implement the Black-Scholes price for a European call and put. Then add the five Greeks (delta, gamma, vega, theta, rho). Don't import any options libraries. You may use scipy.stats.norm.

What to watch for
  • Candidate forgets to express σ and T in consistent units (years).
  • Candidate's vega/theta are off by a factor of 100 or 365 (units convention slip).
  • Strong signal: candidate writes it vectorized so it handles arrays of S, K, T.
Tap to reveal solution
midlanguage

Write a Context Manager (Two Ways)

Signal: Tests whether the candidate can write `with` blocks that always clean up — table stakes for DB connections, file handles, position locks.

Question

Write a context manager that acquires a lock, yields, and releases on exit even if an exception fires. Do it both ways: with a class implementing `__enter__`/`__exit__`, and with `contextlib.contextmanager`.

What to watch for
  • Candidate's __exit__ returns True unconditionally — silently swallows exceptions.
  • Candidate forgets that contextmanager generators must yield exactly once.
  • Strong signal: candidate uses `try: yield finally: ...` correctly in the generator version.
Tap to reveal solution
midnumpy/pandas

Find the Bug — NaN Handling

Signal: Quant data has NaNs everywhere. If candidates can't reason about NaN propagation, their P&L will lie to them.

Question

Spot the bug: def mean_active_return(returns: pd.Series, benchmark: pd.Series) -> float: active = returns - benchmark return active.sum() / len(active) The series have NaN gaps (different stocks listed on different days). Fix it and explain.

What to watch for
  • Candidate says .mean() handles NaN. Half-right — pandas .mean() skips NaN by default, but the bug is the denominator len(), not the numerator.
  • Candidate doesn't see that sum() skips NaN but len() includes it.
  • Strong signal: candidate distinguishes pandas (skips NaN by default) from numpy (propagates NaN by default).
Tap to reveal solution
juniorlanguage

`is` vs `==`

Signal: Tests whether the candidate understands the difference between identity (same object) and equality (same value).

Question

Predict and explain the output: a = 256; b = 256 print(a is b) a = 257; b = 257 print(a is b) s1 = 'hello'; s2 = 'hello' print(s1 is s2) s1 = 'hello world!'; s2 = 'hello world!' print(s1 is s2)

What to watch for
  • Candidate confuses `is` and `==`.
  • Candidate doesn't know about CPython's small-integer cache (range −5 to 256).
  • Candidate uses `is` to compare values in their own code (a real-world bug).
Tap to reveal solution
midlanguage

Late Binding in Closures

Signal: Reveals whether the candidate has worked with callbacks, event handlers, or partial application — areas where this bug hides.

Question

Predict the output: funcs = [lambda: i for i in range(3)] print([f() for f in funcs]) Fix it.

What to watch for
  • Candidate predicts [0, 1, 2] — wrong, that's the classic mistake.
  • Candidate sees [2, 2, 2] but can't explain WHY.
  • Candidate's fix uses `i=i` default-argument binding without explaining what that does.
Tap to reveal solution
midfinance

Monte Carlo Price a European Call

Signal: Tests numpy fluency on a finance task that scales naturally. Also reveals whether the candidate knows variance reduction.

Question

Price a European call by Monte Carlo simulation under risk-neutral GBM. With N = 1,000,000 paths, how close to the Black-Scholes price should you expect to get? Show the price and a 95% confidence interval. Then apply ONE variance reduction technique.

What to watch for
  • Candidate forgets to discount the payoff back to today (e^{-rT}).
  • Candidate uses Python loop over paths instead of vectorizing.
  • Strong signal: candidate uses antithetic variates or control variates.
Tap to reveal solution
midlanguage

Write a Timer Decorator

Signal: Reveals whether the candidate understands functions are first-class and how to use `functools.wraps`.

Question

Write a decorator `@timed` that prints the function's name and how long it took. Make it preserve the function's docstring and name. Then make it work with `async def` functions too.

What to watch for
  • Candidate writes a decorator that loses __name__/__doc__ (forgets @functools.wraps).
  • Candidate doesn't know how to detect coroutines (asyncio.iscoroutinefunction).
  • Bonus signal: discusses time.perf_counter() vs time.time() (the former is monotonic).
Tap to reveal solution
seniornumpy/pandas

Rolling Correlation Matrix

Signal: Tests pandas fluency on a realistic risk-management computation. Senior devs vectorize this; juniors write triple-nested loops.

Question

Given a DataFrame `returns` with N stocks (columns) and T daily returns (rows), compute the rolling 60-day correlation matrix at every point in time. Result is a (T-59, N, N) ndarray.

What to watch for
  • Candidate writes nested loops over (t, i, j).
  • Candidate doesn't know pandas has rolling().corr() but doesn't know its output shape.
  • Strong signal: candidate notes the O(T·N²·W) cost and considers Welford-style online updates.
Tap to reveal solution
juniornumpy/pandas

Boolean Indexing vs np.where

Signal: Tests whether the candidate knows how to filter / branch in vectorized code.

Question

Given a 1D array `returns`, write three versions of this: produce a new array where positive returns are doubled and non-positive returns are left alone. Discuss which is most idiomatic.

What to watch for
  • Candidate writes a for-loop. Buzzer.
  • Candidate uses np.where but doesn't know it returns a NEW array (no in-place).
  • Strong signal: candidate notes np.where(condition) (one arg) is different from np.where(cond, x, y) (three arg).
Tap to reveal solution
juniorfinance

Annualized Sharpe Ratio

Signal: Basic but reveals whether the candidate knows the SQRT(252) scaling and what 'excess return' means.

Question

Given a numpy array of daily returns, compute the annualized Sharpe ratio assuming a risk-free rate of 2% per year. Don't use any pre-built libraries.

What to watch for
  • Candidate forgets the √252 annualization factor.
  • Candidate subtracts 0.02 from each daily return (wrong — that's 2% per DAY).
  • Strong signal: candidate notes the difference between geometric and arithmetic Sharpe.
Tap to reveal solution
midnumpy/pandas

Why Is This Pandas Code So Slow?

Signal: The single most common pandas anti-pattern. Either the candidate has fought this or they haven't.

Question

A teammate's pandas code processes 1M rows in 20 minutes. You suspect a bug. Find and fix it: def compute_pnl(df: pd.DataFrame) -> pd.DataFrame: df['pnl'] = df.apply( lambda row: row['qty'] * (row['mark'] - row['entry']), axis=1 ) return df

What to watch for
  • Candidate suggests using `.iterrows()` instead. Also wrong, same problem.
  • Candidate doesn't know that `.apply(axis=1)` calls the function once per row in Python land.
  • Strong signal: candidate also mentions dtype mismatches as a separate slowdown source.
Tap to reveal solution
midfinance

Implement EMA (Exponentially Weighted Moving Average)

Signal: EMA is the building block of half of all technical signals. Tests both the math and whether the candidate knows pandas' .ewm().

Question

Implement EMA over an array of prices, parameterized by a half-life (in periods). Do it three ways: pure-Python loop, numpy, and pandas. Discuss when you'd use each.

What to watch for
  • Candidate doesn't know what half-life means (the period over which weight drops to 1/2).
  • Candidate's numpy version has an O(n) loop — fine, just acknowledge that EMA is inherently sequential.
  • Strong signal: candidate notes EMA is a one-pole IIR filter, and mentions adjust=False in pandas.
Tap to reveal solution
midlanguage

Generators vs Lists

Signal: Whether the candidate reaches for generators when data is streamed/infinite, and whether they understand memory implications.

Question

You're given a CSV with 10GB of stock tick data — too big to fit in RAM. Write a function that returns the average price across the file. Show your work and explain memory behavior.

What to watch for
  • Candidate uses pandas.read_csv() with no chunking — out of memory.
  • Candidate uses a list comprehension to read every row into a list.
  • Candidate doesn't know about generator expressions / itertools / chunking.
  • Strong signal: candidate mentions `csv.DictReader` over `pd.read_csv` for streaming + correctness.
Tap to reveal solution
seniorfinance

Minimum Viable Backtester

Signal: Tests OOP design under finance constraints: lookahead bias, position sizing, transaction costs. Anyone with backtesting scars writes this differently than someone who's only read about it.

Question

Sketch the smallest possible event-driven backtester. It should take daily bars and a strategy function that decides target position based on history-to-date, then compute P&L net of transaction costs. Highlight the lookahead-bias guard.

What to watch for
  • Candidate's strategy function sees future data (uses df instead of df.iloc[:t+1]).
  • Candidate ignores transaction costs entirely.
  • Strong signal: candidate distinguishes 'signal time' vs 'execution time' (you signal on close, execute next open).
Tap to reveal solution
juniornumpy/pandas

Vectorize This Loop

Signal: The single highest-signal Python question for quant work. If they reach for a for-loop on a numpy array, they're not ready for production code.

Question

You have a numpy array `prices` of length 1,000,000. Compute the array of log-returns (i.e., log(p[i] / p[i-1]) for each i). Make it as fast as you can. Then time your version vs the naive for-loop.

What to watch for
  • Candidate writes a Python for-loop and is satisfied.
  • Candidate creates a temporary array unnecessarily.
  • Strong signal: candidate uses np.diff(np.log(prices)) — the cleanest one-liner.
Tap to reveal solution
midnumpy/pandas

Broadcasting Rules

Signal: Whether the candidate can read shape errors and design around them. Critical for any tensor work.

Question

You have a (1000, 50) matrix `returns` (1000 days × 50 stocks) and a (50,) vector `weights`. Write a one-liner that computes the portfolio return for each day. What about a (1000,) vector — does that work? Why or why not?

What to watch for
  • Candidate doesn't know `@` or `np.dot` for matrix multiplication.
  • Candidate manually loops over stocks (wrong direction of vectorization).
  • Candidate doesn't grasp WHY (50,) broadcasts but (1000,) doesn't.
Tap to reveal solution
midlanguage

Explain the GIL

Signal: Tests whether the candidate knows when threading vs multiprocessing actually helps — critical for any Python code that processes market data.

Question

Explain the GIL. Given a CPU-bound function that takes 10 seconds per call, will using `threading.Thread` to run 4 calls in parallel make it faster? What about `multiprocessing.Pool` or `concurrent.futures.ProcessPoolExecutor`?

What to watch for
  • Candidate says 'GIL means Python isn't multithreaded' — partially right but reductive.
  • Candidate doesn't know threading IS useful for I/O-bound work (the GIL is released during system calls).
  • Strong signal: candidate mentions free-threaded Python (PEP 703 — landing in 3.13+), or numpy/c-extensions releasing the GIL on heavy ops.
Tap to reveal solution
seniordesign

Design a Limit Order Book

Signal: The canonical 'design a system' quant interview question. Reveals whether the candidate has thought about microstructure.

Question

Design and implement a limit order book in Python supporting: add_limit(side, price, qty, oid), cancel(oid), match against market orders. Optimize for low-latency add/cancel; matching speed matters less. Walk through the data-structure choices.

What to watch for
  • Candidate uses a flat list (O(n) for everything).
  • Candidate uses a heap (O(log n) but can't cancel cheaply).
  • Strong signal: candidate uses sorted price levels + a doubly-linked list of orders within each level + a hash map of oid→node.
Tap to reveal solution
juniorfinance

Max Drawdown of an Equity Curve

Signal: Tests vectorized thinking on a real metric. Many candidates write nested loops.

Question

Given an array of daily equity values, compute the max drawdown (the largest peak-to-trough decline as a fraction). Then return the (peak_date, trough_date) where it happened.

What to watch for
  • Candidate uses a nested loop (O(n²)).
  • Candidate gets confused about whether to return drawdown as positive or negative.
  • Strong signal: candidate spots np.maximum.accumulate immediately.
Tap to reveal solution
seniorfinance

OLS Regression from Scratch

Signal: Tests linear algebra fluency + numerical literacy. Many candidates can call sklearn.LinearRegression but can't derive what it does.

Question

Implement multivariate OLS — β = (X'X)^{-1} X' y. Return coefficients, standard errors, t-stats, and R². Don't use sklearn or statsmodels. Discuss what could go numerically wrong.

What to watch for
  • Candidate uses np.linalg.inv() directly (numerically poor — use lstsq or solve).
  • Candidate doesn't add a constant column.
  • Strong signal: candidate mentions QR decomposition or SVD as a more stable alternative.
Tap to reveal solution
#1 of 23