34 Computer Labs
Mathematical Finance with Python and Google Colab
35 Overview
The computer labs are an essential part of Mathematical Finance.
They are designed for independent study and can be opened directly in Google Colab from the GitHub repository:
https://github.com/wanghemath/Book-MathFinance
Each lab combines four ingredients:
- Mathematical background before programming.
- Guided Python implementation using standard scientific Python tools.
- Financial interpretation of the numerical results.
- Exercises and experiments for student practice.
The labs are not only coding assignments. They are computational companions to the mathematical theory of pricing, hedging, calibration, fixed income, portfolios, and risk management.
36 How to Open a Lab in Google Colab
Every notebook is stored under the labs/ folder of the GitHub repository. To open a lab, click its Open in Colab link.
The general link pattern is:
https://colab.research.google.com/github/wanghemath/Book-MathFinance/blob/main/labs/lab-file-name.ipynb
For example, Lab 1 opens at:
Students may run the notebooks directly in Colab without installing Python locally.
37 Recommended Student Workflow
For each lab, students should follow this order:
- Read the background sections carefully.
- Run the setup cell.
- Run each code cell one at a time.
- Modify parameters and observe how the output changes.
- Answer the checkpoint questions.
- Complete the exercises at the end.
- Save a personal copy of the notebook to Google Drive.
A good habit is to keep notes on three questions:
- What mathematical object is being simulated or computed?
- What financial concept does the output represent?
- Which assumptions are built into the model?
38 Lab Roadmap
The following 18 labs form a complete computational sequence for the book.
| Lab | Topic | Main Concepts | Notebook | Open in Colab |
|---|---|---|---|---|
| 1 | Prices, Returns, Compounding, and One-Period No-Arbitrage | Simple returns, log returns, portfolios, one-period arbitrage, replication | lab-01-foundations-returns-no-arbitrage.ipynb |
Open |
| 2 | Multi-Period Binomial Trees and Risk-Neutral Pricing | Binomial trees, backward induction, risk-neutral probabilities, American exercise | lab-02-binomial-trees-risk-neutral-pricing.ipynb |
Open |
| 3 | Brownian Motion, GBM, and Monte Carlo Pricing | Brownian motion, GBM, quadratic variation, Monte Carlo option pricing | lab-03-brownian-motion-geometric-brownian-motion-monte-carlo.ipynb |
Open |
| 4 | Black–Scholes Formula, Greeks, and Delta Hedging | Black–Scholes formula, Greeks, finite-difference checks, dynamic Delta hedging | lab-04-black-scholes-formula-greeks-delta-hedging.ipynb |
Open |
| 5 | Implied Volatility and the Volatility Smile | Implied volatility, bisection, smile, skew, no-arbitrage checks | lab-05-implied-volatility-volatility-smile.ipynb |
Open |
| 6 | Monte Carlo Variance Reduction | Antithetic variables, control variates, stratification, importance sampling | lab-06-monte-carlo-variance-reduction.ipynb |
Open |
| 7 | Exotic Options: Asian, Barrier, and Lookback Options | Path dependence, Asian options, barrier options, lookback options | lab-07-exotic-options-asian-barrier-lookback.ipynb |
Open |
| 8 | Finite Difference Methods for the Black–Scholes PDE | Explicit, implicit, Crank–Nicolson schemes, stability, convergence | lab-08-finite-difference-black-scholes-pde.ipynb |
Open |
| 9 | Stochastic Calculus by Simulation: Ito Integrals and Ito Formula | Ito sums, quadratic variation, Ito formula, exponential martingales | lab-09-stochastic-calculus-ito-integral-ito-formula.ipynb |
Open |
| 10 | Martingales, Change of Measure, and Girsanov Simulation | Risk-neutral measure, density process, Girsanov theorem, reweighting | lab-10-martingales-change-of-measure-girsanov.ipynb |
Open |
| 11 | Interest Rates, Bonds, Duration, Convexity, and Yield Curves | Discount factors, bond pricing, duration, convexity, bootstrapping | lab-11-interest-rates-bonds-duration-convexity.ipynb |
Open |
| 12 | Short-Rate Models: Vasicek and CIR | Short rates, affine bond pricing, Vasicek, CIR, calibration | lab-12-short-rate-models-vasicek-cir.ipynb |
Open |
| 13 | HJM and Yield-Curve Simulation | Forward rates, HJM drift restriction, curve simulation, caplets | lab-13-hjm-yield-curve-simulation.ipynb |
Open |
| 14 | Portfolio Optimization: Mean-Variance Theory and Constraints | Efficient frontier, tangency portfolio, constraints, estimation risk | lab-14-portfolio-optimization-mean-variance-constraints.ipynb |
Open |
| 15 | CAPM, Factor Models, and Risk Decomposition | CAPM, beta, alpha, factor exposures, tracking error | lab-15-capm-factor-models-risk-decomposition.ipynb |
Open |
| 16 | Value at Risk, Expected Shortfall, and Risk Backtesting | Historical VaR, normal VaR, Expected Shortfall, EWMA, Kupiec test | lab-16-value-at-risk-expected-shortfall-backtesting.ipynb |
Open |
| 17 | Stochastic Volatility: The Heston Model | Heston simulation, correlated Brownian motion, Fourier pricing, smile calibration | lab-17-stochastic-volatility-heston-model.ipynb |
Open |
| 18 | Integrated Pricing, Hedging, Calibration, and Risk | Volatility surface, smile-consistent pricing, Delta hedging, VaR and ES | lab-18-integrated-pricing-hedging-calibration-risk.ipynb |
Open |
39 Module Organization
The labs can be grouped into six major modules.
39.1 Module I: Discrete-Time Foundations
- Lab 1: Prices, returns, compounding, and one-period no-arbitrage.
- Lab 2: Multi-period binomial trees and risk-neutral pricing.
This module introduces the principle that derivative prices are determined by replication and absence of arbitrage, not by subjective forecasts alone.
39.2 Module II: Continuous-Time Equity Models
- Lab 3: Brownian motion, GBM, and Monte Carlo pricing.
- Lab 4: Black–Scholes formula, Greeks, and Delta hedging.
- Lab 5: Implied volatility and the volatility smile.
This module moves from random walks to continuous-time diffusion models and introduces the main computational language of option pricing.
39.3 Module III: Numerical Methods for Derivatives
- Lab 6: Monte Carlo variance reduction.
- Lab 7: Exotic options.
- Lab 8: Finite-difference methods for the Black–Scholes PDE.
This module studies how to price claims when closed-form formulas are unavailable.
39.4 Module IV: Stochastic Calculus and Change of Measure
- Lab 9: Ito integrals and Ito formula.
- Lab 10: Martingales, change of measure, and Girsanov simulation.
This module gives students computational intuition for the mathematical foundation of continuous-time finance.
39.5 Module V: Fixed Income and Yield Curves
- Lab 11: Interest rates, bonds, duration, convexity, and yield curves.
- Lab 12: Short-rate models: Vasicek and CIR.
- Lab 13: HJM and yield-curve simulation.
This module introduces bond markets, term-structure models, and the modeling of interest-rate curves.
39.6 Module VI: Portfolios, Risk, and Advanced Models
- Lab 14: Portfolio optimization.
- Lab 15: CAPM, factor models, and risk decomposition.
- Lab 16: VaR, Expected Shortfall, and risk backtesting.
- Lab 17: Heston stochastic volatility.
- Lab 18: Integrated pricing, hedging, calibration, and risk.
This final module connects pricing models with portfolio construction, model calibration, and risk management.
40 Python Environment
The notebooks are designed to run in Google Colab with standard packages:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy.stats import norm
from scipy.optimize import minimize, brentqSome labs may use additional routines from scipy.linalg, scipy.special, or scipy.integrate, but no specialized finance package is required.
41 Suggested Use in a Course
A 14-week course can use the labs as follows.
| Week | Suggested Labs | Theme |
|---|---|---|
| 1 | Lab 1 | Returns and no-arbitrage |
| 2 | Lab 2 | Binomial pricing |
| 3 | Lab 3 | Brownian motion and GBM |
| 4 | Lab 4 | Black–Scholes and hedging |
| 5 | Lab 5 | Implied volatility |
| 6 | Labs 6–7 | Monte Carlo and exotic options |
| 7 | Lab 8 | PDE methods |
| 8 | Labs 9–10 | Stochastic calculus and martingales |
| 9 | Lab 11 | Bonds and duration |
| 10 | Labs 12–13 | Term-structure models |
| 11 | Lab 14 | Portfolio optimization |
| 12 | Lab 15 | Factor models |
| 13 | Labs 16–17 | Risk and stochastic volatility |
| 14 | Lab 18 | Integrated final lab |
42 Student Deliverables
For a typical lab submission, students may be asked to submit:
- A completed notebook with all code cells executed.
- Written answers to checkpoint questions.
- At least one parameter experiment beyond the guided example.
- A short interpretation of the numerical output.
- A brief discussion of model assumptions and limitations.
43 Instructor Notes
The labs are designed to be modular. An instructor may use them in several ways:
- as weekly homework assignments;
- as in-class computational demonstrations;
- as independent-study materials;
- as preparation for final projects;
- as supplementary material for a mathematically rigorous course.
Because each lab contains its own background review, students can often work through a lab even if they need to refresh a concept from probability, stochastic processes, numerical analysis, or statistics.
44 Recommended Repository Structure
A clean GitHub structure is:
Book-MathFinance/
├── index.qmd
├── introduction.qmd
├── labs-summary.qmd
├── chapters/
│ ├── chapter-01-...
│ ├── chapter-02-...
│ └── ...
├── labs/
│ ├── lab-01-foundations-returns-no-arbitrage.ipynb
│ ├── lab-02-binomial-trees-risk-neutral-pricing.ipynb
│ ├── lab-03-brownian-motion-geometric-brownian-motion-monte-carlo.ipynb
│ └── ...
├── assets/
│ ├── css/
│ └── js/
└── references.bib
45 Final Advice for Students
Mathematical finance is best learned by moving between three representations:
- formulas, such as the Black–Scholes formula or a bond pricing equation;
- algorithms, such as Monte Carlo simulation or finite-difference methods;
- financial interpretation, such as hedging error, implied volatility, or risk exposure.
The goal of these labs is to help students build fluency in all three.