PokeBot LogoPokeBot
Back to Blog
Guides

Python for Quant Interviews: NumPy, Pandas, and Monte Carlo Simulations

Five Python problems to drill for quant interviews, with worked solutions: simulation, vectorized stats, time series, backtest logic and GBM option pricing.

Dongbo at PokeBot Team
quantpythoncoding-interviewinterview-prepfinance
A laptop showing a Python notebook that simulates stock prices with NumPy (geometric Brownian motion) and prices a call option by Monte Carlo, with a histogram of simulated final prices and the Monte Carlo price (10.46) checked against the Black-Scholes price (10.45).
Share

Last updated: November 2026.

Quick answer: Five problem shapes are worth drilling for the Python round in a quant interview: a Monte Carlo simulation, a loop you must vectorize, a time-series cleanup, a backtest with a look-ahead trap, and an option priced by simulating geometric Brownian motion. Below is each one with an original worked solution and the mistake that sinks most attempts.

Preparing for this round like a software interview, grinding graph problems, mostly wastes your time. The code a quant writes at work is array math on prices, and the round is built to see whether you can do that correctly while someone watches. Correctly matters more than cleverly. An answer that runs fast but uses tomorrow's price to trade today scores worse than a slow loop that gets the timing right.

The math and probability side of quant interviews is covered in the 20 quant interview questions that keep appearing. This post is only about the Python.

What Does the Python Round in a Quant Interview Actually Test?

It tests whether your code can be trusted with money. In practice that comes down to two habits.

  • Alignment. Every value in a price series belongs to a date. Interviewers watch whether you know which row a number came from and whether it was known at that moment.
  • Checking your own output. A simulation that prints a number is half an answer. The other half is how you know the number is right: a known closed form, a standard error, a sanity case.

Speed of typing barely matters. Saying what you are about to do before you do it matters a lot, because the interviewer is grading your reasoning as much as the final cell.

Which Python Problems Are Worth Drilling?

These are representative problem shapes, written in our own words; formats vary by firm. None is attributed to a specific firm, and every solution below is our own. The snippets share setup: np, rng and prices carry over from earlier blocks.

#Problem shapeExample promptThe trap
1SimulationEstimate the expected number of fair coin flips until two heads in a rowNever checking the estimate against the exact answer
2Vectorized statisticCompute a 20-day rolling z-score of a price series without a loopUsing the current row in its own window, then trading on it
3Time seriesTurn a daily price table with gaps into returns and annualized volatilityFilling gaps in a way that invents returns
4Backtest logicBacktest a moving-average crossover with transaction costsLook-ahead: applying today's signal to today's return
5GBM pricingPrice a European call by Monte Carlo and compare to Black-ScholesSimulating the stock under its real drift instead of the risk-free rate

All five solutions were run on NumPy and pandas before publishing. The printed numbers come from those runs, and yours will differ slightly because random draws differ.

How Do You Solve the Five Classic Problems?

1. Simulation: flips until two heads in a row

The exact answer is 6, which you can get by recursion on paper. The interviewer wants to see you simulate it and confirm.

import numpy as np

rng = np.random.default_rng(42)

def flips_until_hh(rng):
    count, prev_heads = 0, False
    while True:
        count += 1
        heads = rng.random() < 0.5
        if heads and prev_heads:
            return count
        prev_heads = heads

trials = np.array([flips_until_hh(rng) for _ in range(200_000)])
mean = trials.mean()
se = trials.std(ddof=1) / np.sqrt(len(trials))
print(mean, se)   # about 5.99, with a standard error near 0.01

The loop is fine here. Each trial has a random length, so forcing it into arrays makes the code harder to read for no real gain, and saying that out loud scores better than a contorted vectorized version. What earns the points is the last two lines. An estimate of 5.99 with a standard error of 0.01 sits about one standard error from 6, so the simulation agrees with the math.

2. Vectorized statistic: rolling z-score

import pandas as pd

prices = pd.Series(100 + rng.standard_normal(300).cumsum())

window = 20
mean = prices.rolling(window).mean()
std = prices.rolling(window).std()
z = (prices - mean) / std

