Appendix A — OCaml Setup and Tooling

This appendix covers everything needed to run the code in this book, from a fresh Linux/macOS installation to a productive VS Code development environment.


A.1 Installing OCaml with opam

opam is the OCaml package manager. Install it first:

# Linux (Debian/Ubuntu)
sudo apt-get install -y opam

# macOS (Homebrew)
brew install opam

# Initialise
opam init --auto-setup
eval $(opam env)

Install OCaml 5.2

opam switch create 5.2.0
eval $(opam env)
ocaml --version   # should print 5.2.0

A.2 Installing Book Dependencies

opam install \
  core base dune \
  owl owl-plplot \
  zarith \
  yojson ppx_jane \
  ppx_sexp_conv ppx_compare \
  menhir \
  alcotest qcheck

For OxCaml / Jane Street extensions (requires Jane Street opam repository):

opam repo add janestreet-bleeding \
  https://ocaml.janestreet.com/opam-repository
opam install jane-street-headers mode_string

A.3 Dune Project Template

Every chapter's exercise code uses this layout:

my_project/
  dune-project       ← project root
  lib/
    dune             ← library target
    black_scholes.ml
    numerics.ml
    ...
  bin/
    dune             ← executable target
    main.ml
  test/
    dune             ← test target
    test_bs.ml

dune-project

(lang dune 3.12)
(using menhir 2.1)

lib/dune

(library
 (name quant)
 (libraries core base owl zarith yojson)
 (preprocess (pps ppx_jane)))

bin/dune

(executable
 (name main)
 (libraries quant core)
 (preprocess (pps ppx_jane)))

test/dune

(test
 (name test_bs)
 (libraries quant alcotest))

Build and run:

dune build
dune exec bin/main.exe
dune test

A.4 VS Code Setup

Install the OCaml Platform extension (ID: ocamllabs.ocaml-platform).

Install ocaml-lsp-server and ocamlformat:

opam install ocaml-lsp-server ocamlformat

Recommended .vscode/settings.json:

{
  "editor.formatOnSave": true,
  "ocaml.server.path": "ocamllsp",
  "[ocaml]": {
    "editor.defaultFormatter": "ocamllabs.ocaml-platform"
  }
}

A.5 utop — Interactive REPL

opam install utop
utop

Inside utop:

#require "core";;           (* load library *)
open Core;;
List.map ~f:(fun x -> x * 2) [1;2;3];;

Load a module file directly:

#use "black_scholes.ml";;
Black_scholes.call ~spot:100. ~strike:100. ~rate:0.05 ~vol:0.2 ~tau:1.0;;

A.6 Common Commands Reference

TaskCommand
Build alldune build
Run executabledune exec bin/main.exe
Run testsdune test
Clean builddune clean
Format codedune fmt
Check typesdune build @check
List installed packagesopam list
Switch OCaml versionopam switch 4.14.0
Update opamopam update && opam upgrade

A.7 Troubleshooting

"Unbound module Core": Run opam install core and rebuild.

"ocamllsp not found": Run opam install ocaml-lsp-server then restart VS Code.

Dune build error "multiple rules": Ensure each .ml file appears in only one (library) or (executable) stanza.

opam env not loaded: Add eval $(opam env) to your ~/.bashrc or ~/.zshrc.


A.8 The qf_lib Companion Library

Every code example in this book is written against qf_lib, the companion OCaml library. It provides seven modules covering the full quantitative finance stack:

ModuleContents
NumericsRoot-finding (bisection, Newton), integration (Simpson, Gauss-Legendre), Cholesky, interpolation
StatsNormal CDF/PDF/quantile (Beasley-Springer-Moro), Box-Muller RNG, descriptive statistics
Fixed_incomeDiscount curves, bond pricing, YTM, duration, DV01, swap PV, par swap rate
EquityBlack-Scholes call/put, Greeks (Δ, Γ, ν, Θ, ρ), implied vol, CRR binomial tree, Monte Carlo
CreditHazard curves, CDS pricing, par spread, Merton model, Z-spread
RiskHistorical/parametric/MC VaR, Expected Shortfall, Greeks aggregation, scenario analysis, Kupiec test
ExecutionAlmgren-Chriss optimal execution, TWAP, VWAP, square-root impact, implementation shortfall

Installing qf_lib

# Clone the book repository (if not already done)
git clone https://github.com/quantitative-finance-with-ocaml/book.git
cd book/qf_lib

# Install dependencies and build
opam install . --deps-only --with-test
dune build

# Run all tests (unit + property-based)
dune test

# Run a chapter example
dune exec examples/ch10_black_scholes.exe

Using qf_lib in your own projects

Add qf_lib as a dependency in your dune-project:

(depends
 (qf_lib (>= 0.1.0)))

Then reference the modules in your dune file:

(executable
 (name my_pricer)
 (libraries qf_lib.equity qf_lib.stats))

And open the modules in your code:

(* Price a European call using Black-Scholes *)
let price = Equity.call ~spot:100.0 ~strike:100.0 ~rate:0.05 ~vol:0.20 ~tau:1.0
let () = Printf.printf "Call price: £%.4f\n" price

Property-Based Tests

qf_lib includes QCheck property-based tests that verify financial invariants across thousands of randomly generated inputs. These tests serve as both a correctness guarantee and as examples of how to write property tests for your own financial models:

# Run only the equity property tests
dune test test/test_equity

# Run with verbose output to see all generated cases
QCHECK_VERBOSE=1 dune test test/test_equity

Key properties tested:

  • Put-call parity: C - P = S - K·e^{-rT} for all valid parameters
  • Positive vega: call price strictly increases with volatility
  • No-arbitrage lower bound: C ≥ max(0, S - K·e^{-rT})
  • Bond convexity: bond price strictly decreasing in yield
  • Survival probability: in [0, 1] and decreasing in time
  • ES ≥ VaR: at all confidence levels