Objective
Quant developer interviews often include a "here is some research code, make it production quality" round, and the job itself is mostly that. By the end of this lesson you should be able to look at a script, name the specific design problems (not "it's messy"), and restructure it into small pure functions, typed records and a package whose modules depend on each other in one direction.
What goes wrong in research scripts
Research code is written to get one number once. It becomes a liability when it is run twice, imported by something else, or changed by a second person. The recurring problems are concrete:
- Hidden state. A module-level list or dictionary that functions append to, so the result of a call depends on what was called before.
- Mixed concerns. Parsing, maths, printing and file writing in one loop, so none of it can be tested or reused without the rest.
- Anonymous data. Tuples such as
(100, 95, 0.5, 0.25, "P")whose meaning lives in the author's head; swapping two fields is a silent bug. - Magic constants (a global
RATE = 0.05) instead of explicit inputs. - Import-time side effects. Code at module level that runs when another module does
import pricing.
The script we will fix
import math
RATE = 0.05
results = []
def run(trades):
for t in trades:
S, K, T, vol, typ = t
d1 = (math.log(S / K) + (RATE + 0.5 * vol**2) * T) / (vol * math.sqrt(T))
d2 = d1 - vol * math.sqrt(T)
N = lambda x: 0.5 * (1 + math.erf(x / math.sqrt(2)))
if typ == "C":
p = S * N(d1) - K * math.exp(-RATE * T) * N(d2)
else:
p = K * math.exp(-RATE * T) * N(-d2) - S * N(-d1)
results.append(p)
print(f"{typ} K={K}: {p:.4f}")
print("total", round(sum(results), 4))
run([(100, 100, 1.0, 0.2, "C"), (100, 95, 0.5, 0.25, "P")])
It prints C K=100: 10.4506, P K=95: 3.7320, total 14.1825, which is correct. Now import it from another module and call run([(100, 100, 1.0, 0.2, "C")]). The import itself runs the module-level run(...) and prints the first three lines; the second call then prints C K=100: 10.4506 and total 24.6331. The total is wrong because results still holds the two prices from the import-time run. Every problem in the list above appears here: global mutable state, an import side effect, pricing tangled with printing, a positional tuple, and a rate that cannot vary per trade.
Principles that fix it
One job per function. A function should do one thing you can name in a short phrase without "and": "price a European option", "load the trade file", "format a report line". If its docstring needs "and then", split it.
Pure core, imperative shell. A pure function's output depends only on its arguments and it changes nothing outside itself: no globals, no I/O, no mutation of its inputs. Pure functions are trivially testable (call, compare), safe to cache and safe to run in parallel. Push everything impure (reading files, network, clocks, random seeds, printing) into a thin outer layer that calls the pure core. Most of a pricing library can be pure.
Name your data. Use @dataclass(frozen=True) for records and Enum for closed sets of values. Fields have names and types, the constructor checks the field count, == and repr come for free, and frozen=True makes instances immutable and hashable, so they cannot be changed behind your back. Use slots=True as well when you create millions of them, to save memory.
Pass dependencies in. A function that needs a rate takes a rate (or a Market object). It does not read a global, and it does not open the config file itself.
Worked example
refactor the pricing script
Restructure the script above so that pricing is a pure function of named inputs, printing happens in one place, importing the module has no side effects, and repeated calls give the same answer.
Show solutionHide solution
Separate the records, the maths and the I/O:
import math
from dataclasses import dataclass
from enum import Enum
class Right(Enum):
CALL = "C"
PUT = "P"
@dataclass(frozen=True)
class Option:
strike: float
expiry: float # years
right: Right
@dataclass(frozen=True)
class Market:
spot: float
rate: float
vol: float
def norm_cdf(x: float) -> float:
return 0.5 * (1.0 + math.erf(x / math.sqrt(2.0)))
def black_scholes(opt: Option, mkt: Market) -> float:
"""Pure: same inputs, same output, no I/O, no globals."""
sqrt_t = math.sqrt(opt.expiry)
d1 = (math.log(mkt.spot / opt.strike) + (mkt.rate + 0.5 * mkt.vol**2) * opt.expiry) / (
mkt.vol * sqrt_t
)
d2 = d1 - mkt.vol * sqrt_t
df = math.exp(-mkt.rate * opt.expiry)
if opt.right is Right.CALL:
return mkt.spot * norm_cdf(d1) - opt.strike * df * norm_cdf(d2)
return opt.strike * df * norm_cdf(-d2) - mkt.spot * norm_cdf(-d1)
def price_book(book: list[tuple[Option, Market]]) -> list[float]:
return [black_scholes(o, m) for o, m in book]
def main() -> None: # the only function that does I/O
book = [
(Option(100, 1.0, Right.CALL), Market(spot=100, rate=0.05, vol=0.20)),
(Option(95, 0.5, Right.PUT), Market(spot=100, rate=0.05, vol=0.25)),
]
prices = price_book(book)
for (opt, _), p in zip(book, prices):
print(f"{opt.right.value} K={opt.strike}: {p:.4f}")
print("total", round(sum(prices), 4))
if __name__ == "__main__":
main()
Running it prints the same three lines as before (10.4506, 3.7320, total 14.1825), so behaviour is preserved, and mypy --strict reports no issues. What changed, and why each change matters:
resultsis gone.price_bookreturns a new list, so calling it twice gives the same answer twice; the 24.6331 bug cannot happen.- The
if __name__ == "__main__":guard meansimportdefines functions and runs nothing. black_scholesis pure, so its test is one line:assert black_scholes(Option(100, 1.0, Right.CALL), Market(100, 0.05, 0.2)) == pytest.approx(10.450584, abs=1e-6).Right.CALLreplaces the string"C": a typo such as"c"used to fall through to the put branch silently;Right.CALis anAttributeErrorat once and a mypy error before that.- The rate is per market, so pricing two currencies needs no change to the function.
The refactor is deliberately small. In an interview, do it in this order and say so: first pin the current behaviour with a test on the known outputs, then change structure without changing results, then fix bugs as a separate step.
Package layout and dependency direction
Once there is more than one file, make it an installable package with the src layout:
pricing/
pyproject.toml # name, version, dependencies, tool config (mypy, pytest)
src/pricing/
__init__.py # re-export the public API only
models.py # Option, Market, Right: imports nothing from the package
analytics.py # black_scholes, greeks: imports models
config.py # load_config: imports models
io.py # read trades, write reports: imports models
cli.py # main(): wires config, io and analytics together
tests/
test_analytics.py
The rule that keeps it maintainable is dependencies point inward: cli depends on io, config and analytics, which depend on models; nothing depends on cli, and analytics never imports io. The core then has no knowledge of files, databases or command-line flags, so it can be reused from a notebook, a risk service or a test without dragging those in. Two symptoms that the direction is wrong: a circular import (ImportError: cannot import name ... (most likely due to a circular import)), and a unit test of the maths that needs a database connection. The src layout also forces tests to run against the installed package (pip install -e .) rather than whatever happens to be in the current directory.
Configuration
Read configuration once, at the edge, into a frozen dataclass that validates itself, and pass that object down. Do not scatter os.environ reads or config["risk"]["window"] lookups through the code.
import tomllib
from dataclasses import dataclass
@dataclass(frozen=True)
class RiskConfig:
max_position: int
vol_window: int = 20
stop_loss: float = 0.02
def __post_init__(self) -> None:
if self.vol_window < 2:
raise ValueError("vol_window must be at least 2")
def load_config(text: str) -> RiskConfig:
return RiskConfig(**tomllib.loads(text)["risk"])
cfg = load_config("""
[risk]
max_position = 500
vol_window = 60
""")
print(cfg)
load_config("[risk]\nmax_position = 1\nvol_windw = 60\n")
The first call prints RiskConfig(max_position=500, vol_window=60, stop_loss=0.02). The second raises TypeError: RiskConfig.__init__() got an unexpected keyword argument 'vol_windw': a misspelt key fails at start-up instead of silently using the default window of 20 for months. Assigning cfg.stop_loss = 0.5 raises FrozenInstanceError at run time, and mypy flags it before then (Property "stop_loss" defined in "RiskConfig" is read-only). tomllib is in the standard library from Python 3.11.
Knowledge check
Which of these functions is pure?
Knowledge check
In the package layout above, analytics.py needs the list of trades to price. Where should the code that reads trades.csv live, and who calls it?
Knowledge check
Why does the original script print total 24.6331 when another module imports it and then calls run with only the ATM call?
Key takeaways
- Diagnose by category: hidden state, mixed concerns, anonymous tuples, magic constants, import-time side effects.
- Keep a pure core (inputs in, value out) and push I/O, clocks and randomness to a thin shell.
- Use frozen dataclasses and Enums for records; they name fields, validate arity and prevent mutation.
- Lay packages out so dependencies point inward to the models; circular imports and database-needing unit tests mean the direction is wrong.
- Load configuration once into a validated frozen object and pass it down.
- Refactor safely: pin behaviour with a test, restructure, then fix bugs separately.
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).