# If z drives a trade, the trade must use yesterday's value
z_for_trading = z.shift(1)

Three lines replace a nested loop. The follow-up question is almost always about the window: today's price sits inside today's rolling mean, so a z-score computed at the close can only drive tomorrow's trade. Say so before you're asked. Also expect "what are the first 19 values?" They are missing, and dropping or keeping them is a choice you should state.

3. Time series: returns and volatility from messy prices

idx = pd.bdate_range("2025-01-01", periods=260)
px = pd.DataFrame(
    100 * np.exp(np.cumsum(0.01 * rng.standard_normal((260, 2)), axis=0)),
    index=idx, columns=["AAA", "BBB"],
)
px.iloc[5, 0] = np.nan                     # a missing print

log_ret = np.log(px).diff()                # gap stays a gap
ann_vol = log_ret.std() * np.sqrt(252)     # roughly 0.15 to 0.17 here
weekly = px.resample("W-FRI").last()       # 53 weekly rows

The interesting part is the missing value. Forward-filling the price before taking returns creates a fake zero return on the gap day and lumps two days of movement into the next one. Leaving the gap as missing drops the gap day and the day after it from the volatility estimate, and .std() skips both. Neither choice is universally right, so name the one you picked and why. The square root of 252 converts daily volatility to annual using the usual count of trading days, and you should say that assumption out loud too.

4. Backtest logic: moving-average crossover

fast = prices.rolling(10).mean()
slow = prices.rolling(30).mean()
signal = (fast > slow).astype(int)         # 1 = long, 0 = flat

position = signal.shift(1).fillna(0)       # trade on yesterday's signal
rets = prices.pct_change().fillna(0)
costs = 0.0005 * position.diff().abs().fillna(0)   # 5 bps per change

strategy = position * rets - costs
total_return = (1 + strategy).prod() - 1

The .shift(1) line is the whole question. Without it, the signal built from today's close earns today's return, and the backtest quietly becomes a time machine. Expect the interviewer to delete that line and ask what happens. The equity curve typically looks better, and that improvement is not tradeable. Costs come next. Charging them on every change in position is the simple version, and mentioning that real costs depend on size and liquidity shows you know where the simple version stops.

5. GBM pricing: a European call by Monte Carlo

The setup: spot 100, strike 100, risk-free rate 5%, volatility 20%, one year. Under the risk-neutral measure, the log of the terminal price is normal, with a drift of the rate minus half the variance and a spread that grows with the square root of time.

S0, K, r, sigma, T = 100.0, 100.0, 0.05, 0.2, 1.0
n_pairs = 250_000

Z = rng.standard_normal(n_pairs)
paths = np.concatenate([Z, -Z])            # antithetic pairs
ST = S0 * np.exp((r - 0.5 * sigma**2) * T + sigma * np.sqrt(T) * paths)
disc_payoff = np.exp(-r * T) * np.maximum(ST - K, 0.0)

# Average each pair first, so the standard error respects the pairing
pair_means = 0.5 * (disc_payoff[:n_pairs] + disc_payoff[n_pairs:])
price = pair_means.mean()
se = pair_means.std(ddof=1) / np.sqrt(n_pairs)
print(price, se)   # close to 10.45; Black-Scholes gives about 10.4506

Three details separate a strong answer from an average one.

  • The rate, not the stock's expected return, goes in the drift. Pricing uses the risk-free rate. Plugging in a forecast return gives a price nobody can hedge to.
  • The half-variance term. Leaving it out makes the average simulated price drift above the forward, and the call comes out too expensive.
  • A benchmark. For a European call you have a closed form, so compute Black-Scholes and show your estimate lands within a couple of standard errors. Then say Monte Carlo earns its keep on path-dependent payoffs that have no closed form.

The antithetic pairs are a bonus. If you use them, compute the standard error on pair averages, since the two halves of each pair are deliberately correlated.

How Does the Coding Round Differ by Firm Type?

Public accounts vary by team and year, so treat this as a starting hypothesis built from what each seat's code does day to day. Confirm the format with your recruiter.

