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:

  1. Mathematical background before programming.
  2. Guided Python implementation using standard scientific Python tools.
  3. Financial interpretation of the numerical results.
  4. 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.

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, brentq

Some 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:

  1. A completed notebook with all code cells executed.
  2. Written answers to checkpoint questions.
  3. At least one parameter experiment beyond the guided example.
  4. A short interpretation of the numerical output.
  5. 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.

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.