Skip to content

Latest commit

 

History

8 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 

Repository files navigation

Python for Quant Finance — The Complete Pre-MFE Roadmap

A 7–9 month, project-gated path from "knows Python" to walking into an MFE program already dangerous.

duration commitment phases license

Note

Who wrote this and why. I'm preparing for an MFE myself. This is the roadmap I built for my own preparation, published openly because I couldn't find one that was specific about what to build rather than what to read. It is a study plan, not advice from a practitioner — weigh it accordingly, and tell me where I'm wrong by opening an issue.


Who this is for

You've finished Python basics — data types, mutability, loops, conditionals, functions, recursion, break/continue/pass. Everything below assumes that and nothing more.

Total duration: ~7–9 months at 15–20 hrs/week. Compress or stretch as needed, but do not skip phases — each builds on the last.

Important

The one rule: never move to the next phase until you've completed the checkpoint project of the current one.

Reading ≠ knowing. Only building is knowing.


The roadmap at a glance

Phase Weeks Focus Checkpoint project
0 1 Professional setup Existing work on GitHub, clean history
1 2–6 Intermediate → advanced Python OOP pricing library + 15 pytest tests
2 7–9 NumPy mastery Correlated Cholesky Monte Carlo, zero loops
3 10–13 pandas & time series 10-year, 30-ticker cleaned data pipeline
4 14–19 Probability, stats, econometrics Stylized-facts research note
5 20–28 Core quant finance domains Flagship — backtester, FI library, or risk engine
6 29–33 Machine learning for finance Honest return-prediction study
7 34–37 Performance & data engineering Profiled, Numba-accelerated flagship
8 final 4–6 Integration & interview prep Green book, 50 LeetCode, closed-book derivations

Contents: Phase 0 · 1 · 2 · 3 · 4 · 5 · 6 · 7 · 8 · Weekly system · Resources · Milestones


Phase 0 — Professional Setup

Week 1

You'll be judged on your workflow as much as your code.

  • Git & GitHubinit, add, commit, branch, merge, push/pull, writing good commit messages, .gitignore. Everything you build from now on gets committed. Your commit history is your proof of work for admissions and recruiters.
  • Environmentsvenv or conda, pip, requirements.txt. Understand why isolating project dependencies matters.
  • Tools — VS Code (Python + Jupyter extensions), notebooks for exploration, .py files for real code. Learn the discipline: explore in notebooks, ship in modules.
  • The terminalcd, ls, mkdir, running scripts, reading error tracebacks bottom-up.

Tip

Checkpoint: push whatever you've already built to GitHub with clean, incremental commits. If you can't, redo this phase before continuing.


Phase 1 — Intermediate → Advanced Python

Weeks 2–6

The gap between "knows Python" and "engineers in Python." Quant interviews at top firms test this layer hard.

1.1 Object-oriented programming, properly

  • Classes, __init__, instance vs class attributes, methods.
  • Dunder methods__repr__, __str__, __eq__, __lt__, __len__, __getitem__, __add__.

    Exercise: build a Portfolio class where portfolio1 + portfolio2 merges holdings and len(portfolio) returns position count.

  • Inheritance and super(); when to prefer composition over inheritance.
  • Abstract base classes (abc) — how real pricing libraries define an Instrument interface that Option, Bond and Swap all implement.
  • @property, @staticmethod, @classmethod — know the difference cold.
  • dataclasses — the modern way to define data containers (a Trade, a Quote).

1.2 Functional & idiomatic Python

  • List/dict/set comprehensions (nested too), generator expressions.
  • Generators and yield — process a 10 GB tick-data file without loading it into memory. This is a real quant-dev interview question.
  • lambda, map, filter, sorted(key=...), zip, enumerate, any/all.
  • Decorators — write your own @timer and @memoize. Understand closures first.
  • *args, **kwargs, unpacking, keyword-only arguments.
  • Context managers (with, and writing your own via __enter__/__exit__).

1.3 Robustness & correctness

  • Exceptionstry/except/else/finally, raising your own classes (class InvalidPriceError(ValueError)).
  • Type hintsdef price(S: float, K: float) -> float:, Optional, list[float], and running mypy. MFE group projects will thank you.
  • Testing with pytest — write tests first, then implement. Learn assert, fixtures, pytest.approx for floats, parametrized tests.

    Non-negotiable: from now on, every module you write gets a test file.

  • Logging — the logging module instead of print for anything serious.