Prop trading and market makingBank quant deskSystematic hedge fund
What the seat's code doesSimulates games and strategies, checks logic fastPrices and risk-manages productsCleans data, builds signals, backtests
Problems most worth drillingSimulation (1), fast correct logicGBM pricing (5), closed-form checksTime series (3), backtests (4), vectorized stats (2)
What a strong answer showsQuick, correct, and checked against intuitionCorrect risk-neutral setup and a benchmarkClean alignment and no leakage
Ask the recruiterIs coding a separate round or folded into other tests?Is there a take-home pricing task?Live data problem or take-home notebook?

If you are applying across all three, start with problem 4. Look-ahead bias turns a backtest into fiction, and the same timing discipline carries into problems 2 and 3.

For the bigger picture on how these roles split, read quant trader vs quant researcher interviews. If you are going for research seats, what quant researchers actually do all day explains why backtest hygiene gets so much airtime.

How Should You Practice Before the Interview?

Reading solutions builds recognition, and recognition falls apart once the parameters change. Build recall instead.

  1. Blank file, timer on. Write each of the five from nothing in 15 minutes. If you need to look something up, note it and redo that problem tomorrow.
  2. Break it on purpose. Remove the .shift(1) or drop the half-variance term. Predict what changes, then run it and see.
  3. Check every number. No simulation counts as done until it matches a closed form or comes with a standard error.
  4. Talk while you type. Narrate each line as if an interviewer were on the call, because the round grades your explanation along with the code.

Step 4 is where practice tools help. In PokeBot's Interview Practice you can add your own prompts under "I have my own interview questions," paste in one of the five problems, and rehearse explaining your approach with scored feedback on structure and clarity. The quant prep page scores your resume against a quant researcher or trader hiring bar, and the Quant Interview Workbook has 56 questions with original step-by-step solutions for the probability and statistics side of the loop.

See free sample questions from PokeBot's 56-question Quant Interview Workbook ($29) →

Score your resume free, create your PokeBot account

Frequently Asked Questions

What Python coding questions come up in quant finance interviews?

Five shapes are worth drilling: a Monte Carlo simulation of a probability puzzle, a loop you must rewrite with vectorized NumPy or pandas, a time-series cleanup on messy price data, backtest logic where the trap is look-ahead bias, and pricing an option by simulating geometric Brownian motion. Interviewers change the parameters, so learn the pattern behind each one.

Do I need to know pandas for a quant interview?

For research and data-heavy roles, yes. Expect to compute returns from a price table, roll a window over it, group by ticker and line up two series on dates. The skill being tested is getting the alignment right: which row a value came from, and whether it was known at that time.

Why do quant interviewers care so much about vectorization?

Research code runs over millions of rows, and a Python for-loop over a price series is slow and harder to check. A vectorized version using whole-array operations is shorter, faster and easier to review. Interviewers also use it to see whether you think in arrays or in single values.

What is look-ahead bias in a backtest interview question?

Look-ahead bias means the strategy trades on information it could not have had yet, usually because the signal computed from today's close is applied to today's return. The standard fix in pandas is to shift the position by one row so today's trade uses yesterday's signal. Missing that shift invalidates every number the backtest produces.

How do you price an option with Monte Carlo in Python?

Draw standard normal shocks, turn each into a terminal stock price under risk-neutral geometric Brownian motion, take the payoff of each path, average them and discount at the risk-free rate. Report a standard error next to the price. For a European call with spot 100, strike 100, a 5% rate, 20% volatility and one year to expiry, the simulation should land close to the Black-Scholes value of about 10.45.

Is the Python round at a prop trading firm different from a bank or hedge fund?

It can be, because the code behind each seat does different work. A seat whose code mostly simulates games points you toward simulation problems; a seat that cleans data and backtests points you toward pandas and look-ahead traps; a pricing seat points you toward Monte Carlo pricing. Formats vary by team, so ask the recruiter what the coding round covers before you allocate prep time.

How should I practice Python for quant interviews?

Write each of the five problem types from a blank file with a timer running, then explain your code out loud as if someone were watching. Check every simulation against a known answer before trusting it. PokeBot's Interview Practice lets you add your own prompts and rehearse the explanation with scored feedback.

Share