1.4 Under the hood (interview favourites)

  • Mutability revisited: why def f(x, lst=[]) is a famous bug. Shallow vs deep copy.
  • How Python variables are references; is vs ==.
  • Time complexity of core operations: list append O(1), list insert O(n), dict/set lookup O(1). Big-O basics.
  • Iterators vs iterables; what for actually does.

Tip

Checkpoint: build a derivatives pricing library, properly engineered — abstract PricingEngine base class with BlackScholesEngine, BinomialEngine and MonteCarloEngine subclasses, an Option dataclass, full type hints, and a pytest suite with ≥15 tests including cross-validation between engines.

This single project teaches you more than a month of tutorials.


Phase 2 — NumPy Mastery

Weeks 7–9

NumPy is the bedrock. Quants who loop over arrays get rejected.

  • ndarray fundamentalsshape, dtype, and why NumPy is ~100× faster (contiguous memory, C loops).
  • Creationarray, zeros, ones, arange, linspace, full, eye.
  • Indexing & slicing — basic, boolean masks (prices[returns < 0]), fancy indexing. Views vs copies is a silent-bug factory; know when a slice shares memory.
  • Vectorization — rewrite any loop as array ops.

    Exercise: compute a 20-day moving average three ways (pure loop, np.convolve, cumsum trick) and time all three.

  • Broadcasting — the rules, cold.

    Exercise: build a full option-price surface over a strike grid × maturity grid with zero loops.

  • Axis semantics on 2-D/3-D arrays: mean(axis=0) vs axis=1. Simulate 10,000 GBM paths as a matrix and compute per-path and per-date statistics.
  • Aggregationsargmax/argmin/argsort, where, clip, cumsum/cumprod, diff.
  • Linear algebra (np.linalg) — matrix multiply @, inv, solve (and why solve beats inv), eigenvalues (→ PCA on yield curves), Cholesky decomposition (→ correlated Monte Carlo, a genuine desk technique).
  • Randomdefault_rng, seeding, standard_normal, multivariate_normal, choice (→ bootstrap resampling).
  • Numerical hygiene — floating-point error, np.isclose, never == on floats, nan propagation.

Tip

Checkpoint: correlated Monte Carlo engine. Simulate 5 correlated assets via Cholesky, price a basket option, and verify the sample correlation matrix matches the input. Fully vectorized — a single Python loop disqualifies it.


Phase 3 — pandas & Time Series Mastery

Weeks 10–13

Where quants live day-to-day. Aim for fluency, not familiarity.

Core mechanics

  • Series & DataFrame anatomy — the index is everything. loc vs iloc, and why chained indexing df[a][b] = x is a bug.
  • I/Oread_csv (parse_dates, dtypes, chunksize), Parquet and why it beats CSV.
  • Selection & filtering — boolean masks, query, isin, between.
  • Cleaningdropna, fillna (and why ffill is right for prices but forward-filling returns is a crime), duplicates, string methods, astype.
  • Transformationsapply vs vectorized ops (know why apply is slow), assign, pipe, map, replace.
  • GroupBy — split-apply-combine: aggregate returns by sector/month, transform (z-score within groups → cross-sectional signals), agg with multiple functions.
  • Mergingmerge (inner/left/outer, and how a bad join silently duplicates rows), concat, join, and merge_asof for as-of joins of trades to quotes, a real market-microstructure tool.

Time series — the quant core

  • DatetimeIndex, timezone handling, business-day calendars.
  • resample — daily → monthly returns done correctly (compound, don't average).
  • rolling / expanding / ewm — moving statistics, EWMA volatility (RiskMetrics style).
  • shift / pct_change / diff — and the look-ahead-bias discipline that goes with them.
  • MultiIndex — panel data (dates × tickers), stack/unstack, pivot_table.
  • Performance — vectorize first, itertuples if you must, never iterrows in production.

Tip

Checkpoint: equity data pipeline. Download 10 years of prices for ~30 tickers (yfinance), clean them with a documented missing-data policy and survivorship notes, compute daily/monthly returns, rolling 60-day volatility and correlations, and per-sector aggregates. Output a tidy Parquet dataset plus a one-page summary notebook.

This dataset feeds every later phase.


Phase 4 — Probability, Statistics & Econometrics

Weeks 14–19

MFE coursework assumes this. Arriving with it already coded is a massive advantage. Do the maths on paper and in code — the combination is what builds real intuition.

4.1 Probability

  • Distributions — normal, lognormal, Student-t, chi-square, Poisson, exponential. pdf, cdf, ppf, rvs for each. Know why asset returns are fat-tailed: compare fitted normal vs t on real returns, with Q-Q plots.
  • LLN & CLT — demonstrate both by simulation.
  • Conditional probability & Bayes — code the classic interview problems (dice games, coin sequences, Monty Hall) as simulations.
  • Moments — skewness and kurtosis of real return data.

4.2 Statistics

  • MLE — fit a distribution to returns by writing the negative log-likelihood yourself and minimising with scipy.optimize.minimize. Don't just call .fit().
  • Hypothesis testing — t-tests, p-values and their misuse, confidence intervals via both formulas and bootstrap.
  • Linear regression, deeply (statsmodels) — OLS assumptions, reading the full summary table, R², heteroskedasticity, residual autocorrelation, Newey-West errors.

    Application: estimate a stock's beta via CAPM regression and test whether alpha is significant.

  • Multiple regression — multicollinearity (VIF), factor models. Regress returns on Fama-French factors; the data is free online.

4.3 Time-series econometrics

  • Stationarity, unit roots, the ADF test.
  • Autocorrelation — ACF/PACF on returns vs |returns|. Volatility clustering is a stylized fact you should discover for yourself.
  • AR, MA, ARMA — fit, forecast, evaluate.
  • GARCH(1,1) with the arch package — fit to real returns, forecast volatility, compare to realized vol. The single most-used time-series model in risk.
  • Cointegration — the statistical basis of pairs trading.

4.4 Parallel maths track

Ongoing through all phases — paper and Python together.

  • Linear algebra — matrix ops, eigendecomposition, positive-definiteness (covariance matrices), Cholesky. Do 3Blue1Brown's Essence of Linear Algebra, then implement PCA from scratch on the yield curve and reproduce the level/slope/curvature result.
  • Calculus — partial derivatives (Greeks), Taylor expansion (delta-gamma P&L approximation), Lagrange multipliers (portfolio optimization), basic ODEs.
  • Stochastic calculus preview — don't master it, the MFE will. Random walks → Brownian motion, Itô's lemma at intuition level, why the −σ²/2 appears. Shreve Stochastic Calculus for Finance I is very readable now and maps directly onto binomial tree code.

Tip

Checkpoint: stylized-facts report. A polished notebook proving on real data: fat tails, volatility clustering, near-zero return autocorrelation, the leverage effect. Fit normal vs t vs GARCH and compare with proper statistical tests. Write it like a research note — it doubles as SOP and interview material.


Phase 5 — Core Quant Finance Domains

Weeks 20–28

Finance proper. For each domain: learn the theory, implement from scratch, then check against a library.

5.1 Portfolio theory & asset allocation

  • Returns maths — simple vs log returns, annualization, geometric vs arithmetic mean.
  • Markowitz mean-variance optimization — implement the efficient frontier with scipy.optimize.minimize under constraints (long-only, fully invested), plot it, find max-Sharpe and min-variance portfolios.
  • CAPM, beta, the security market line. Sharpe / Sortino / Information ratios.
  • Why naive Markowitz fails — estimation error in the covariance matrix. Demonstrate with a rolling out-of-sample test, then touch on shrinkage (Ledoit-Wolf via scikit-learn).
  • Risk parity as an alternative — implement inverse-vol and equal-risk-contribution weighting.

5.2 Fixed income

Warning

Most self-taught quants skip fixed income. Don't — it's MFE-critical and it's where the gap shows.

  • Time value of money, compounding conventions, discount factors.
  • Bond pricing from cash flows; clean vs dirty price; yield-to-maturity via root-finding (Brent).
  • Duration and convexity — derive, implement, verify numerically by bumping yields. Plot the price-yield curve.
  • Yield curve — bootstrapping zero rates from par bonds and swap rates (a genuinely great coding exercise), forward rates, Nelson-Siegel fitting via least squares.
  • PCA on historical yield-curve moves — connects straight back to your linear algebra.

5.3 Derivatives

  • Re-derive everything so you own it: put-call parity (test it numerically), binomial → Black-Scholes convergence, risk-neutral pricing intuition.
  • Add engines — finite-difference PDE solver (explicit and implicit Crank-Nicolson); Longstaff-Schwartz least-squares Monte Carlo for American options; Greeks by finite differences vs analytic.
  • Delta-hedging simulation — hedge daily, watch P&L variance shrink. The most instructive experiment in derivatives.
  • Volatility — realized vol estimators, implied vol surfaces on real option chains (yfinance provides them), the smile and skew.

5.4 Risk management

  • VaR three ways — historical, parametric (variance-covariance), Monte Carlo. Implement all three on a multi-asset portfolio.
  • Expected Shortfall (CVaR) and why regulators moved to it — VaR isn't subadditive; construct the classic counterexample.
  • Backtesting VaR — the Kupiec exceedance test.
  • Stress testing and scenario analysis; EWMA and GARCH-based dynamic VaR.
  • Drawdown analytics — maximum drawdown, duration, recovery time.

5.5 Backtesting & strategy research

  • Event-driven vs vectorized architectures — build a small event-driven engine with Strategy / Portfolio / ExecutionHandler classes. Your OOP phase pays off here.
  • The seven deadly sins — look-ahead bias, survivorship bias, overfitting, data snooping, ignoring costs/slippage/borrow, unrealistic fills, no out-of-sample test. Be able to give a concrete example of each.
  • Walk-forward analysis and parameter-sensitivity heatmaps.
  • Cross-sectional strategies — momentum and mean-reversion on your Phase-3 dataset; decile portfolios; long-short construction.

Tip

Checkpoint — pick ONE and do it exceptionally. This becomes your flagship repository.

  1. Multi-strategy backtester — event-driven engine running momentum + pairs trading, full cost model, walk-forward validation, tear-sheet report generator.
  2. Fixed-income analytics library — curve bootstrapper, bond pricer, duration/convexity, PCA study.
  3. Risk engine — portfolio VaR/ES three ways, GARCH-dynamic VaR, Kupiec backtest, stress scenarios.

Phase 6 — Machine Learning for Finance

Weeks 29–33

ML is table stakes for MFE grads. But finance-flavoured ML ≠ Kaggle ML.

  • scikit-learn workflow — train/test split, pipelines, StandardScaler, metrics.
  • Models — know how each works, not just .fit(): linear/logistic regression, regularization (Ridge/Lasso — connect it to shrinkage), decision trees, random forests, gradient boosting (XGBoost/LightGBM), k-means, PCA again from the ML view.
  • Feature engineering from market data — lagged returns, rolling statistics, technical features, cross-sectional ranks.
  • Bias-variance tradeoff, overfitting diagnostics, feature importance and SHAP.
  • Optional stretch: a small PyTorch feedforward net for the same task — mostly to learn the framework exists. Deep learning depth can wait for the MFE.

Caution

The finance-specific dangers — this is what separates you.

  • Temporal leakage — why random train/test splits are invalid on time series.
  • Purged and embargoed cross-validation, walk-forward validation.
  • The near-zero signal-to-noise ratio of returns.
  • Why 55% directional accuracy can be a great model — and 90% means you leaked data.

Read: Advances in Financial Machine Learning (López de Prado) — the chapters on labelling (triple-barrier), sample weights, and cross-validation. Hard but formative.

Tip

Checkpoint: a return-prediction study done right. Predict next-day or next-week direction for liquid ETFs with proper purged walk-forward CV, honest benchmarks (always-long, momentum), transaction-cost-aware evaluation, and a written conclusion.

Even if the conclusion is "no exploitable edge found" — a negative result presented rigorously is more impressive to quants than a fake 80% accuracy.


Phase 7 — Performance, Data Engineering & Polish

Weeks 34–37

What makes you quant-developer capable — a huge differentiator.

  • Profile before optimizing%timeit, cProfile, line_profiler. Find the actual bottleneck; never guess.
  • Numba @njit — accelerate Monte Carlo and backtest loops 50–200×. Understand what it can and can't compile.
  • Multiprocessing vs threading vs the GIL — a classic interview question. concurrent.futures for parallel simulations.
  • Memory — dtypes (float32 vs float64), categoricals, chunked processing, Parquet.
  • SQL — non-negotiable for any quant job. SELECT/WHERE/GROUP BY/HAVING/joins/window functions. Practise on SQLite with your own price data via sqlite3 + pandas.read_sql. Window functions (ROW_NUMBER, moving averages in SQL) are an interview favourite.
  • Clean-code habits — project structure (src/, tests/, notebooks/), docstrings, README quality, black formatting, pre-commit hooks, and GitHub Actions running your pytest suite on every push. A green CI badge quietly signals professionalism.

Tip

Checkpoint: take your Phase-5 flagship. Profile it, Numba the hot loop, add CI, and document the speedup in the README. "Optimized Monte Carlo from 41s to 0.6s" is a resume bullet.


Phase 8 — Integration & Interview Prep

Final 4–6 weeks

  • Brainteasers & probability puzzlesA Practical Guide to Quantitative Finance Interviews (Zhou, the "green book"), one hour daily. Also Heard on the Street (Crack). This is exactly what quant internship interviews ask — and those start early in MFE programs, often within weeks of arrival.
  • Mental math — trading-firm tests like Optiver's are pure speed arithmetic. Zetamac daily, 10 minutes.
  • Coding drills — easy/medium LeetCode in Python: arrays, hashmaps, two pointers, binary search, simple DP. ~50 problems is plenty for quant roles.
  • Re-derive on paper, closed-book — Black-Scholes intuition, duration, VaR definitions, CAPM, the OLS estimator. If you can't whiteboard it, you don't own it.
  • Polish GitHub — 3–4 pinned repos with immaculate READMEs, results tables and plots. Documentation that shows you can communicate.
  • Read the markets 20 min/day (FT, Bloomberg, Matt Levine). Interviews always touch current markets.
  • Front-run your MFE syllabus — preview the heaviest course, usually stochastic calculus. Start Shreve I seriously now.

The Weekly Operating System

Applies to every phase.

Split Activity
60% Building
25% Reading / watching
15% Maths on paper

Tutorials feel productive; only building compounds.

  • Every concept → a small experiment in code the same day.
  • Every week → at least one commit to GitHub.
  • Keep a learning-log.md: what you learned, what confused you, questions to revisit. Reviewing it monthly is where real intuition forms.
  • Spaced re-derivation — once a month, pick one old topic and re-implement it from a blank file, closed-book. Painful and priceless.

Master Resource Shelf

In order of use.

Phase Resource
1 Fluent Python (Ramalho, selective) · Corey Schafer's OOP videos
2–3 Python for Data Analysis (McKinney — pandas' creator; work the exercises)
4 Introduction to Statistical Learning (free PDF, ch. 2–3) · MIT OCW 18.S096 · 3Blue1Brown (Linear Algebra + Calculus)
4–5 Hilpisch, Python for Finance · Shreve, Stochastic Calculus for Finance I
5 Hull, Options, Futures and Other Derivatives (the bible — read alongside coding) · Tuckman, Fixed Income Securities · Ernie Chan, Quantitative Trading · QuantStart
6 López de Prado, Advances in Financial Machine Learning (selective) · scikit-learn docs
8 Zhou, green book · Heard on the Street · Zetamac · LeetCode

Milestone Checklist

Fork this repo and tick these off as you go.

  • Phase 0 — existing projects on GitHub with clean history
  • Phase 1 — OOP pricing library + 15 pytest tests
  • Phase 2 — correlated (Cholesky) Monte Carlo basket pricer, zero loops
  • Phase 3 — 10-year, 30-ticker cleaned equity dataset pipeline (Parquet)
  • Phase 4 — stylized-facts research note (fat tails, GARCH, clustering)
  • Phase 5 — flagship: backtester or fixed-income library or risk engine
  • Phase 6 — honest ML return-prediction study with purged walk-forward CV
  • Phase 7 — profiled + Numba-accelerated flagship, CI badge, SQL fluency
  • Phase 8 — green book done, 50 LeetCode, all core derivations closed-book

Finish this and you won't just survive the MFE. You'll be the person classmates form project teams around, and you'll walk into internship interviews with real artifacts while others have coursework.


Contributing

Corrections, better resources, and "this phase is mis-ordered because…" are all welcome — open an issue or a pull request. I'd rather this be right than be mine.

License

MIT — use it, fork it, adapt it.

About

The pre-MFE quant finance roadmap I built for myself: 9 phases, ~8 months, every one gated behind a project you have to build.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors