fincl
Table of Contents
- 1 Getting Started
- 2 Dates and markets
- 3 Options
- 4 Pricing engines
- 5 Simulation
- 6 Stochastic processes
- 7 Portfolios and risk
- 8 Extending fincl
[in package FINCL/DOCGEN]
fincl is a Common Lisp library for quantitative finance.
This documentation and the library is a work in progress. API is subject to change without notice.
1 Getting Started
Acquire the dependencies for fincl and the library itself and load it.
Assuming you have registered the package locally to quicklisp, you can load
the library
(ql:quickload :fincl)
(defpackage #:fun-in-fincl (:use #:cl #:fincl))
(in-package #:fun-in-fincl)
;;; Literals for dates and tenors
(named-readtables:in-readtable fincl:syntax)
The closest thing to a "Hello, World!" of a quantitative finance library is pricing a European option with the Black-Scholes formula.
(defconstant +today+ #D"2026-10-01")
(defparameter *market*
(make-bs-market :valuation-date +today+
:spot 100 :rate 0.04d0
:dividend 0.01d0
:vol 0.2d0))
(defparameter *option*
(make-option (call 110) (expires #T"1Y" :from +today+)))
(price *option* (make-engine :black-scholes) *market*)
;; ==> 5.240727867335534d0
;; NIL
;; #<ENGINE (make-engine :black-scholes)>
2 Dates and markets
Dates and tenors are read with #D"2026-10-01" and #T"3M" in the
fincl:syntax readtable; date+ and date< move and compare dates.
A market holds the spots, curves, dividends and volatilities that engines
read. It has a valuation date, there is no hidden "today", and it is
immutable: a scenario is a new market (see bump). make-market builds one
with several underlyings and curves from lists; make-bs-market builds the
common case of one underlying, one currency and one curve, with flat inputs.
Discrete cash and proportional dividends are given as a dividend-schedule,
a list of (ex-date amount [:kind :cash|:proportional] [:pay-date date]).
(make-market :valuation-date #D"2026-10-01"
:underlyings '((:spx :spot 5000 :currency :usd
:dividend 0.015d0 :vol 0.18d0))
:curves '((:usd-ois :rate 0.04d0))
:discounting '((:usd . :usd-ois)))
[class] FINCL:DATE STRUCTURE-OBJECT
A calendar date. Immutable. Two dates are
EQUALPwhen they are the same day, so they can key anEQUALPhash table.(make-date 2027 6 15) => #D"2027-06-15"
[class] FINCL:TENOR STRUCTURE-OBJECT
A length of time in whole days, weeks, months or years. Immutable; two tenors are
EQUALPwhen they have the same N and UNIT.(make-tenor 3 :months) => #
T"3M"
[function] FINCL:DATE+ DATE DAYS
The date DAYS calendar days after DATE (before, if DAYS is negative).
(date+ #D"2027-06-15" 10) => #D"2027-06-25"
- [function] FINCL:DATE< A B
[class] FINCL:MARKET
State of the world at a valuation date.
[function] FINCL:MAKE-MARKET &KEY VALUATION-DATE (DAY-COUNTER
FINCL:+ACTUAL-365-FIXED+) UNDERLYINGS CURVES DISCOUNTING FIXINGSA COMPOSITE-MARKET observed on VALUATION-DATE. The arguments are lists:
UNDERLYINGS ((name :spot s [:currency c][:dividend q] [:dividend-schedule d][:vol v]) ...) S a positive real; C a keyword (default
:DEFAULT); Q a real continuous dividend yield or a DIVIDEND-CURVE (default 0); D discrete dividends alongside Q, a DIVIDEND-SCHEDULE or the entries MAKE-DIVIDEND-SCHEDULE takes, ((ex-date amount [:kind k][:pay-date p]) ...); V a real Black vol or a BLACK-VOL-STRUCTURE (default none, for markets that need no vol). CURVES ((id :rate r) ...) or ((id :curve c) ...): R a real zero rate, C a YIELD-CURVE. DISCOUNTING ((currency . curve-id) ...): the curve each currency discounts on. If omitted and there is one curve, every currency discounts on it. FIXINGS ((index-id (date rate) ...) ...): past fixings of interest-rate indexes, DATE a date or a "YYYY-MM-DD" string.Reals are coerced to double-float.
(make-market :valuation-date #D"2026-09-24" :underlyings '((:spx :spot 5000 :currency :usd :dividend 0.015d0 :vol 0.18d0) (:aapl :spot 230 :currency :usd :vol 0.25d0 :dividend-schedule (("2027-02-10" 0.26d0) ("2027-05-12" 0.26d0)))) :curves '((:usd-ois :rate 0.04d0)) :discounting '((:usd . :usd-ois)))
[function] FINCL:MAKE-BS-MARKET &KEY VALUATION-DATE (DAY-COUNTER
FINCL:+ACTUAL-365-FIXED+) SPOT RATE (DIVIDEND 0.0d0) DIVIDEND-SCHEDULE VOLA flat Black-Scholes market: a COMPOSITE-MARKET with one underlying and one currency, both
:DEFAULT, discounting on the curve:DEFAULT. Numeric inputs are coerced to double-float; pass double-float or rational literals, since 0.05 reads as a single-float and (float 0.05 1d0) is 0.05000000074505806d0. DIVIDEND-SCHEDULE adds discrete dividends, as in MAKE-MARKET.(make-bs-market :valuation-date #D"2026-09-24" :spot 100 :rate 0.05d0 :vol 0.2d0 :dividend-schedule '(("2027-03-15" 2)))
[generic-function] FINCL:VALUATION-DATE MARKET
The date the market is observed on.
[class] FINCL:DIVIDEND-SCHEDULE FINCL:TERM-STRUCTURE
Known discrete dividends of one underlying. Made by MAKE-DIVIDEND-SCHEDULE.
[function] FINCL:MAKE-DIVIDEND-SCHEDULE ENTRIES
A DIVIDEND-SCHEDULE from ENTRIES, a list of
(ex-date amount &key (kind :cash) pay-date)
EX-DATE and PAY-DATE are dates or "YYYY-MM-DD" strings; PAY-DATE (default EX-DATE) may not precede EX-DATE. A
:CASHAMOUNT is a non-negative sum of money, a:PROPORTIONALone a fraction in [0, 1) of the price.(make-dividend-schedule '((#D"2027-02-10" 0.82d0 :pay-date #D"2027-03-01") (#D"2027-08-10" 0.85d0)))
[function] FINCL:BUMP MARKET FACTOR SHIFT
A new market with the risk FACTOR moved by SHIFT; MARKET is unchanged. FACTOR is (:spot u), (:vol u), (:dividend u) (the continuous yield) or (:dividend-schedule u) (every discrete dividend amount) for underlying U, (:dividend-schedule u ex-date) for the dividends going ex on one date, (:curve id) for a yield curve, or (:quote id selector) for one input quote of a bootstrapped curve, chosen by its helper's tenor or index, the curve then rebootstrapped. SHIFT is (:relative x), multiplying by 1 + x, or (:absolute x), adding x: to the spot, the vol, the yield, the dividend amounts (floored at 0), the rate or the quoted rate.
(bump m '(:spot :spx) '(:relative 1/100)) ; SPX spot up 1% (bump m '(:curve :usd-ois) '(:absolute 1/10000)) ; rates up 1bp (bump m
(:quote :usd-sofr ,#T"5Y") '(:absolute 1/10000)) ; the 5Y quote up 1bp (bump m(:dividend-schedule :aapl ,#D"2027-02-10") '(:absolute 1/100))
3 Options
An option is contract giving the holder the right, but not the obligation, to exercise a purchase or sale of an underlying asset at an agreed-upon price. Options have finite lifetime, and carry various exercise rights. e.g. European options can be exercised on the expiration date, while American options can be exercised at any point before the expiration.
Besides exercise rights, the primary difference of option types is how their payoff is assessed. The major supported option payoff schemes are presented in this section. The user may write their own option payoff schemes (see TODO).
Throughout, $K$ denotes the strike price of the option. $t\in [0, T]$ denotes a time between the inception of the option $0$ and the expiration date $T$ (measured in years), and $S_t$ denotes the price of the underlying asset at time $t$. $\phi$ will $\pm 1$ for calls/puts, respectively.
- [class] FINCL:OPTION FINCL:INSTRUMENT
- [generic-function] FINCL:OPTION-PAYOFF OBJECT
[class] FINCL:PAYOFF
What a contract pays as a function of the observable. Carries no slots: call/put and the option's K belong to the option payoffs in options.lisp, since a coupon or a swap leg has neither. Subclasses use COMPONENT-CLASS too, so construction languages can fill their slots from facts (
:FACTslot option).
[generic-function] FINCL:PAYOFF-VALUE PAYOFF X
Dispatching payoff. Convenient; too slow to call per path.
3.1 Vanilla Options
$$\max(\phi (S_{T} - K) , 0).$$
Exercise is European unless the option says otherwise (see make-option).
[class] FINCL:VANILLA-PAYOFF FINCL:STRIKE-PAYOFF
max(phi (S - K), 0). Engines with closed forms specialize on this class.
(make-instance 'vanilla-payoff :kind :put :strike 40d0)
3.2 Asian Options
With $A$ the average of $S_t$ over the observation dates $t_1,\dots,t_n$ (arithmetic $\frac{1}{n}\sum_i S _{t_i}$ or geometric $(\prod_i S _{t_i})^{1/n}$):
fixed strike: $\max(\phi (A - K), 0)$
floating strike: $\max(\phi (S_T - A), 0)$
European exercise only.
[class] FINCL:ASIAN FINCL:OBSERVED-PATH
The payoff is applied to the average of the observable on DATES (arithmetic or geometric, equal weights). A
:FIXEDstrike pays the payoff of the average; a:FLOATINGstrike pays max(phi (S_T - A), 0).
3.3 Barrier Options
The vanilla payoff, conditional on the path touching a level $H$ before $T$, monitored continuously or on a list of dates. With rebate $R$:
knock-out: the payoff if $H$ is never touched; $R$, paid at the touch, otherwise
knock-in: the payoff if $H$ is touched; $R$, paid at $T$, otherwise
The type is one of :down-and-out, :down-and-in, :up-and-out,
:up-and-in. European exercise only.
[class] FINCL:BARRIER FINCL:OBSERVED-PATH
A single barrier at LEVEL. A knock-out pays nothing once the observable has touched it and pays REBATE when it does; a knock-in pays only if it has, and REBATE at expiry otherwise. Monitored continuously, or on DATES.
3.4 Lookback Options
With $m = \min_t S_t$ and $M = \max_t S_t$ over the observation dates (every simulation step by default):
floating strike: call $S_T - m$, put $M - S_T$
fixed strike: call $\max(M - K, 0)$, put $\max(K - m, 0)$
European exercise only.
[class] FINCL:LOOKBACK FINCL:OBSERVED-PATH
The extremum of the observable: a
:FLOATINGstrike pays phi (S_T - extremum), the minimum for a call and the maximum for a put; a:FIXEDstrike pays the payoff of the maximum (call) or minimum (put).
3.5 make-option
(make-option clause...) builds an option from clauses, which may come in
any order. Arguments of a clause are evaluated.
payoff:
(call K)or(put K); one is requiredexercise:
(european)(default),(american), or(bermudan :dates dates)/(bermudan :every tenor :from date)(expires date), or(expires tenor :from date); required, except thatbermudan :datestakes the last datepath feature, optional:
(average :arithmetic :dates dates)(or:geometric,:every tenor :from date,:strike-type :floating),(barrier :down-and-out level :rebate R :monitoring dates)(continuous by default),(lookback :floating)(or:fixed)(underlying name)and(currency name), when the market has several
(make-option (put 95) (american) (expires #T"1Y" :from +today+))
(make-option (call 100) (barrier :up-and-out 130 :rebate 2) (expires #D"2027-06-15"))
(make-option (call 100) (average :arithmetic :every #T"1M" :from +today+)
(expires #T"1Y" :from +today+))
make-option-from-clauses takes the same clauses as a list, for building
options from data.
[macro] FINCL:MAKE-OPTION &REST CLAUSES
Build an option from clauses: a kind (call/put) and strike or a payoff scheme, an expiry, and optionally exercise rights. With no payoff clause the payoff is vanilla; with no exercise clause the option is European.
A vanilla European call K=110 with 1Y expiry (make-option (call 110) (expiry #
T"1Y" :from +today+)) Clause arguments are evaluated.
[function] FINCL:MAKE-OPTION-FROM-CLAUSES CLAUSES
Build an option from clauses: a kind (call/put) and strike or a payoff scheme, an expiry, and optionally exercise rights. With no payoff clause the payoff is vanilla; with no exercise clause the option is European.
A vanilla European call K=110 with 1Y expiry (make-option (call 110) (expiry #
T"1Y" :from +today+)) CLAUSES is a list of (head . arguments), as data.
4 Pricing engines
(price instrument engine market) returns (values npv standard-error engine).
An instrument is an instance of an instrument: an option, bond, a swap.
An engine is an instance, a keyword designator, a list (:cos :n-terms 512),
a process (priced by the first engine that can), or :auto, which tries the
engines below in order of speed and accuracy and falls back to Monte Carlo with
a warning. Build one with make-engine, which evaluates its arguments.
(make-engine :cos :process (make-heston) :n-terms 512)
(price option :auto market)
Designators:
:black-scholes: closed forms; European, barriers, geometric Asians:baw: American:merton-series: European, Merton jump diffusion:cev: European, CEV with $\beta\le 1$:binomial: American, Bermudan, GBM:cos: European, Bermudan, American; any process with a characteristic function:fd: European, Bermudan, American, barriers; GBM, CEV, local vol, Heston:mc: any exercise and process that can be simulated
4.1 Pricing
Price an instrument with an engine under a market. price returns the
value, its standard error (NIL for deterministic engines) and the engine
used; greeks returns a plist of sensitivities. An engine that cannot price
an instrument signals unsupported-combination, or model-domain-error in a
parameter regime its method does not cover; automatic selection moves on to
the next engine. unsupported-quanto is signalled for an instrument in a
currency other than its underlying's, and invalid-argument for a malformed
argument.
[class] FINCL:INSTRUMENT
A contract. Carries terms only: no market data, no model. Instruments are immutable and reusable across scenarios.
- [class] FINCL:ENGINE
[function] FINCL:MAKE-ENGINE KEY &REST SETTINGS
The engine designated by KEY (:black-scholes, :baw, :rgw, :binomial, :cos, :fd, :mc, :merton-series, :cev, or any class's (:designator ...)) with SETTINGS, its initargs, evaluated.
:PROCESSgoes to engines that take one; an engine whose model is fixed (Black-Scholes, BAW, RGW) accepts a process only of its model, with no parameters set (it prices with the market's data), and takes the process's DIVIDEND-MODEL setting if it has one of its own.(make-engine :binomial :n-steps 4000) (make-engine :cos :process (make-heston :xi 0.5d0) :n-terms 512)
[generic-function] FINCL:PRICE INSTRUMENT ENGINE MARKET
Returns (values npv standard-error engine). The second value is
NILfor deterministic engines; the third is the engine that priced. ENGINE may be an engine designator (src/engines/selection.lisp): a keyword such as :binomial, a list (:cos :n-terms 512) as data, a process to price under with an automatically chosen engine, or :auto for GBM.(price opt (make-engine :binomial :n-steps 4000) m) (price opt (make-heston :xi 0.5d0) m)
[generic-function] FINCL:GREEKS INSTRUMENT ENGINE MARKET &KEY WHICH BUMPS METHOD BATCHES
Sensitivities of INSTRUMENT's price under ENGINE in MARKET, as a plist with the keys in WHICH (default every key of GREEK-KEYS: :delta :gamma :vega :theta :rho :dividend-rho :vanna :volga). BUMPS overrides DEFAULT-GREEK-BUMPS for the methods that bump. Monte Carlo results also carry :standard-errors, a plist with the same keys.
(greeks call (make-instance 'black-scholes-engine) m :which '(:delta :vega)) => (
:DELTA0.6368...:VEGA37.52...)
- [condition] FINCL:UNSUPPORTED-COMBINATION FINCL:PRICING-ERROR
[condition] FINCL:MODEL-DOMAIN-ERROR FINCL:PRICING-ERROR
The engine has a method for the instrument, but its approximation does not hold in this market regime.
[condition] FINCL:UNSUPPORTED-QUANTO FINCL:PRICING-ERROR
An instrument paying in a currency other than its underlying's: pricing it needs an FX vol and correlation fincl does not model.
[condition] FINCL:INVALID-ARGUMENT FINCL:INVALID-INPUT TYPE-ERROR
An argument of the wrong type or shape. Also a
TYPE-ERROR, so handlers written forCHECK-TYPEkeep working.
4.2 Black-Scholes
Closed forms in the forward, the discount factor and the total variance to expiry, so they hold under term structures of rates, dividends and vol. European vanillas; continuous barriers (Reiner-Rubinstein) and discrete monitoring through the continuity correction of Broadie, Glasserman and Kou; discrete geometric Asians.
See F. Black and M. Scholes, The pricing of options and corporate liabilities, Journal of Political Economy 81 (1973); E. Reiner and M. Rubinstein, Breaking down the barriers, Risk 4 (1991); M. Broadie, P. Glasserman and S. Kou, A continuity correction for discrete barrier options, Mathematical Finance 7 (1997); A. Kemna and A. Vorst, A pricing method for options based on average asset values, Journal of Banking and Finance 14 (1990).
[class] FINCL:BLACK-SCHOLES-ENGINE FINCL:ANALYTIC-ENGINE
Black's formula for European vanillas.
4.3 Barone-Adesi-Whaley
Quadratic approximation of the American premium over the European price. Returns the European price where early exercise is never optimal.
See G. Barone-Adesi and R. E. Whaley, Efficient analytic approximation of American option values, Journal of Finance 42 (1987).
[class] FINCL:BARONE-ADESI-WHALEY-ENGINE FINCL:ANALYTIC-ENGINE
Quadratic approximation for American vanillas.
4.4 Merton series
European vanillas under Merton jump diffusion as a Poisson-weighted sum of Black-Scholes prices conditional on the number of jumps.
See R. C. Merton, Option pricing when underlying stock returns are discontinuous, Journal of Financial Economics 3 (1976).
[class] FINCL:MERTON-SERIES-ENGINE FINCL:ANALYTIC-ENGINE
Merton's (1976) series for European vanillas under a jump diffusion: Black prices conditional on the number of jumps, weighted by their Poisson probabilities.
(make-instance 'merton-series-engine :process (make-instance 'merton-jump :intensity 1))
4.5 CEV formula
European vanillas under CEV with $\beta\le 1$ and absorption at zero, in terms of the noncentral $\chi^2$ distribution.
See R. Schroder, Computing the constant elasticity of variance option pricing formula, Journal of Finance 44 (1989).
[class] FINCL:CEV-ENGINE FINCL:ANALYTIC-ENGINE
Schroder's (1989) noncentral chi-square formula for European vanillas under CEV with absorption at zero, beta <= 1.
(make-instance 'cev-engine :process (make-instance 'cev :beta 0.5d0))
4.6 Binomial tree
Cox-Ross-Rubinstein tree for GBM. By default the last step is valued with the Black-Scholes formula to remove the odd-even oscillation (BBS), and the price is $2v(N)-v(N/2)$ (BBSR). Bermudan dates snap to the nearest step.
n-steps: steps in the treesmooth: Black-Scholes on the last stepextrapolate: Richardson extrapolation
See J. C. Cox, S. A. Ross and M. Rubinstein, Option pricing: a simplified approach, Journal of Financial Economics 7 (1979); M. Broadie and J. Detemple, American option valuation: new bounds, approximations, and a comparison of existing methods, Review of Financial Studies 9 (1996).
[class] FINCL:BINOMIAL-ENGINE FINCL:ENGINE
Cox-Ross-Rubinstein binomial tree.
(make-instance 'binomial-engine :n-steps 5000)
4.7 COS
Fourier-cosine expansion of the density of the log-return, with coefficients from the characteristic function. Europeans need only the characteristic function; Bermudans and Americans use the backward recursion, which needs state-independent log-increments, with the American price extrapolated from Bermudans of $M, 2M, 4M, 8M$ dates.
n-terms: terms in the expansiontruncation: half-width $L$ of the truncation range, in cumulant scalerichardson-dates: $M$
See F. Fang and C. W. Oosterlee, A novel pricing method for European options based on Fourier-cosine series expansions, SIAM Journal on Scientific Computing 31 (2008), and Pricing early-exercise and discrete barrier options by Fourier-cosine series expansions, Numerische Mathematik 114 (2009).
[class] FINCL:COS-ENGINE FINCL:ENGINE
Fang and Oosterlee's Fourier-cosine (
COS) method. Europeans need only a characteristic function; Bermudans and Americans use the backward recursion of their 2009 paper, which needs a process whose log-increments are independent of the state (the INDEPENDENT-INCREMENTS mixin; GBM).(make-instance 'cos-engine :process (make-instance 'heston) :n-terms 160)
4.8 Finite differences
Crank-Nicolson on a log-spot grid concentrated at the strike, with Rannacher start-up after each payoff discontinuity. Americans and Bermudans by Ikonen-Toivanen; barriers by truncating the grid or by events on the monitoring dates. Heston by Hundsdorfer-Verwer ADI on a (log-spot, variance) grid. Jump processes are refused.
n-space,n-variance,n-time: grid sizestheta: time-stepping weight, $\frac{1}{2}$ is Crank-Nicolsonrannacher-steps: implicit substeps after a discontinuityconcentration,width: grid concentration and half-width in standard deviations
See R. Rannacher, Finite element solution of diffusion problems with irregular data, Numerische Mathematik 43 (1984); S. Ikonen and J. Toivanen, Operator splitting methods for American option pricing, Applied Mathematics Letters 17 (2004); K. J. in 't Hout and S. Foulon, ADI finite difference schemes for option pricing in the Heston model with correlation, International Journal of Numerical Analysis and Modeling 7 (2010).
[class] FINCL:FD-ENGINE FINCL:ENGINE
Finite differences in log-spot: a theta-scheme with Rannacher start-up on a sinh-concentrated grid, Ikonen-Toivanen splitting for American exercise, continuous barriers as boundary conditions; Heston by Hundsdorfer-Verwer ADI.
(make-engine :fd :process (make-local-vol) :n-space 400 :n-time 400)
4.9 Monte Carlo
Simulates the paths of any process that defines a stepper. Terminal-only payoffs sample the terminal value exactly where the process allows; the rest step through a time grid containing every observation date. Americans and Bermudans by least-squares regression on the continuation value. Barriers monitored continuously are corrected with the Brownian bridge. Prices do not depend on the number of threads or chunks.
process,n-paths,n-steps,seedrng::counter(counter-based Philox),:sobol(randomized quasi-Monte Carlo) or arandom-stategeneratorantithetic: antithetic pairscontrol-variates::european,:geometric-asian
See P. Glasserman, Monte Carlo Methods in Financial Engineering (2004); F. A. Longstaff and E. S. Schwartz, Valuing American options by simulation: a simple least-squares approach, Review of Financial Studies 14 (2001); J. K. Salmon, M. A. Moraes, R. O. Dror and D. E. Shaw, Parallel random numbers: as easy as 1, 2, 3, Proceedings of SC11 (2011); S. Joe and F. Y. Kuo, Constructing Sobol sequences with better two-dimensional projections, SIAM Journal on Scientific Computing 30 (2008).
- [class] FINCL:MONTE-CARLO-ENGINE FINCL:ENGINE
5 Simulation
simulate is a construct that allows one to simulate paths of a process
or processes, and evaluates lisp forms on a list of days in the simulation.
Paths come from the process protocol that the Monte Carlo engine uses. The
lisp forms evaluated and tracked on these days can be :state variables
from the process, or symbols declared in :start and :hold. This allows trading
and hedging strategies to be simulated, where one can write trackers for
PnL, max drawdown, etc. Because the maximum resolution of the simulation
is daily actions, these simulations cannot model complex intraday statistics
and strategies.
(simulate (process market dates &key n-paths seed rng antithetic n-steps max-dt
correlation keep market-from-state)
(:accumulate (var init) ...) ; per-path doubles
(:hold (var init) ...) ; per-path objects
(:portfolio var [init] &key record engine cash cash-curve collect) ; a per-path book, one clause each
(:state var name [underlying]) ; a state component, e.g. :variance
(:start [([market] &key time)] form ...) ; at the valuation date
(:every (date [market] &key time dt) form ...) ; at each of DATES
(:on date-list (i [market] &key time dt) form ...) ; at the dates of a list
(:final (name form) ...)) ; named per-path outputs
Within :start, :every and :on bodies, (record name value) adds the
real VALUE to the statistic NAME (a keyword) at the current date, and returns
VALUE; (stop) ends the path, after which its later dates run no clauses and
record nothing (:final still runs); (previous var) is a :state
variable's value at the previous date. All are matched by name in any
package. time and dt bind the date's market time and its step from the
previous date.
MARKET is the date's market within the simulation, holding its curves,
surfaces and dividends; it is built lazily, only doing so if the forms use it.
Recording. A statistic is over everything recorded under NAME at a date,
so it summarizes the paths at that date. Recording at the same date more than
once under one name pools the values, and a date where nothing was recorded
holds NaN (a count of 0). record in :start goes to the valuation date.
Recorded values are streamed into summarizing statistics, each (name,
date) keeps the count, mean, standard deviation, minimum and maximum, and
:keep :quantiles adds quantiles. Read the results with
(simulation-statistic result name statistic), which gives a vector over
simulation-dates, and list the names with simulation-recorded-names. Use
record for a quantity followed through time, such as a hedging balance or a
spot, and a :final output for the per-path quantity at the end such as
profit-loss, since :final keeps one value per path. In a :portfolio
clause the key :record lists :value and Greek keys to record each date under
the names
(var-keyword key), e.g. (:book :delta) for the book book and the key
:delta. Several :portfolio clauses run several books on the same paths,
so their outputs are paired; without :final each book's value is an output
named by its variable.
Outputs. Each :final entry is a number per path for each path. All outputs
come from the same paths, so a quantity computed from several (a difference, a
ratio, an indicator) is a paired estimate on common random numbers:
simulation-summary gives its mean and standard error, with antithetic pairs
averaged first, and the standard error of a difference $X-Y$ is
$\sqrt{(\sigma_X^2+\sigma_Y^2-2\rho\sigma_X\sigma_Y)/n}$, small when the
outputs are correlated. For example, the following code simulates a
delta-hedging strategy against a short call position, comparing :hedged
strategy against an :unhedged strategy. At each date, the underlying is traded
to neutralize the net delta exposure of the holdings.
(simulate ((make-gbm) *market* *dates* :n-paths 20000)
(:accumulate (shares 0d0) (cash 0d0) (premium 0d0))
(:state s :spot)
(:start (market)
;; Sell the call option to open the position
(setf premium (price call :black-scholes market))
(incf cash premium))
(:every (date market)
(when (date< date expiry)
(let ((delta (getf (greeks call :black-scholes market :which '(:delta)) :delta)))
;; Neutralize delta exposure
(decf cash (* (- delta shares) s))
(setf shares delta))))
;; Return final balances
(:final (:hedged (+ cash (* shares s) (- (payoff-value (option-payoff call) s))))
(:unhedged (- premium (payoff-value (option-payoff call) s)))))
Collection. record keeps count, mean, variance, min and max per name and
date, merged in chunk order; :keep :quantiles keeps the values for
quantiles, :keep (:paths k) the first $k$ paths' states, held objects
(whose markets path-markets rebuilds) and recorded values
(simulation-path-record), :keep :states every path's.
Several underlyings. PROCESS may be a list of (underlying process) pairs,
each stepped on its own view. :correlation ((u1 u2 rho) ...) correlates
the Brownian motions $W^{(1)}, W^{(2)}$ driving the two spots: with
spot-loadings $a, b$ ($W^{(1)}=\sum_k a_k Z^{(1)}_k$, unit norm), factors
$i$ and $j$ are correlated at $\rho\,a_i b_j$, so
$\operatorname{corr}(W^{(1)}, W^{(2)})=\rho$ whatever the processes' own
factors (Heston's variance shock included). A square matrix over every factor
gives full control.
(simulate (((:aapl (make-heston)) (:msft (make-gbm))) market dates
:correlation '((:aapl :msft 0.6d0)) :keep (:paths 20))
(:state a :spot :aapl)
(:state m :spot :msft)
(:every (date) (record :basket (+ (* 2 a) m))))
Clauses must not start parallel work: paths already run in parallel, and pricing inside a clause is serial.
See P. Glasserman, Monte Carlo Methods in Financial Engineering (2004); D. Bertsimas, L. Kogan and A. W. Lo, When is time continuous?, Journal of Financial Economics 55 (2000).
[macro] FINCL:SIMULATE (PROCESS MARKET DATES &REST OPTIONS) &BODY CLAUSES
Simulate paths of PROCESS from MARKET's valuation date through DATES, run the clauses' logic on every path, and return a SIMULATION-RESULT. DATES is an ascending list of dates after the valuation date; the last is the end of every path.
PROCESS is a process, or a literal list of legs (target process &rest options), each leg's process driving one market component, its target: (:spot u) the spot of underlying U, (:vol u), (:dividend u), (:dividend-schedule u) or (:curve id). A bare keyword U is (:spot u), so ((:spx (make-gbm)) (:vix (make-heston))) simulates two spots. The leg options go to STRUCTURE-AT-STATE. A process given alone drives the market's only underlying's spot. OPTIONS: :n-paths 10000 paths simulated. :seed 42 the random seed. :rng :counter :counter (a path's draws do not depend on N-PATHS, chunks or workers), :sobol, or a random-state designator. :antithetic
NILpair each path with its mirror image; statistics and SIMULATION-SUMMARY then work on pair means. :n-steps :max-dt fill the gaps between DATES with extra steps (default one step per gap); the clauses still run only on DATES. :correlation correlations between legs, a list of (leg leg rho) naming legs by target or underlying, e.g. ((:spx :ndx 0.6d0)), or a factor matrix, as in MAP-SIMULATED-PATHS. :keep what to store for later::QUANTILES(per-date quantiles of every recorded name), (:PATHSk) (states and held values of the first k paths; k is evaluated),:STATES, or a list of these. :market-from-state a function building a date's market from the simulated states, replacing MARKET-AT-STATE. :fix a list of rate indexes, e.g. (list (euribor #T"6M")). On each date the index fixes, its fixing is read from that date's simulated curve, and the markets of later dates hold it, so instruments priced there use the path's own past fixings. Pricing needs every fixing date among DATES (FIXING-DATES lists an instrument's).Optional clauses.
:ACCUMULATEand:HOLDmay repeat,:PORTFOLIOonce per variable, and:FINALappears once; the logic clauses run in the order written. (:accumulate (var init) ...) per-pathDOUBLE-FLOATvariables, reset to INIT on every path (an integer INIT is coerced; assigning a non-double is an error). (:hold (var init) ...) per-path variables of any type; INIT is evaluated afresh on every path, so (:hold (v (make-array 5))) gives each path its own array. Readable later with SIMULATION-HELD for the kept paths. (:portfolio var [init] &key record engine cash cash-curve collect) VAR is a per-path PORTFOLIO (INIT, default empty), changed with ADJUST-POSITION and priced with ENGINE. RECORD lists:VALUE,:CASHand Greek keys; each is recorded every date under the name (var-keyword key), e.g. (:book :delta). Several clauses simulate several books on the same paths, each with its own cash. Without:FINALthe outputs are the books' values::VALUEfor one book, (var-keyword) for each of several. CASH (a real, evaluated per path), or a CASH-ACCOUNT position in INIT, makes the book self-financing: on each date after the first, before the clauses, its cash grows by D(t_k-1)/D(t_k) (the path's discount on the currency's discount curve, or CASH-CURVE's; the initial curve's when no leg simulates it), then each position's income over the interval (dividends, coupons and redemptions, option payoffs at expiry; COLLECT lists the kinds paid, default:ALLof:DISCRETE-DIVIDEND:CONTINUOUS-DIVIDEND:COUPON:REDEMPTION:EXPIRY) is paid into it, and matured bonds and expired options leave the book. An option held must expire on a date of DATES. (:state var name [leg]) VAR is bound to the double-float state component NAME (:spot, :variance, ... see SIMULATION-STATE-NAMES) of the leg (an underlying, or a target) at the current date. (:derive target ([market [date]]) form ...) sets TARGET's component in every market built from the paths to the value of the forms, computed from DATE, MARKET (that date's market, with the legs' components and earlier:DERIVEtargets already set) and the:STATEvariables. The forms cannot see:ACCUMULATEor:HOLDvariables, RECORD or STOP, so the component depends only on the date and the simulated states. TARGET may not be a leg's. For example, a flat implied vol that follows the spot S (a:STATEvariable): (:derive (:vol :spx) () (make-instance 'flat-black-vol :vol (* 0.002d0 s))) (:start [([market] &key time)] form ...) at the valuation date, before the first step. The optional (market) binds that date's market,TIME0. RECORD here goes to the valuation date, the first of SIMULATION-DATES. (:every (date [market] &key time dt) form ...) at every date of DATES. DATE is bound to the date, MARKET to the market on it built from the simulated states,TIMEto its market time and DT toTIMEless the previous date's (doubles). (:on date-list (i [market] &key time dt) form ...) at the dates of DATE-LIST (a subset of DATES), I being the date's position in the list. (:final (name form) ...) one clause: named per-path outputs, evaluated after the last date (or after STOP) from the final state; NAME is a keyword. (:final form) is (:final (:value form)). MARKET in the forms is the market of the path's last date. MARKET is built only if the clause uses it, and a global special variable may serve as its name. Clause code runs in serial. An error in a clause is re-signalled in the caller.Inside
:START,:EVERYand:ONbodies these local operators are available, matched by name in any package: (record name value) adds the real VALUE to the statistic NAME at the current date. NAME is a keyword. The statistic at a date is over all the values recorded under NAME at it. The streamed statistics are the mean, standard deviation, minimum, maximum and count (quantiles also with:KEEP:QUANTILES); individual values are not stored. It returns VALUE. (stop) ends the path: its later dates run no clauses and record nothing, and:FINALstill runs. (path-discount [curve]) the discount from the valuation date to the current date along this path, on CURVE ((:curve id); default the discount curve of the market's only currency). When a leg simulates that curve it is exp(-integral of the short rate) on the path; otherwise it is the initial market's discount factor. Also available in:FINAL. (previous var) the:STATEvariable VAR's value at the previous date (the valuation date's at the first). With:PORTFOLIOclauses, also, BOOK being one of their variables and holding cash: (trade book instrument &key by to engine) buys or sells INSTRUMENT in BOOK to quantity TO, or BY a change, at its price on the date's market (ENGINE, else the position's, else the book's), paid from BOOK's cash; returns the cash paid. A position sold to 0 leaves the book. (deposit book amount) (withdraw book amount) move a non-negative AMOUNT into or out of BOOK's cash; return the balance.A leg's process may be a PHYSICAL-PROCESS (CHANGE-MEASURE): its state then evolves under the physical measure, while each date's market is built from that state with the risk-neutral process, so prices in the clauses stay arbitrage-free. Legs under both measures form one physical model in which the risk-neutral legs carry no premium. SIMULATION-MEASURE is then
:PHYSICAL, and discounted means of outputs are physical expectations, not prices.Results of simulation in SIMULATION-RESULT: :final outputs SIMULATION-VALUES (one number per path), SIMULATION-MEAN, SIMULATION-STANDARD-ERROR, SIMULATION-QUANTILE. Differences of outputs are paired estimates on common random numbers. recorded names SIMULATION-STATISTIC (a vector over SIMULATION-DATES), SIMULATION-RECORDED-NAMES. kept paths SIMULATION-PATH-STATE, SIMULATION-HELD, SIMULATION-PATH-RECORD (each RECORD of the path, by date), PATH-MARKETS. any vector SIMULATION-SUMMARY gives the mean and standard error. The function underneath is MAP-SIMULATED-PATHS.
;; A short CALL delta-hedged on DATES, which end on its EXPIRY. The ;; balance is recorded each date (read it with SIMULATION-STATISTIC) and the ;; terminal P&L is a :final output (read it with SIMULATION-VALUES). (simulate ((make-gbm) market dates :n-paths 20000) (:accumulate (shares 0d0) (cash 0d0) (premium 0d0)) (:state s :spot) (:start (market) (setf premium (price call :black-scholes market)) (incf cash premium)) (:every (date market) (when (date< date expiry) (let ((delta (getf (greeks call :black-scholes market :which '(:delta)) :delta))) (decf cash (* (- delta shares) s)) (setf shares delta))) (record :balance (- (+ cash (* shares s)) (price call :black-scholes market)))) (:final (:hedged (+ cash (* shares s) (- (payoff-value (option-payoff call) s)))) (:unhedged (- premium (payoff-value (option-payoff call) s)))))
;; The same hedge as a self-financing book: the short call's payoff is ;; paid from cash at EXPIRY, so the book's final value is the P&L. (simulate ((make-gbm) market dates :n-paths 20000) (:portfolio book (make-portfolio "hedge" (make-position call :quantity -1)) :cash (price call :black-scholes market) :engine :black-scholes) (:every (date market) (when (date< date expiry) (trade book (make-holding) :to (getf (greeks call :black-scholes market :which '(:delta)) :delta)))) (:final (:pnl (price book :black-scholes market))))
;; The exposure of a SWAP when the curve it prices on follows Hull-White: ;; its INDEX fixes along each path on the simulated curve, and ;; PATH-DISCOUNT discounts along the path. (simulate ((make-hull-white :a 0.03d0 :sigma 0.008d0) market (sort (append dates (fixing-dates swap market)) #'date<) :n-paths 5000 :fix (list index) :keep :quantiles) (:every (date market) (record :exposure (max 0d0 (swap-npv swap market))) (record :discounted (* (path-discount) (swap-npv swap market)))) (:final (:pv (* (path-discount) (swap-npv swap market)))))
[function] FINCL:MAP-SIMULATED-PATHS VISITOR PROCESS MARKET DATES &KEY (N-PATHS 10000) (SEED 42) (RNG
:COUNTER) (SAMPLER:BOX-MULLER) ANTITHETIC N-STEPS MAX-DT EVERY-STEP (OUTPUTS 1) CORRELATION DERIVESimulate N-PATHS paths of PROCESS from MARKET's valuation date to the last of DATES and show each to VISITOR; returns the per-path outputs, an n-paths x OUTPUTS column-major DOUBLE-VECTOR (output k of path i at i + k n-paths; with one output, the per-path values in path order).
PROCESS is a stochastic process, or a list of legs (target process &rest options) on the composite MARKET, each stepped on its own view; a target is (:spot u), (:vol u), (:dividend u), (:dividend-schedule u) or (:curve id), a bare keyword U meaning (:spot u), and the options go to STRUCTURE-AT-STATE. CORRELATION correlates the legs' first factors, a list of (leg1 leg2 rho) naming legs by target or underlying, or every factor, a square 2-D array in leg order. DERIVE is as for MAKE-SIMULATION-PLAN; it sets components of the markets MARKET-AT-STATE builds from the plan. The grid (MAKE-TIME-GRID) holds DATES, the dividend ex-dates before the last date, and steps of at most the span over N-STEPS (or MAX-DT); with neither, one step per gap. Normals come from the Monte Carlo engine's generators (RNG, SEED, SAMPLER), so path i is the engine's path i on the same grid and does not depend on N-PATHS or the number of workers; under ANTITHETIC the second half of the paths are the first half's partners.
VISITOR is called once per chunk of paths with the chunk index and returns (values start step finish), closures called for one path at a time: (start path-index state) at the valuation date;
NILstops the path (step path-index k state) at the K-th date of DATES (1-based; with EVERY-STEP, at every grid index K);NILstops (finish path-index state values) writes the path's OUTPUTS doubles intoVALUES(01) STATE is the process's state vector (a vector of them, one per leg, for a list of legs); it is reused, so copy what you keep.(map-simulated-paths (lambda (chunk) (declare (ignore chunk)) (values (constantly t) (constantly t) (lambda (i state values) (declare (ignore i)) (setf (aref values 0) (aref state 0))))) (make-gbm) m (list #D"2027-09-24") :n-paths 1000)
[generic-function] FINCL:MARKET-AT-STATE MARKET SIMULATION DATE STATES
MARKET as of DATE built from the simulated states: STATES is a vector of the legs' state vectors in the order of (SIMULATION-UNDERLYINGS SIMULATION). The default, for a composite market, ages MARKET to DATE in one copy of its tables, sets each leg's target to STRUCTURE-AT-STATE of its state (a spot leg: element 0), then each
:DERIVEtarget to its function's value; every other component (curves, dividend schedules, vol structures, fixings) is kept. Define a method on your market class, or pass:MARKET-FROM-STATEto SIMULATE (a function of the same arguments), to build markets otherwise.(market-at-state m plan #D"2027-03-24" states)
[function] FINCL:SIMULATION-UNDERLYINGS SIMULATION
The legs SIMULATION steps, in order: the underlying of a spot leg (
NILfor a market that is not composite), the target (kind key) of any other. MARKET-AT-STATE's STATES follow this order.
[generic-function] FINCL:SPOT-LOADINGS PROCESS
The loadings of the Brownian motion driving PROCESS's observable on its factors, a DOUBLE-VECTOR of length PROCESS-FACTORS with unit norm: W = sum_k loading_k Z_k in the continuous-time limit. Correlating two processes' observables at c correlates their factors i and j at c a_i b_j (SIMULATE's
:CORRELATION). The default puts it all on factor 0.(spot-loadings (make-heston :rho -0.6d0)) => #(-0.6d0 0.8d0)
[function] FINCL:SIMULATION-STATE-NAMES PROCESS
The names a
:STATEclause may use for PROCESS, a process or a list of legs (target process &rest options): the process's state names, or (component leg) lists for legs, a spot leg named by its underlying and any other by its target.(simulation-state-names (make-heston)) => (
:SPOT:VARIANCE) (simulation-state-names `((:aapl ,(make-heston)) (:msft ,(make-gbm)))) => ((:SPOT:AAPL) (:VARIANCE:AAPL) (:SPOT:MSFT))
[class] FINCL:SIMULATION-RESULT STRUCTURE-OBJECT
What SIMULATE collected: per-path outputs by name, per-date statistics by name, and what
:KEEPstored. Read it with SIMULATION-VALUES, SIMULATION-MEAN, SIMULATION-STANDARD-ERROR, SIMULATION-QUANTILE, SIMULATION-SUMMARY, SIMULATION-STATISTIC, SIMULATION-HELD and PATH-MARKETS.
[function] FINCL:SIMULATION-OUTPUT-NAMES RESULT
The names of RESULT's outputs, in the order of SIMULATE's
:FINAL.
[function] FINCL:SIMULATION-VALUES RESULT &OPTIONAL NAME
The per-path values of RESULT's output NAME (optional with one output), a DOUBLE-VECTOR in path order; under antithetics the second half holds the partners of the first.
[function] FINCL:SIMULATION-MEAN RESULT &OPTIONAL NAME
The mean of RESULT's output NAME (see SIMULATION-SUMMARY).
[function] FINCL:SIMULATION-STANDARD-ERROR RESULT &OPTIONAL NAME
The standard error of the mean of RESULT's output NAME (see SIMULATION-SUMMARY).
[function] FINCL:SIMULATION-QUANTILE RESULT NAME P
The P-quantile of RESULT's output NAME over every path (NAME may be
NILwith one output).
[function] FINCL:SIMULATION-SUMMARY RESULT VECTOR
(values mean standard-error) of
VECTOR, a per-path vector of RESULT's length in path order, such as an output or a quantity computed from several (a difference, a ratio, an indicator). Antithetic partners are averaged first, and under:SOBOLthe randomizations, so the standard error is that of the estimator. Outputs share their paths, so the standard error of a difference is that of the paired differences.(simulation-summary r (map 'double-vector #'- (simulation-values r :a) (simulation-values r :b)))
[function] FINCL:SIMULATION-STATISTIC RESULT NAME STATISTIC &OPTIONAL P
A DOUBLE-VECTOR over (SIMULATION-DATES RESULT) of STATISTIC of the values recorded under NAME:
:MEAN,:STD-DEV,:MIN,:MAX,:COUNT, or:QUANTILEwith P (needs:KEEP:QUANTILES). A date where nothing was recorded holds NaN (0 for:COUNT).(simulation-statistic r :hedge-value :mean)
[function] FINCL:SIMULATION-RECORDED-NAMES RESULT
The names RESULT recorded with RECORD, keywords or lists, in printed order.
[function] FINCL:SIMULATION-DATES OBJECT
The valuation date followed by the dates the path logic sees, in order: the dates of a SIMULATION-PLAN or of a SIMULATION-RESULT. Per-date statistics are vectors over these dates.
[function] FINCL:SIMULATION-HELD RESULT PATH NAME
The values of the
:HOLDor:PORTFOLIOvariable NAME (a keyword, the variable's name) on stored PATH at each simulation date, a vector.
[function] FINCL:SIMULATION-PATH-RECORD RESULT PATH NAME
The values stored PATH (
:KEEP(:PATHSk) or:STATES) recorded under NAME at each of (SIMULATION-DATES RESULT), a DOUBLE-VECTOR with NaN where the path recorded nothing (before its first record of NAME, or after STOP); the last value recorded on a date. A book's records are named by their lists.(simulation-path-record r 0 :balance) (simulation-path-record r 0 '(:book :value))
[function] FINCL:PATH-MARKETS RESULT PATH
((date . market) ...) for stored PATH (
:KEEP(:PATHSk) or:STATES), each market built from the path's state on its date as during the run, at every simulation date from the valuation date on.(path-markets r 0)
5.1 Simulated market components
By default only the spots move along a path: on each date the market is rebuilt with the simulated spots, and its curves, vol surfaces, dividends and fixings stay as they were on day 0. A simulation can also rebuild those other parts on each date, either from a process or from a formula.
Two words are used below. The world is what determines the market on each
date: the processes stepped along the paths and the :derive forms. The
desk is the clause code: what is held, how it is priced, when it is
hedged, and which model it prices with. The desk reads the world's markets;
nothing the desk does changes the paths.
What a run measures. Every process here is risk-neutral: the average discounted price of anything the world prices stays equal to today's price. A strategy whose prices agree with the world therefore has an average discounted P&L of 0. A run measures the spread of the P&L (hedging error), the cost of a decision rule (when to exercise, when to call), exposure and its tails, and what the desk gains or loses when its prices differ from the world's. For example, a 2-year at-the-money straddle marked by Black-Scholes on a 20% surface, in a Heston world with vol of vol 0.5, is worth 22.51 to the desk and 19.75 in the world, and its average mark falls from the first to the second over its life.
Targets. A component is named in the factor syntax of bump:
(:spot u), (:vol u), (:dividend u), (:dividend-schedule u) and
(:curve id); a bare keyword u means (:spot u). market-component
reads one from a market.
Legs. PROCESS may be a list of legs (target process &rest options),
each stepped on its own; the options go to structure-at-state, which turns
the leg's state on a date into its component. process-targets lists the
kinds a process can drive. :correlation and (:state var name leg) name a
leg by its target or, for a spot, its underlying.
(simulate ((((:spot :spx) (make-heston))
((:curve :usd-ois) (make-hull-white :a 0.03d0 :sigma 0.008d0) :knots tenors))
market dates :correlation (((:spot :spx) (:curve :usd-ois) 0.2d0)))
...)
Formulas. (:derive target ([market [date]]) form ...) sets a component
on every date from the date, the market built so far and the :state
variables. Its forms see nothing else of the path (no :accumulate or
:hold variable, no record), so a component depends only on the date and
the simulated states, and path-markets rebuilds it exactly.
(:derive (:curve :usd-libor-3m) (market) ; a basis over a simulated curve
(bump-structure (market-component market '(:curve :usd-ois)) '(:absolute 0.0015d0)))
(:derive (:vol :spx) (market date) ; a surface per date from a table
(gethash date surfaces))
Hull-White curves. A Hull-White leg simulates the short rate
$r = x + \alpha(t)$, $\alpha(t) = f(0,t) + \frac{\sigma^2}{2a^2}(1-e^{-at})^2$,
and its integral exactly: over a step $\Delta$,
$x_{t+\Delta} = x_t e^{-a\Delta} + \varepsilon_1$ and
$\int_t^{t+\Delta} x\,ds = x_t B(\Delta) + \varepsilon_2$, $B(\Delta) = (1-e^{-a\Delta})/a$,
with $(\varepsilon_1,\varepsilon_2)$ Gaussian,
$\operatorname{Var}\varepsilon_1 = \frac{\sigma^2}{2a}(1-e^{-2a\Delta})$,
$\operatorname{Var}\varepsilon_2 = \frac{\sigma^2}{a^2}\big(\Delta - 2B(\Delta) + \frac{1-e^{-2a\Delta}}{2a}\big)$,
$\operatorname{Cov} = \frac{\sigma^2}{2}B(\Delta)^2$. The curve on a date is
the model's own bond price function $\tau \mapsto P(t,t+\tau\mid r_t)$
(state-discount-bond), exact at every maturity and evaluated only when a
price asks for it; with :knots (tenors) it is those bond prices
log-linear in discount factors between the knots, as before task 33, and only
that curve has a snapshot-form. Every rates instrument prices on either
unchanged. market-curve-discount reads a curve of a market with several
underlyings. (path-discount [curve]) in a clause is
$\exp(-\int_0^t r\,ds)$ on the path when a leg simulates that curve, and
today's discount factor otherwise, so its average is today's discount
factor. :fix (list index ...) records each index's fixing on each date from
that date's simulated curve, and later markets on the path carry them;
pricing needs every fixing date among DATES (fixing-dates).
Derived surfaces. rescale-vol-structure keeps a surface's smile and
sets its at-the-money level to a function $a(\tau)$:
$w'(k,\tau) = w(k,\tau)\,a(\tau)/w(0,\tau)$ in total variance at
log-moneyness $k$. Driven by a simulated Heston variance $v$,
$a(\tau) = \theta\tau + (v-\theta)\frac{1-e^{-\kappa\tau}}{\kappa}$, the
expected variance to $\tau$, so a shock to $v$ fades over longer maturities
as the model says. This level is the variance-swap level, a little above
Heston's own implied variance when the vol of vol is not 0; with vol of vol 0
the two agree.
(simulate (heston market dates)
(:state v :variance)
(:derive (:vol :spx) (market)
(rescale-vol-structure (market-component market '(:vol :spx))
(lambda (tau) (+ (* theta tau) (* (- v theta) (/ (- 1 (exp (- (* kappa tau)))) kappa))))))
(:every (date market)
(record :straddle (+ (price call :black-scholes market) (price put :black-scholes market)))))
The desk's model. The library never refits a model. A desk that refits
keeps its model in :hold and calls calibrate on the date's market, for
example to (surface-quotes market :spx options), the options quoted at the
market's vols. Calibration inside a clause is serial, so results do not
depend on the worker count. One warm-started Heston refit to six quotes
with COS takes about 0.3 s, so a weekly refit over a year at 1,000 paths
takes about four hours on one worker.
(:hold (desk heston-0))
(:every (date market)
(setf desk (handler-bind ((convergence-failure #'use-best))
(calibrate desk market (surface-quotes market :spx options) :engine :cos)))
(record :mark (price straddle (make-engine :cos :process desk) market)))
Writing a component model. A process drives a non-spot component when
it lists the kind in process-targets, steps with make-stepper and
defines structure-at-state; a curve process that names a state component
:integral (the integral of its short rate) is discounted by
path-discount. A :derive form can also move a component by an
independent factor, such as a random level scaling every implied vol by
$e^x$. Then the average surface rises (with $\operatorname{Var} x = 0.04$
after a year, every vol averages 2% above today's), the stock's own
volatility does not follow the surface, a shock moves all maturities
alike, and a parametric surface (SSVI) changes shape as well as level. The
library ships only components computed from the world's own state.
Pitfalls.
Rates move together. Hull-White has one source of randomness, so every maturity of the curve moves in the same direction: over a month the 2-year and 10-year zero rates move with correlation 1.00. A trade that profits when the curve steepens shows almost no P&L, and hedging a 7-year bond with 2- and 10-year ones, rebalanced 24 times over 19 months, leaves a residual of about 0.01% of its value. Neither says anything about the real trade.
The stock does not feel the rates. The stock is stepped on today's rates, not on the rates simulated beside it. Uncorrelated with them, its average discounted price stays at today's spot; correlated, it does not: at correlation 0.5 with a Hull-White rate ($\sigma = 1\%$) the average discounted price of a 100 stock after 5 years is 98.8.
A derived surface keeps today's shape.
rescale-vol-structuremoves the level of the surface and keeps today's smile: if the 1-year 90-strike vol is 1.7 points above the at-the-money 20%, it is 2.5 points above an at-the-money 30%. A strategy that depends on the skew changing is not captured.A refit changes the desk, not the world. Refitting a model in a clause changes the prices and hedges the clause sees. The stock's paths are the same, bit for bit, with or without the refit.
Glossary.
World: the legs and
:deriveforms, which determine the market on each date.Desk: the clause code, which prices, hedges and refits on those markets.
Target: the name of one market component, such as
(:curve :usd-ois).Derived component: a component set on each date by a
:deriveform.
See J. Hull and A. White, Pricing interest-rate-derivative securities, The Review of Financial Studies 3 (1990); P. Glasserman, Monte Carlo Methods in Financial Engineering (2004), section 3.3; R. Ahmad and P. Wilmott, Which free lunch would you like today, sir?, Wilmott Magazine (2005).
[function] FINCL:MARKET-COMPONENT MARKET TARGET
The component of the composite MARKET that TARGET names, in BUMP's factor syntax: (:spot u) the spot of underlying U (a bare keyword U means the same), (:vol u) its vol structure, (:dividend u) its continuous dividend curve, (:dividend-schedule u) its discrete dividends, (:curve id) the yield curve ID. A component the market lacks signals MISSING-MARKET-DATA listing what it has.
(market-component m '(:curve :usd-ois)) (market-component m :spx) ; the SPX spot
[generic-function] FINCL:PROCESS-TARGETS PROCESS
The kinds of market component PROCESS can drive in SIMULATE, from (:spot :vol :dividend :dividend-schedule :curve): (
:SPOT) for every equity process. The first is the kind a process given alone drives.(process-targets (make-gbm)) => (
:SPOT)
[generic-function] FINCL:STRUCTURE-AT-STATE PROCESS TARGET INITIAL MARKET DATE STATE &KEY KNOTS &ALLOW-OTHER-KEYS
The market component TARGET (e.g. (:spot :spx) or (:curve :usd-ois)) on DATE, on a path where PROCESS's state vector is STATE. INITIAL is the component in the initial market; MARKET is the market on DATE built so far (aged, with the components of the legs before this one set). The keys are the leg's options in SIMULATE, e.g.
:KNOTSin ((:curve :usd-ois) (make-hull-white) :knots tenors). The method for a spot returns element 0 of STATE.Define a method on a process class to let it drive another kind of component; it must also list the kind in PROCESS-TARGETS.
(structure-at-state (make-gbm) '(:spot :spx) 100d0 m d #(104.2d0)) => 104.2d0
[function] FINCL:FIXING-DATES INSTRUMENT &OPTIONAL MARKET
The dates the floating rates of the rates INSTRUMENT fix on, ascending and distinct; with MARKET, only those after its valuation date. A SIMULATE run that prices INSTRUMENT along its paths needs them among its dates, with the index in
:FIX.(fixing-dates swap m) ; => (#D"2027-03-24" #D"2027-09-23" ...)
[generic-function] FINCL:STATE-DISCOUNT-BOND PROCESS STATE T0 T1
The price at T0 of a zero-coupon bond paying 1 at T1, on a path where PROCESS's state at T0 is STATE, or
NILif PROCESS has no closed form. Times are in the leg's market time.(state-discount-bond process state 1d0 5d0) ; a 4-year bond, 1 year in
[function] FINCL:MARKET-CURVE-DISCOUNT MARKET CURVE DATE
Discount factor from MARKET's valuation date to DATE on CURVE, a yield curve or the id of one in MARKET.
[function] FINCL:RESCALE-VOL-STRUCTURE STRUCTURE ATM-VARIANCE
A vol structure with
STRUCTURE's smile shape and the ATM level that ATM-VARIANCE gives. ATM-VARIANCE is a function of the time to maturity tau (market time from the valuation date of the market the result is read on) returning the total at-the-money-forward variance a(tau) wanted there. The result's total variance at log-moneyness k = ln(K/F) is w(k, tau) a(tau) / w(0, tau): at each maturity the at-the-money variance is a(tau) and every other strike keeps its ratio to it inSTRUCTURE.STRUCTUREis a moneyness surface (SVI, SSVI, grid, smile) or a flat vol.When a(tau) / w(0, tau) changes quickly with tau the total variance can fall between maturities at some strikes (calendar arbitrage); CALENDAR-ARBITRAGE-FREE-P checks a result. For example, a simulated Heston variance v sets the level to the expected integrated variance:
(rescale-vol-structure surface (lambda (tau) (+ (* theta tau) (* (- v theta) (/ (- 1 (exp (- (* kappa tau)))) kappa)))))
[function] FINCL:SURFACE-QUOTES MARKET UNDERLYING OPTIONS &KEY (WEIGHT 1)
A QUOTE-SET quoting each of OPTIONS (European vanillas) at its Black vol on MARKET's vol structure for UNDERLYING, at its strike and expiry, with WEIGHT. Options expiring on or before MARKET's valuation date are left out, so one list serves every date of a simulation; none left signals INVALID-ARGUMENT.
(calibrate desk market (surface-quotes market :spx options) :engine :cos)
5.2 Books with cash
A :portfolio given :cash x (or holding a cash-account position in
its INIT) is self-financing: cash is a position of x units of a
cash-account, priced at 1 under any engine, so the book's value, Greeks,
snapshots and P&L explain include it. Negative cash is borrowing at the
same rate; there is no credit limit, transaction cost or margin.
On each date $t_k$, $k \ge 1$, of a path still running, in order:
Interest. The balance is multiplied by $G_k = D{k-1}/D_k$, $D$ the path's discount on the curve of the cash (
:cash-curve id, default the currency's discount curve): $e^{\int{t{k-1}}^{t_k} r\,ds}$ when a leg simulates that curve, so the discounted balance is constant between trades, and $P(0,t{k-1})/P(0,t_k)$ on the initial curve otherwise.Income. Each position pays its quantity times its income over $(t_{k-1}, t_k]$ into cash, for the kinds in
:collect(default:all):a holding, its discrete dividends going ex in the interval, on the ex-date: a cash dividend $D$ its price drop $D\,P(t{pay})/P(t{ex})$, so the drop and the cash cancel and no receivable is carried; a proportional one $\delta$ times the spot expected just before the drop (
:discrete-dividend); and its continuous yield to first order, $S_{k-1}(e^{q\Delta t}-1)$ (:continuous-dividend);a bond, its coupons (
:coupon) and redemption (:redemption); a swap or FRA, its signed flows (:coupon), on their payment dates;an option, its payoff at expiry (
:expiry), which must be one of the dates (early exercise is clause code:tradeit to 0,depositthe intrinsic value);cash, caps, floors and swaptions nothing.
A flow paid at $t_p < t_k$ is grown to $t_k$ by $P(0,t_p)/P(0,t_k)$
without a leg on the cash's curve, exactly, and credited at face with
one: an error of about the amount times $r(t_k - t_p)$, at most 0.33% of
the flow for monthly dates at 4%. Then the bonds, swaps and FRAs whose
last flow is paid and the options that expired leave the book.
3. The :every and :on clauses, in order. (trade book instrument &key by
to engine) buys or sells in BOOK at the date's price (ENGINE, else the
position's engine, else the book's :engine, with price-portfolio's
fallbacks), paid from its cash, and returns the cash paid; a position sold
to 0 leaves the book, and a price that fails signals. (deposit book x)
and (withdraw book x) move cash in and out. adjust-position stays a free change of quantity.
4. The book's :record keys, :value, :cash and Greeks.
At :start only steps 3 and 4 run; after stop nothing accrues.
A negative dividend yield as a drift. A user giving an equity $q < 0$ to
make it grow faster than the rate is, in a book, debited $|q| S\,\Delta t$ a
period as a continuous dividend: :collect '(:discrete-dividend :coupon
:redemption :expiry) leaves it out, and the yield then acts only on the
spot's drift.
A retirement drawdown, 60% in an equity and 40% in a 6-year par bond rolled monthly, 5% a year withdrawn, the bond on the exact Hull-White curve:
(simulate ((((:curve :usd) (make-hull-white :a 0.05d0 :sigma 0.01d0)) (:eq (make-gbm)))
market dates :n-paths 20000 :keep (:paths 10)
:correlation ((:eq (:curve :usd) 0.2d0)))
(:portfolio book (make-portfolio "60/40") :cash 1 :engine :discounting
:collect '(:discrete-dividend :coupon :redemption) :record (:value))
(:hold (bond nil))
(:every (date market)
(withdraw book (/ 0.05d0 12))
(when bond (trade book bond :to 0)) ; sell last month's bond
(let ((v (price book :discounting market))) ; cash and the equity
(if (<= v 0)
(stop)
(progn
(setf bond (par-bond date 6 (par-rate market 6))) ; user code
(trade book (make-holding :underlying :eq) :to (/ (* 0.6d0 v) (market-component market '(:spot :eq))))
(trade book bond :to (/ (* 0.4d0 v) (price bond :discounting market)))))))
(:final (:ruined (if (<= (price book :discounting market) 0) 1d0 0d0))))
A book with bonds prices with :discounting: holdings and cash ignore the
engine, and :auto is refused for rates instruments. (paths result :record
'(:book :value)) in fincl-viz draws the book's value on the kept paths.
[class] FINCL:CASH-ACCOUNT FINCL:INSTRUMENT
One unit of a currency, worth 1 in it: a position's quantity is a cash balance (negative: borrowed). Interest is not part of its value; SIMULATE's books accrue it.
(make-position (make-cash-account :currency :usd) :quantity 1000)
[function] FINCL:MAKE-CASH-ACCOUNT &KEY CURRENCY
A CASH-ACCOUNT in CURRENCY (a keyword;
NILmeans the market's).(make-cash-account :currency :usd)
6 Stochastic processes
A process is a stochastic differential equation. For the
purposes of financial modeling, these are typically drift-diffusion processes or Lévy processes.
However, fincl allows you to define your own (see TODO).
A general drift-diffusion process has the form $$dS_t = \mu(X_t, t) + \sigma(X_t,t)dW_t,$$ where $\mu(X_t,t)$ is called the drift, and $\sigma(X_t,t)$ is the diffusion. $W_t$ is a standard Brownian motion.
The Lévy processes add a jump term to drift-diffusion models dictated by a Poisson process. All processes forms are given under the risk-netural measure, where $r$ is the risk-free rate, $q$ is an equity dividend.
6.1 Drift-diffusion processes
6.1.1 Geometric Brownian motion
The classical drift-diffusion model of constant volatility. $$dS_t = (r - q) S_t \,dt + \sigma S_t\,dW_t.$$
[class] FINCL:GBM FINCL:STOCHASTIC-PROCESS FINCL:INDEPENDENT-INCREMENTS
Black-Scholes dynamics, with the market's rate, dividend and (by default) vol term structures.
(make-gbm :vol 0.2d0 :dividend-model :escrowed)
[function] FINCL:MAKE-GBM &REST INITARGS &KEY VOL DIVIDEND-MODEL
A new gbm process: (make-instance 'gbm initarg...).
6.1.2 Constant elasticity of variance
$$dS_t = (r-q)\,S_t\,dt + \sigma S_t^{\beta}\,dW_t$$
$\beta$: elasticity of the diffusion in $S$
$\sigma$: scale of the diffusion
See J. C. Cox, The constant elasticity of variance option pricing model (1975).
[class] FINCL:CEV FINCL:STOCHASTIC-PROCESS
Constant-elasticity-of-variance dynamics.
[function] FINCL:MAKE-CEV &REST INITARGS &KEY BETA SIGMA SCHEME
A new cev process: (make-instance 'cev initarg...).
6.1.3 Dupire local volatility
$$\frac{dS_t}{S_t} = (r-q)\,dt + \sigma_{\mathrm{loc}}(S_t,t)\,dW_t$$
where $\sigma_{\mathrm{loc}}$ is the local volatility of an implied total variance surface $w(k,T)$, $k =\ln (K / F (T) )$, in Gatheral's form of Dupire's formula,
$$\sigma_{\mathrm{loc}}^2 =\frac{\partial _T w}{1 - \frac{k}{w}\partial _k w + \frac{1}{4}\left(-\frac{1}{4} - \frac{1}{w} + \frac{k^2}{w^2}\right)(\partial _k w)^2+ \frac{1}{2}\partial _{kk} w}.$$
The surface is the market's unless one is given.
[class] FINCL:LOCAL-VOL FINCL:STOCHASTIC-PROCESS
Dupire local volatility consistent with an implied-vol surface: Monte Carlo prices of Europeans reproduce the surface.
[function] FINCL:MAKE-LOCAL-VOL &REST INITARGS &KEY SURFACE SUBSTEPS
A new local-vol process: (make-instance 'local-vol initarg...).
6.1.4 Heston
[class] FINCL:HESTON FINCL:STOCHASTIC-PROCESS
Heston stochastic volatility model.
[function] FINCL:MAKE-HESTON &REST INITARGS &KEY V0 KAPPA THETA XI RHO SCHEME
A new heston process: (make-instance 'heston initarg...).
[generic-function] FINCL:MAKE-STEPPER PROCESS MARKET TIMES
Dispatch once on (process, market) and return a closure
(lambda (state normals j) ...)that advances STATE in place from
TIMEs[j] toTIMEs[j+1], consuming PROCESS-FACTORS normals.TIMEs is a (SIMPLE-ARRAYDOUBLE-FLOAT(*)) of grid times in market time, starting at 0 and possibly unevenly spaced. The closure is called once per path per step, so everything that can be hoisted belongs in the method body: per-interval drifts, variances and step lengths are computed there into typed vectors indexed by J. Rates enter through LOG-GROWTH over each interval, so the discounted observable is a martingale under any deterministic term structure. Discrete dividends are not the method's concern: an:AROUNDmethod applies them to the closure it returns (DIVIDEND-STEPPER). A process that is not resolved (see RESOLVE-PROCESS) is resolved at the last grid time.
6.1.5 NGARCH
$$\ln S_t = \ln S _{t-1} + (r-q)\Delta - \frac{1}{2} h _t + \sqrt{h _t}\,z _t, \qquad h _{t+1} = \omega + \beta h _t + \alpha\, h _t\,(z _t-\gamma )^2$$
with $z_t$ standard normal and period $\Delta$.
$\omega$: intercept of the variance
$\beta$: persistence of the variance
$\alpha$: sensitivity of the variance to shocks
$\gamma$: leverage, raising the next variance more after negative shocks
See J.-C. Duan, The GARCH option pricing model, Mathematical Finance 5 (1995).
[class] FINCL:GARCH FINCL:STOCHASTIC-PROCESS
Duan's NGARCH(1,1).
[function] FINCL:MAKE-GARCH &REST INITARGS &KEY PERIOD ALPHA BETA GAMMA OMEGA H0
A new garch process: (make-instance 'garch initarg...).
6.1.6 Hull-White
$$dr_t = \left(\theta(t) - a\,r_t\right)dt + \sigma\,dW_t$$
$a$: speed of mean reversion
$\sigma$: volatility of the short rate
$\theta(t)$: fitted to the initial yield curve
See J. Hull and A. White, Pricing interest-rate derivative securities, Review of Financial Studies 3 (1990).
[class] FINCL:HULL-WHITE FINCL:STOCHASTIC-PROCESS
Hull-White one-factor short-rate model, fitted to a yield curve. Priced through rates engines (
:JAMSHIDIAN,:HULL-WHITE-TREE); it does not drive an equity spot. In SIMULATE it drives a yield curve, ((:curve id) (make-hull-white) :knots tenors), its state the short rate and its integral (:SHORT-RATE:INTEGRAL).
[function] FINCL:MAKE-HULL-WHITE &REST INITARGS &KEY A SIGMA
A new hull-white process: (make-instance 'hull-white initarg...).
6.2 Lévy processes
Lévy processes add jump terms to drift-diffusion models, accounting for random jumps seen in the price movement of various instruments. Throughout, $dN_t$ will denote a Poisson process with rate $\lambda$.
6.2.1 Merton Jump Diffusion
$$\frac{dS_t}{S_t} = (r-q-\lambda k)\,dt + \sigma\,dW_t + (e^{Y}-1)\,dN_t, \qquad Y \sim \mathcal{N}(\mu_J, \sigma_J^2),$$
with $k = e^{\mu_J + \sigma_J^2/2} - 1$.
$\sigma$: volatility of the diffusion
$\lambda$: jump intensity
$\mu_J$, $\sigma_J$: mean and standard deviation of the log jump $Y$
See R. C. Merton, Option pricing when underlying stock returns are discontinuous, Journal of Financial Economics 3 (1976).
[class] FINCL:MERTON-JUMP FINCL:JUMP-DIFFUSION
Merton's jump diffusion: GBM plus normally distributed log jumps at Poisson times.
[function] FINCL:MAKE-MERTON-JUMP &REST INITARGS &KEY VOL INTENSITY JUMP-MEAN JUMP-VOL
A new merton-jump process: (make-instance 'merton-jump initarg...).
6.2.2 Kou Jump Diffusion
Kou's jump-diffusion process dictated by $$\frac{dS_t}{S_t} = (r-q-\lambda)\, dt + \sigma \,dW_t + (e^{Y_t} - 1)\,dN_t.$$ See S.G. Kou, "A jump-diffusion model for option pricing"
[class] FINCL:KOU-JUMP FINCL:JUMP-DIFFUSION
Kou's jump diffusion: GBM plus double-exponential log jumps at Poisson times.
6.2.3 Variance Gamma
$$S_t = S_0\exp\left((r-q+\omega)\,t + \theta \, G_t + \sigma \, W_{G_t}\right), \qquad \omega = \frac1\nu\ln\left(1 - \theta\nu - \tfrac12\sigma^2\nu\right),$$
where $G$ is a gamma process with $\mathbb{E}[G_t] = t$ and $\operatorname{Var}[G_t] = \nu t$.
$\theta$: drift of the Brownian motion, setting the skewness
$\sigma$: volatility of the Brownian motion
$\nu$: variance rate of the gamma clock, setting the kurtosis
See D. B. Madan, P. P. Carr and E. C. Chang, The variance gamma process and option pricing, European Finance Review 2 (1998).
[class] FINCL:VARIANCE-GAMMA FINCL:EXPONENTIAL-LEVY FINCL:STOCHASTIC-PROCESS
The variance gamma process of Madan, Carr and Chang.
Under a change of measure SIGMA and THETA may take physical values and NU may not: with NU fixed the Levy measures C e^(-G|x|)/|x| (x < 0) and C e^(-Mx)/x (x > 0), C = 1/NU, are equivalent for any G, M > 0 (Sato, Theorem 33.1), and (SIGMA, THETA) <-> (G, M) is one to one. A drift change is refused: a pure-jump process has no Brownian driver, and its drift beside the jumps is fixed by equivalence.
[function] FINCL:MAKE-VARIANCE-GAMMA &REST INITARGS &KEY SIGMA NU THETA
A new variance-gamma process: (make-instance 'variance-gamma initarg...).
6.2.4 Normal Inverse Gaussian
$$S_t = S_0\exp\left((r-q+\omega)\,t + \beta V_t + W_{V_t}\right), \qquad \omega = \delta\left(\sqrt{\alpha^2-(\beta+1)^2} - \gamma\right),$$
where $V$ is an inverse Gaussian process with $\mathbb{E}[V_t] = \delta t/\gamma$ and $\gamma = \sqrt{\alpha^2-\beta^2}$.
$\alpha$: heaviness of the tails, lighter as it grows
$\beta$: asymmetry, with $|\beta| < \alpha$
$\delta$: scale
See O. E. Barndorff-Nielsen, Processes of normal inverse Gaussian type, Finance and Stochastics 2 (1998).
[class] FINCL:NIG FINCL:EXPONENTIAL-LEVY FINCL:STOCHASTIC-PROCESS
Barndorff-Nielsen's normal inverse Gaussian process.
Under a change of measure ALPHA and BETA may take physical values and DELTA may not: the Levy density (DELTA ALPHA / pi) e^(BETA x) K_1(ALPHA |x|) / |x| behaves as DELTA / (pi x^2) near 0, so two NIG measures are equivalent only with the same DELTA (Sato, Theorem 33.1), and then for any ALPHA > |BETA|. A drift change is refused: a pure-jump process has no Brownian driver, and its drift beside the jumps is fixed by equivalence.
[function] FINCL:MAKE-NIG &REST INITARGS &KEY ALPHA BETA DELTA
A new nig process: (make-instance 'nig initarg...).
6.2.5 CGMY
$$S_t = S_0\exp\left((r-q+\omega)\,t + L_t\right), \qquad \omega = -C\,\Gamma(-Y)\left((M-1)^Y - M^Y + (G+1)^Y - G^Y\right),$$
where $L$ is a pure-jump process with Lévy density
$$\nu(x) = C\,\frac{e^{-G|x|}}{|x|^{1+Y}}\ (x<0), \qquad \nu(x) = C\,\frac{e^{-Mx}}{x^{1+Y}}\ (x>0).$$
$C$: overall activity
$G$, $M$: exponential decay of the left and right tails, with $M > 1$
$Y < 2$: fine structure of the jumps
See P. Carr, H. Geman, D. B. Madan and M. Yor, The fine structure of asset returns, Journal of Business 75 (2002).
[class] FINCL:CGMY FINCL:EXPONENTIAL-LEVY FINCL:STOCHASTIC-PROCESS
The CGMY tempered stable process.
[function] FINCL:MAKE-CGMY &REST INITARGS &KEY C G M Y
A new cgmy process: (make-instance 'cgmy initarg...).
6.2.6 Bates
$$\frac{dS_t}{S_t} = (r-q-\lambda k)\,dt + \sqrt{v_t}\,dW^1_t + (e^{Y}-1)\,dN_t, \qquad dv_t = \kappa(\theta - v_t)\,dt + \xi\sqrt{v_t}\,dW^2_t,$$
with $\mathrm{corr}(dW^1_t, dW^2_t) = \rho$, $Y \sim \mathcal{N}(\mu_J, \sigma_J^2)$ and $k = e^{\mu_J + \sigma_J^2/2} - 1$.
$v_0$, $\theta$: initial and long-run variance
$\kappa$: speed of mean reversion of the variance
$\xi$: volatility of the variance
$\rho$: correlation of the two Brownian motions
$\lambda$, $\mu_J$, $\sigma_J$: jump intensity, and mean and standard deviation of the log jump $Y$
See D. S. Bates, Jumps and stochastic volatility: exchange rate processes implicit in Deutsche mark options, Review of Financial Studies 9 (1996).
[class] FINCL:BATES FINCL:HESTON
Bates's model: Heston stochastic volatility plus Merton jumps.
[function] FINCL:MAKE-BATES &REST INITARGS &KEY V0 KAPPA THETA XI RHO SCHEME INTENSITY JUMP-MEAN JUMP-VOL
A new bates process: (make-instance 'bates initarg...).
6.3 Change of measure
Every process is stated under the risk-neutral measure $Q$. A process under the physical measure $P$, for scenarios rather than prices, comes from one by Girsanov's theorem: a state $X^i$ driven by $W^i$ with diffusion coefficient $\sigma_i$ has
$$dW^{i,Q}_t = dW^{i,P}_t + \lambda_i(t, X_t)\,dt, \qquad \mu^P_i = \mu^Q_i + \sigma_i\lambda_i,$$
$\lambda_i$ the market price of risk of $W^i$. Diffusion coefficients and correlations are the same under both measures; jump parts change through their intensity and size law.
Premia are named by state (:spot, :variance, :short-rate), given as
a price of risk $\lambda$: a real,
(:scaled c)for $\lambda = c\,\sigma$ (a drift change $c\,\sigma^2$, proportional to variance), or a function of time and state;a drift change $\delta = \sigma\lambda$, in the state's coordinate (for the spot, the excess growth rate: $E^P[S_{t+h}] = E^Q[S_{t+h}]\,e^{\delta h}$ for constant $\delta$);
physical values of measure-dependent parameters.
| Process | Premium | Under $P$ |
|---|---|---|
| GBM, CEV, local vol | spot: any form | drift added after each step; exact when $\delta$ is constant over a step, trapezoid rule otherwise |
| Merton, Kou | spot; jump parameters | as GBM; the jump law compensated at its $P$ intensity |
| Heston, Bates | spot: any form; variance: (:scaled c) or a constant $d$; $\kappa$, $\theta$ | $\kappa^P = \kappa - c\,\xi^2$, $\theta^P = (\kappa\theta + d)/\kappa^P$ |
| NGARCH | spot: real $\lambda$ per period | $\gamma^P = \gamma - \lambda$, mean $\lambda\sqrt{h_t}$ |
| Hull-White | short rate: any form, of time only; $a$ | drift $\sigma\lambda(t)$ inside the exact step |
| variance gamma, NIG | $\sigma, \theta$; $\alpha, \beta$ | physical Lévy measure, drift beside the jumps unchanged |
The measures stay equivalent: states without a Brownian driver take no
price of risk, and variance gamma's $\nu$ and NIG's $\delta$, which set the
small jumps, are fixed (K. Sato, Lévy Processes and Infinitely Divisible
Distributions, Theorem 33.1). A Heston variance premium keeps the measures
equivalent only if the Feller condition $2\kappa\theta > \xi^2$ holds under both
(P. Cheridito, D. Filipović and R. L. Kimmel, Market price of risk specifications
for affine models, Journal of Financial Economics 83 (2007)); a violation
signals feller-condition-violated. The variance premium is Heston's,
proportional to variance (S. L. Heston, Review of Financial Studies 6 (1993));
the NGARCH form is Duan's (_Mathematical Finance 5_ (1995)).
In SIMULATE a physical process is a leg's process: its state evolves under $P$, and each date's market is built from that state with the risk-neutral process, so prices on every date are $Q$ valuations of a $P$ scenario. Engines and calibration refuse a physical process.
[function] FINCL:CHANGE-MEASURE PROCESS &KEY PRICES-OF-RISK DRIFT-CHANGES PARAMETERS
A PHYSICAL-PROCESS stepping PROCESS's dynamics under the physical measure. PROCESS is a risk-neutral process with a stepper. Premia name the state they apply to, from PROCESS-STATE-NAMES; states not named carry none.
PRICES-OF-RISK ((state spec) ...), lambda for the Brownian motion driving the state: a real (constant lambda); (:scaled c), lambda = c sigma, a drift change of c sigma^2 (proportional to variance); or a function (lambda (time state)) returning lambda,
TIMEin market time, STATE the state vector (read only). DRIFT-CHANGES ((state spec) ...), the drift change delta = sigma lambda itself, in the state's coordinate: a real or a function (lambda (time state)). For the observable, delta is the excess continuously compounded growth over the risk-neutral carry: E^P[S(t+h)] = E^Q[S(t+h)] exp(delta h) for constant delta. PARAMETERS a plist of physical values of PROCESS's measure-dependent parameters (jump intensities and size laws).Latent states take only premia that keep their scheme exact, as physical parameters of the stepping process: Heston's
:VARIANCE(:SCALEDc) gives kappa^P = kappa - c xi^2 and theta^P = kappa theta / kappa^P, a constant drift change d gives theta^P = (kappa theta + d) / kappa; NGARCH's:SPOTtakes a real lambda per period (Duan's model, gamma^P = gamma - lambda); Hull-White's:SHORT-RATEtakes any form, functions being called with STATENIL(a function of time only), as a drift sigma lambda(t) inside its exact step. Heston variance premia keep the measures equivalent only when the Feller condition 2 kappa theta > xi^2 holds under both; a violation signals the warning FELLER-CONDITION-VIOLATED, once per image. Variance gamma and NIG take physical parameters only, plus the drift that keeps their drift beside the jumps unchanged.A drift change of the observable is added after each step of the risk-neutral scheme, exactly when delta is constant over a step, by the trapezoid rule on the states at the step's two ends otherwise. Discrete dividends are applied once, after it. With no premia the result steps as PROCESS on the same normals. Defaults left to the market (
NILparameters) are resolved, and the premia converted, by RESOLVE-PROCESS. Bad arguments signal INVALID-MEASURE-CHANGE.(change-measure (make-gbm) :drift-changes '((:spot 0.03d0))) (change-measure (make-merton-jump) :prices-of-risk '((:spot 0.2d0)) :parameters '(:intensity 1d0))
[class] FINCL:PHYSICAL-PROCESS FINCL:STOCHASTIC-PROCESS
A process under the physical measure P, built by CHANGE-MEASURE from a risk-neutral process and its prices of risk. It steps under P wherever a process is stepped (SIMULATE legs) and answers every valuation question (the date's market, curves, discounting) with RISK-NEUTRAL-PROCESS. Engines and calibration refuse it.
- [generic-function] FINCL:RISK-NEUTRAL-PROCESS OBJECT
[function] FINCL:SIMULATION-MEASURE SIMULATION
The measure SIMULATION's paths were stepped under:
:PHYSICALwhen a leg's process is a PHYSICAL-PROCESS, else:RISK-NEUTRAL. SIMULATION is a SIMULATION-RESULT or a SIMULATION-PLAN. Discounted means of a:PHYSICALresult are expectations under the physical measure, not prices.(simulation-measure (simulate ((make-gbm) m dates) ...)) =>
:RISK-NEUTRAL
[condition] FINCL:INVALID-MEASURE-CHANGE FINCL:INVALID-INPUT
Arguments to CHANGE-MEASURE that do not describe an equivalent physical measure: an unknown or repeated state, a state without a Brownian driver, a premium form the process cannot honour, a parameter fixed by the change of measure, or a process already physical.
[condition] FINCL:RISK-NEUTRAL-PROCESS-REQUIRED FINCL:PRICING-ERROR
A physical process given where prices are computed: an engine, automatic selection or calibration.
[condition] FINCL:FELLER-CONDITION-VIOLATED WARNING
A Heston change of measure whose variance violates the Feller condition 2 kappa theta > xi^2 under the risk-neutral or the physical measure, so the measures may not be equivalent. Signalled once per image for each set of parameters.
7 Portfolios and risk
A portfolio is a tree of positions, each a signed quantity $q_i$ of an
instrument, valued on one market $M$ as
$$V(M)=\sum_i q_i\,V_i(M).$$
Pricing is price on every position, in parallel and under a recovery
policy: a book is priced even when one of its positions cannot be. Risk is
revaluation on scenarios, which are other markets (bump, aging), so every
instrument and engine that prices on a market takes part with no further
method. Results do not depend on the number of workers.
(defparameter *market*
(make-market :valuation-date #D"2026-10-01"
:underlyings '((:spx :spot 5000 :currency :usd
:dividend 0.015d0 :vol 0.18d0))
:curves '((:usd-ois :rate 0.04d0))))
(defparameter *book*
(make-portfolio "book"
(make-position (make-option (call 5000) (expires #T"1Y" :from #D"2026-10-01"))
:quantity 10 :tags '(:desk :a))
(make-position (make-option (put 4500) (american) (expires #T"6M" :from #D"2026-10-01"))
:quantity -5 :tags '(:desk :b))
(make-position (make-holding) :quantity -3 :tags '(:desk :a))))
(price *book* :auto *market*)
;; ==> -11158.493465283193d0
;; NIL
;; NIL
7.1 Positions and portfolios
A position is $q$ units of an instrument: long when $q>0$, short when
$q<0$. It may name its own engine, a designator; otherwise the engine given
to the pricing call prices it (:auto by default). It also carries a plist
of tags. A portfolio is a named tree of positions and
portfolios. Both are immutable; position-instrument, position-quantity,
position-engine and position-tags read a position, portfolio-name and
portfolio-members a portfolio. holding is the underlying itself, worth
its spot, with delta 1 and every other Greek 0, so that a book can hold its
hedge; borrow and financing are not modelled.
(portfolio-by-tag *book* :desk)
;; ==> ((:A . #<PORTFOLIO "book :DESK=:A", 2 positions>)
;; (:B . #<PORTFOLIO "book :DESK=:B", 1 position>))
[class] FINCL:HOLDING FINCL:INSTRUMENT
One unit of an underlying, worth its spot. Its currency is the underlying's; another is a quanto and signals UNSUPPORTED-QUANTO. Borrow and financing costs are not modelled, and dividends received are not part of its value.
(make-holding :underlying :spx)
[function] FINCL:MAKE-HOLDING &KEY UNDERLYING CURRENCY
A HOLDING of UNDERLYING (a keyword;
NILmeans the market's only underlying), paying in CURRENCY (NIL: the underlying's).(make-holding :underlying :spx)
[class] FINCL:PORTFOLIO-POSITION
QUANTITY units of INSTRUMENT: long when positive, short when negative, closed at zero. Made by MAKE-POSITION; immutable.
- [generic-function] FINCL:POSITION-INSTRUMENT OBJECT
- [generic-function] FINCL:POSITION-QUANTITY OBJECT
- [generic-function] FINCL:POSITION-ENGINE OBJECT
- [generic-function] FINCL:POSITION-TAGS OBJECT
[function] FINCL:MAKE-POSITION INSTRUMENT &KEY (QUANTITY 1) ENGINE TAGS
A position of QUANTITY (a real; negative is short) in INSTRUMENT, priced with ENGINE (a designator;
NIL: the portfolio's default) and carrying TAGS, a plist.(make-position (make-option (put 95) (expires #D"2027-09-24")) :quantity -10 :tags '(:desk :a))
[function] FINCL:DERIVE-POSITION POSITION &KEY (QUANTITY (
FINCL:POSITION-QUANTITYPOSITION)) (ENGINE (FINCL:POSITION-ENGINEPOSITION)) (TAGS (FINCL:POSITION-TAGSPOSITION))A copy of
POSITIONwith QUANTITY, ENGINE or TAGS replaced.
[class] FINCL:PORTFOLIO
A named tree of positions and sub-portfolios. Made by MAKE-PORTFOLIO; immutable.
- [generic-function] FINCL:PORTFOLIO-NAME OBJECT
- [generic-function] FINCL:PORTFOLIO-MEMBERS OBJECT
[function] FINCL:MAKE-PORTFOLIO NAME &REST MEMBERS
A PORTFOLIO called NAME (a string or keyword) of
MEMBER(01)s, each a position or a portfolio.(make-portfolio "book" (make-position call :quantity 10 :tags '(:desk :a)) (make-portfolio "hedges" (make-position (make-holding) :quantity -6)))
[function] FINCL:PORTFOLIO-POSITIONS PORTFOLIO
Every position in PORTFOLIO's tree, depth first, in order.
[function] FINCL:PORTFOLIO-LONG PORTFOLIO
The positions of PORTFOLIO with a positive quantity, as a flat portfolio.
[function] FINCL:PORTFOLIO-SHORT PORTFOLIO
The positions of PORTFOLIO with a negative quantity, as a flat portfolio.
[function] FINCL:PORTFOLIO-BY-TAG PORTFOLIO KEY
((value . portfolio) ...): PORTFOLIO's positions grouped by the value of their tag KEY (
NILfor positions without it), in order of first appearance.(portfolio-by-tag book :desk) => ((:a . #<PORTFOLIO ...>) (:b . ...))
[generic-function] FINCL:SAME-INSTRUMENT-P A B
True if instruments A and B are the same contract, so that ADJUST-POSITION adds to an existing position. Options are compared by identity; holdings by underlying and currency.
[function] FINCL:ADJUST-POSITION PORTFOLIO INSTRUMENT &KEY BY TO
A copy of PORTFOLIO whose top-level position in INSTRUMENT (see SAME-INSTRUMENT-P) has its quantity moved BY a real, or set TO one; with no such position, one is appended with quantity BY or TO. Exactly one of BY and TO. PORTFOLIO is unchanged.
(adjust-position book (make-holding :underlying :spx) :to -0.53d0) ; rebalance a hedge
7.2 Pricing a portfolio
price-portfolio returns a portfolio-result with one position-result
per position, in the order of portfolio-positions: the unit price, its
standard error, the engine that priced it and the condition it recovered
from, read by position-result-unit-price, position-result-standard-error,
position-result-engine and position-result-condition. A position that
cannot be priced is recorded with its condition and nothing is signalled;
portfolio-value returns the value, its standard error (Monte Carlo
positions assumed independent) and the unpriced positions.
When an engine declines a position (unsupported-combination or
model-domain-error), the engines in applicable-engines are tried in turn.
That function finds the engines whose pricing methods accept the instrument
by inspecting the method tables through the metaobject protocol, restricted
to those that model the process, and orders them by engine-preference:
Black-Scholes 10, Roll-Geske-Whaley 11, other closed forms 12, COS 20,
finite differences 30, the tree 40, Monte Carlo 90. An engine listed may
still decline in a regime its method does not cover.
(price-portfolio *book* *market*)
;; ==> #<PORTFOLIO-RESULT "book" -11158.4935>
(applicable-engines (make-option (put 4500) (american) (expires #D"2027-04-01"))
*market* :process (make-heston))
price and greeks on a portfolio are the quantity-weighted sums over its
positions; :method :bump makes greeks bump every position.
[function] FINCL:PRICE-PORTFOLIO PORTFOLIO MARKET &KEY (ENGINE
:AUTO) (POLICY #'FINCL::DEFAULT-FALLBACK-POLICY) (PARALLELT)PORTFOLIO priced on MARKET: a PORTFOLIO-RESULT (see PORTFOLIO-VALUE) with one POSITION-RESULT per position, in order. Each position is priced with its own engine, or ENGINE (default
:AUTO); if that declines (UNSUPPORTED-COMBINATION, MODEL-DOMAIN-ERROR), POLICY, a function of (position market engine condition), gives the engines to try next (default: the instrument's APPLICABLE-ENGINES). A position that cannot be priced is recorded with its condition; nothing is signalled. Positions are priced in parallel under lp:*kernel* (serially with PARALLELNIL, e.g. inside code that already runs in parallel); the result does not depend on the number of workers.(portfolio-value (price-portfolio book m)) => 1234.56d0,
NIL,NIL
[class] FINCL:PORTFOLIO-RESULT STRUCTURE-OBJECT
PORTFOLIO priced: RESULTS, a vector of POSITION-RESULTs in the order of PORTFOLIO-POSITIONS.
[class] FINCL:POSITION-RESULT STRUCTURE-OBJECT
One position's pricing: UNIT-PRICE and STANDARD-ERROR per unit of the instrument (
NILif it could not be priced), the ENGINE that priced it, and theCONDITIONrecovered from or, if unpriced, the last one.
- [structure-accessor] FINCL:POSITION-RESULT-UNIT-PRICE POSITION-RESULT
- [structure-accessor] FINCL:POSITION-RESULT-STANDARD-ERROR POSITION-RESULT
- [structure-accessor] FINCL:POSITION-RESULT-ENGINE POSITION-RESULT
- [structure-accessor] FINCL:POSITION-RESULT-CONDITION POSITION-RESULT
[function] FINCL:PORTFOLIO-VALUE RESULT
(values value standard-error unpriced) of a PORTFOLIO-RESULT: the sum of the priced positions' values, the standard error of that sum (
NILif no position has one), and the list of positions that could not be priced.
[function] FINCL:POSITION-RESULT-VALUE R
Quantity x unit price, or
NILif the position was not priced.
[generic-function] FINCL:APPLICABLE-ENGINES INSTRUMENT MARKET &KEY CANDIDATES PROCESS
The engines that have a pricing method for INSTRUMENT, as instances, ordered by ENGINE-PREFERENCE: those of CANDIDATES (designators, default DEFAULT-ENGINES) that model PROCESS (default GBM on the market) and whose pricing generic function has a method for the instrument's exercise, payoff and path classes more specific than the UNSUPPORTED-COMBINATION fallback. An engine listed may still decline in a market regime (MODEL-DOMAIN-ERROR, e.g. discrete dividends it does not model); SELECT-ENGINE and PRICE-PORTFOLIO move on when it does.
(applicable-engines (make-option (put 100) (american) (expires d)) m :process (make-heston)) => (#<ENGINE (make-engine :fd :process (make-heston))> #<ENGINE (make-engine :mc ...)>)
[function] FINCL:SELECT-ENGINE INSTRUMENT MARKET &REST OPTIONS &KEY CANDIDATES PROCESS
The first of APPLICABLE-ENGINES for INSTRUMENT, or
NIL.
[generic-function] FINCL:ENGINE-PREFERENCE ENGINE
The rank of ENGINE (an instance) in APPLICABLE-ENGINES' order, lower first: closed forms 10 (Black-Scholes before RGW and BAW),
COS20, finite differences 30, the tree 40, Monte Carlo 90.
[variable] FINCL:*DEFAULT-ENGINES* (:BLACK-SCHOLES :RGW :BAW :COS :FD :BINOMIAL :MC :MERTON-SERIES :CEV)
The engine designators APPLICABLE-ENGINES considers by default.
[method] FINCL:PRICE (P
FINCL:PORTFOLIO) ENGINE MARKETA portfolio's value: (values value standard-error), by PRICE-PORTFOLIO with ENGINE as the default engine. Signals the first position's condition if any position cannot be priced.
[method] FINCL:GREEKS (P
FINCL:PORTFOLIO) ENGINE MARKETThe sum over PORTFOLIO's positions of quantity x the instrument's Greeks, each under the position's engine or ENGINE.
METHOD:DEFAULTuses each instrument's own GREEKS method (closed forms where there are some);:BUMPuses BUMP-GREEKS for every position. Positions whose Greeks fail signal their condition.
7.3 Scenarios and revaluation
A scenario is a list of risk-factor bumps, as bump takes them, and an
aging in days or to a date; applied to a composite market it gives another
market. revalue prices every position on each scenario's market with the
engine it got on the base market $M_0$, so automatic selection runs once, and
returns the P&L array
$$\Pi_{ij}=q_i\left(V_i(M_j)-V_i(M_0)\right),$$
positions by scenarios; scenario-pnl sums its columns to the portfolio's
$\Pi_j$. A position that cannot be priced contributes 0 and is listed.
The builders parallel-shift-scenarios, spot-vol-grid and
historical-scenarios make the usual scenario sets: shifts of one factor,
the grid of relative spot and absolute vol shifts, and one scenario per
observation of a history of factor changes. scenario-name, scenario-bumps
and scenario-age read a scenario.
(let ((grid (spot-vol-grid :spx '(-1/10 0 1/10) '(-5/100 0 5/100))))
(scenario-pnl (revalue *book* *market* grid)))
;; ==> #(-2067.9972298808498d0 -1577.8793581143627d0 -1041.389844616886d0
;; -769.2592592460352d0 0.0d0 720.3974515347319d0 1427.080644420651d0
;; 2119.837472639283d0 2852.767617368155d0)
[class] FINCL:SCENARIO STRUCTURE-OBJECT
NAME, BUMPS (a list of (factor shift), as BUMP takes them) and AGE (
NIL, a number of calendar days, or a date to move the valuation date to).
- [structure-accessor] FINCL:SCENARIO-NAME SCENARIO
- [structure-accessor] FINCL:SCENARIO-BUMPS SCENARIO
- [structure-accessor] FINCL:SCENARIO-AGE SCENARIO
[function] FINCL:MAKE-SCENARIO NAME &KEY BUMPS AGE
A SCENARIO called NAME: BUMPS, a list of (factor shift) applied in order (see BUMP), then AGE, calendar days to age the market by or a date.
(make-scenario "spot -10%, vol +5" :bumps '(((:spot :spx) (:relative -1/10)) ((:vol :spx) (:absolute 5/100))))
[function] FINCL:APPLY-SCENARIO SCENARIO MARKET
The market SCENARIO turns the composite MARKET into.
[function] FINCL:PARALLEL-SHIFT-SCENARIOS FACTOR SHIFTS &KEY (KIND
:ABSOLUTE)One scenario per shift of SHIFTS applied to FACTOR as (KIND shift).
(parallel-shift-scenarios '(:curve :usd-ois) '(-1/100 -1/1000 1/1000 1/100))
[function] FINCL:SPOT-VOL-GRID UNDERLYING SPOT-SHIFTS VOL-SHIFTS
The scenarios of every relative spot shift in SPOT-SHIFTS combined with every absolute vol shift in VOL-SHIFTS for UNDERLYING, spot shifts varying slowest.
(spot-vol-grid :spx '(-1/10 0 1/10) '(-5/100 0 5/100)) ; 9 scenarios
[function] FINCL:HISTORICAL-SCENARIOS MARKET HISTORY
One scenario per observation of HISTORY, a list of (factor kind changes): FACTOR as BUMP takes it, KIND
:RELATIVE(returns) or:ABSOLUTE(differences), CHANGES a sequence of the factor's observed changes, every factor's of the same length. Scenario i applies change i of every factor. MARKET is used to check the factors.(historical-scenarios m `(((:spot :spx) :relative ,spx-returns) ((:curve :usd-ois) :absolute ,rate-changes)))
[function] FINCL:REVALUE PORTFOLIO MARKET SCENARIOS &KEY (ENGINE
:AUTO)The P&L of PORTFOLIO's positions under SCENARIOS relative to MARKET: (values pnl unpriced), PNL an N-POSITIONS x N-SCENARIOS array of doubles, quantity x (price in the scenario - base price), positions in the order of PORTFOLIO-POSITIONS. Each position is priced with the engine it got on the base market (its own, or ENGINE by PRICE-PORTFOLIO's rules), so automatic selection runs once. A position that cannot be priced on the base market or in a scenario contributes 0 there and is listed in UNPRICED as (position scenario-name condition). Scenarios run in parallel under lp:*kernel*; the result does not depend on the number of workers.
(scenario-pnl (revalue book m (spot-vol-grid :spx '(-1/10 1/10) '(0))))
[function] FINCL:SCENARIO-PNL PNL
The portfolio's P&L in each scenario: the column sums of a REVALUE matrix, as a DOUBLE-VECTOR.
7.4 Value at risk
With losses $\ell = - \Pi $ over $n$ scenarios sorted
$\ell_1 \geq \ell_2 \geq \ldots $ and $ k =\lceil n(1-c)\rceil$, the
historical value at risk and expected shortfall at confidence $c$ are
$$\mathrm{VaR}_c = \ell_k,\qquad
\mathrm{E S}_c = \frac{1}{k}\sum_{m = 1}^{k}\ell_m,$$
the $k$-th largest loss and the mean of the $k$ largest, the sample forms of
the loss quantile and of the tail expectation. The sample is the P&L of a
revaluation on historical-scenarios or on any scenario set.
The delta-normal VaR is $z_c\sqrt{s^\top C s}$ with $z_c$ the normal
quantile, $C$ the covariance of the factor changes over the horizon and
$s_f=\partial V/\partial x_f$ the portfolio's sensitivity to each factor, by
central differences on bumped markets (factor-sensitivities); it is exact
for a portfolio linear in jointly normal factors. repair-positive-semidefinite
raises the negative eigenvalues of a covariance or correlation estimate to
zero, which gives the nearest positive-semidefinite matrix in the Frobenius
norm.
;; RETURNS: 500 daily SPX returns
(let* ((scenarios (historical-scenarios *market* `(((:spot :spx) :relative ,returns))))
(pnl (scenario-pnl (revalue *book* *market* scenarios))))
(values (historical-var pnl 0.99d0) (expected-shortfall pnl 0.99d0)))
(delta-normal-var *book* *market* '(((:spot :spx) :relative))
#2A((0.0004d0)) 0.99d0)
See C. Acerbi and D. Tasche, On the coherence of expected shortfall, Journal
of Banking and Finance 26 (2002); R. T. Rockafellar and S. Uryasev,
Conditional value-at-risk for general loss distributions, Journal of Banking
and Finance 26 (2002); J. P. Morgan and Reuters, RiskMetrics Technical
Document, 4th ed. (1996); N. J. Higham, Computing a nearest symmetric
positive semidefinite matrix, Linear Algebra and its Applications 103 (1988).
[function] FINCL:HISTORICAL-VAR PNL CONFIDENCE
Value at risk at CONFIDENCE (e.g. 0.99) from the P&L sample PNL (a sequence, e.g. SCENARIO-PNL): the K-th largest loss, K = ceiling(n (1 - CONFIDENCE)), as a positive number when it is a loss. With n = 500 and 0.99, the 5th largest loss.
(historical-var (scenario-pnl (revalue book m scenarios)) 0.99d0)
[function] FINCL:EXPECTED-SHORTFALL PNL CONFIDENCE
Expected shortfall at CONFIDENCE from the P&L sample PNL: the mean of the K largest losses, K as in HISTORICAL-VAR.
[function] FINCL:FACTOR-SENSITIVITIES PORTFOLIO MARKET FACTORS &KEY (ENGINE
:AUTO) (STEP 0.001d0)dV/dx for each of FACTORS, a list of (factor kind): the change in PORTFOLIO's value per unit of the factor's change of KIND (
:RELATIVE:per unit return;:ABSOLUTE:per unit move), by central differences of steps ofSTEP, as a DOUBLE-VECTOR. Each position keeps its base engine.
[function] FINCL:DELTA-NORMAL-VAR PORTFOLIO MARKET FACTORS COVARIANCE CONFIDENCE &KEY (ENGINE
:AUTO) (STEP 0.001d0)Parametric VaR at CONFIDENCE: z sqrt(s' C s), z the normal quantile, s the FACTOR-SENSITIVITIES to FACTORS (a list of (factor kind)), C the COVARIANCE of the factors' changes over the horizon (an n x n 2-D array or column-major DOUBLE-VECTOR, in the units of each KIND). (values var sensitivities). Exact for a portfolio linear in the factors whose changes are jointly normal.
(delta-normal-var book m '(((:spot :spx) :relative)) #2A((0.0004d0)) 0.99d0)
[function] FINCL:REPAIR-POSITIVE-SEMIDEFINITE MATRIX N &KEY (FLOOR 0.0d0)
The symmetric N x N MATRIX (column-major DOUBLE-VECTOR) with its eigenvalues below
FLOORraised toFLOOR: V max(Lambda,FLOOR) V', the nearest positive-semidefinite matrix in the Frobenius norm whenFLOORis 0 (Higham 1988). For covariance and correlation estimates that came out slightly indefinite. Returns a new vector.
7.5 Ladders and P&L explain
curve-delta-ladder gives the portfolio's sensitivity to each input quote
of a bootstrapped curve, with the curve rebootstrapped on every bump; the sum
is the parallel-shift sensitivity to first order. vega-ladder gives vega by
expiry bucket.
explain-pnl attributes the P&L between two markets to the Greeks at the
first, position by position:
$$\Delta V\approx\delta\,\Delta S+\tfrac12\gamma\,\Delta S^2
+\nu\,\Delta\sigma+\text{vanna}\,\Delta S\,\Delta\sigma
+\tfrac12\text{volga}\,\Delta\sigma^2+\theta\,\tau
+\rho\,\Delta r+\rho_q\,\Delta q,$$
with $\Delta\sigma$ the move of the Black vol at the position's strike and
expiry and $\tau$ the calendar days between the valuation dates. It returns
each term, their sum :explained, the full revaluation :actual and the
:unexplained remainder: third-order terms, rate convexity and cross terms
with rates.
(explain-pnl *book* *market* (bump *market* '(:spot :spx) '(:relative 1/100)))
;; ==> (:DELTA 181.67 :GAMMA 2.862 ... :EXPLAINED 184.53
;; :ACTUAL 184.56 :UNEXPLAINED 0.0287)
(vega-ladder *book* *market* (list #T"3M" #T"1Y"))
[function] FINCL:CURVE-DELTA-LADDER PORTFOLIO MARKET CURVE-ID &KEY (ENGINE
:AUTO) (STEP 1.0d-4)((label . dV/dq) ...): PORTFOLIO's sensitivity to each input quote of the bootstrapped curve CURVE-ID, per unit of the quote, by central differences of
STEPwith the curve rebootstrapped (BUMP (:quote id index)). LABEL is the helper's tenor, or its index. Their sum is the sensitivity to a parallel move of every quote, (:curve id), to first order.(curve-delta-ladder book m :usd-sofr)
[function] FINCL:VEGA-LADDER PORTFOLIO MARKET BUCKETS &KEY (ENGINE
:AUTO)((label . vega) ...): PORTFOLIO's vega (per unit vol, quantity-weighted) by the expiry of its options, BUCKETS a list of tenors from the valuation date; an option falls in the first bucket whose end is on or after its expiry, and later ones in a last bucket labelled
:BEYOND. Other instruments have no vega.(vega-ladder book m (list #
T"3M" #T"1Y" #T"5Y"))
[function] FINCL:EXPLAIN-PNL PORTFOLIO MARKET-0 MARKET-1 &KEY (ENGINE
:AUTO)PORTFOLIO's P&L from the composite MARKET-0 to MARKET-1, explained by a Taylor expansion in the Greeks at MARKET-0, position by position, as a plist:
:delta delta dS :gamma gamma dS^2 / 2 :vega vega dsigma :vanna vanna dS dsigma :volga volga dsigma^2 / 2 :theta theta x days :rho rho dr :dividend-rho dividend-rho dq :explained (their sum) :actual (full revaluation) :unexplained (the rest)
dS is the move of each position's underlying's spot, dsigma of its Black vol at its strike and expiry, dr and dq of the zero rate and dividend yield to its expiry, days the calendar days between the valuation dates. Each position keeps the engine it gets on MARKET-0. Third-order terms, rate convexity and cross terms with rates are in
:UNEXPLAINED.(explain-pnl book m (bump m '(:spot :spx) '(:relative 1/100)))
7.6 Snapshots
A snapshot is the constructor form that rebuilds a market, a portfolio or
one of their parts: composite markets with their flat, interpolated and
dividend-schedule term structures, smile, grid, SVI and SSVI surfaces and day
counters, options, holdings, positions and portfolios. Bootstrapped curves are
not supported. write-snapshot prints the form with dates as #D literals;
read-snapshot reads it with *read-eval* off and evaluates it with an
evaluator that calls only the snapshot constructors, so reading one runs no
other code. A rebuilt object is made from the same numbers, so its prices are
= to the original's. A composite market prints readably as its snapshot form.
(with-open-file (s "book.sexp" :direction :output :if-exists :supersede)
(write-snapshot *book* s))
(with-open-file (s "book.sexp") (read-snapshot s))
[generic-function] FINCL:SNAPSHOT-FORM OBJECT
A form that rebuilds OBJECT, made only of literals (numbers, strings, keywords, dates),
QUOTE,LIST(01) and the constructors READ-SNAPSHOT allows. Defined for composite markets, the flat, interpolated and dividend-schedule term structures, smile, grid, SVI and SSVI surfaces, day counters, options, holdings, positions, portfolios and physical processes whose premia are data; anything else (bootstrapped curves among them) signals INVALID-ARGUMENT.(snapshot-form (make-holding :underlying :spx)) => (MAKE-HOLDING
:UNDERLYING:SPX)
[function] FINCL:WRITE-SNAPSHOT OBJECT &OPTIONAL (STREAM
*STANDARD-OUTPUT*)Print OBJECT's SNAPSHOT-FORM to
STREAMunder standard I/O syntax, withFINCL:SYNTAXdates, symbols qualified as needed. READ-SNAPSHOT reads it back.(with-open-file (s "book.sexp" :direction :output) (write-snapshot book s))
[function] FINCL:READ-SNAPSHOT &OPTIONAL (STREAM
*STANDARD-INPUT*)The object WRITE-SNAPSHOT wrote to
STREAM: read under standard syntax withFINCL:SYNTAXand*READ-EVAL*NIL, then evaluated by SNAPSHOT-EVAL, which calls only the snapshot constructors.(with-open-file (s "book.sexp") (read-snapshot s))
8 Extending fincl
New currencies, calendars, processes and payoffs are defined with define-
macros, which write classes, constructors and the methods the engines call.
The dice game below uses all of them; each subsection defines one piece
and the last assembles them into a toy option contract pricing.
A fair die is rolled once a week. Players are paid in casino chips, and two contracts are written on it:
Jackpot: pays the face of the last roll, plus a bonus if it shows the top face. With a bonus of 10 on a six-sided die the expected payoff is $3.5 + 10/6$.
Bust game: after three weekly rolls it pays the running total, unless a 1 was rolled along the way, in which case the game ends and pays nothing. The expected payoff is $(5/6)^3 \cdot 12 \approx 6.944$, where 12 is the expected total of three rolls that are all at least 2.
Start with
(ql:quickload :fincl)
(defpackage #:dice (:use #:cl #:fincl))
(in-package #:dice)
(named-readtables:in-readtable fincl:syntax)
8.1 define-currency
Register a currency keyword with its name and the number of decimal places amounts are shown with. Options and markets refer to it by keyword.
(define-currency :chip :name "Casino chip" :fraction-digits 0)
[macro] FINCL:DEFINE-CURRENCY CODE &KEY NAME (FRACTION-DIGITS 2)
Register the currency CODE, a keyword, with its NAME and the number of FRACTION-DIGITS amounts are shown with.
(define-currency :usd :name "US Dollar" :fraction-digits 2)
8.2 define-calendar
Define a holiday calendar from rules: (:fixed month day),
(:nth-weekday n weekday month), (:easter offset), (:dates "YYYY-MM-DD"...)
and (:when predicate), each with :observe, :from, :to and :except.
The macro makes the class and the singleton +name+, which any function
taking a calendar accepts, e.g. (expires #T"2M" :from d :calendar +casino+).
define-observance adds a rule for holidays that fall on a weekend.
Our casino will be closed on weekends as well as Christmas and Dec 26, observing this holiday on the previous weekday if it happens to fall on a weekend.
(define-observance :previous-weekday (date)
(case (day-of-week date)
(6 (date+ date -1))
(7 (date+ date -2))
(t date)))
(define-calendar casino (weekends-only)
"Closed on Christmas Day, and on the 26th, observed on the previous weekday."
(:fixed 12 25)
(:fixed 12 26 :observe :previous-weekday))
[macro] FINCL:DEFINE-CALENDAR NAME (SUPERCLASS) &BODY BODY
Define the holiday calendar NAME: a class on SUPERCLASS (WEEKENDS-ONLY, or another holiday calendar, whose rules NAME inherits), the singleton +NAME+, and the holiday rules in BODY (after an optional docstring). Each rule is one of
(:fixed month day) a date every year (:nth-weekday n weekday month) e.g. 3 :monday 1; negative N counts from the month's end (-1 :monday 5: last Monday of May) (:easter offset) days from Easter Sunday (-2 Good Friday, 1 Easter Monday) (:dates "YYYY-MM-DD" ...) one-off closures (:when predicate) PREDICATE, evaluated, of (year month day)
and
:FIXED,:NTH-WEEKDAY,:EASTERand:WHENtake the options:OBSERVEkeyword (:none, :next-monday, :nearest-weekday, :sunday-to-monday, or one from DEFINE-OBSERVANCE),:FROMyear,:TOyear and:EXCEPT(years...). The weekend comes from SUPERCLASS.(define-calendar my-exchange (weekends-only) "An exchange closed on New Year's Day and Good Friday." (:fixed 1 1 :observe :sunday-to-monday) (:easter -2))
[class] FINCL:WEEKENDS-ONLY FINCL:CALENDAR
Saturdays and Sundays are holidays; nothing else is.
[macro] FINCL:DEFINE-OBSERVANCE NAME (DATE) &BODY BODY
Define the observance rule NAME: BODY maps the holiday's DATE to the date it is observed on, or
NILif it is not observed that year.(define-observance :sunday-to-monday (date) (if (= (day-of-week date) 7) (date+ date 1) date))
[function] FINCL:DAY-OF-WEEK DATE
ISO day of the week: 1 = Monday ... 7 = Sunday.
(day-of-week #D"2027-06-15") => 2
8.3 define-process
Define a custom process, its constructor make-name and its parameters,
which are validated, bounded and enumerable for calibration. The
dynamics are ordinary methods:
initial-state: the state vector at time zero. Element 0 is the observable that payoffs see; the others are latent.make-stepper: returns(lambda (state normals j)), which advances thestatevector in place fromtimes[j]totimes[j+1]using standard normals, and returnsNIL. Do expensive work outside the lambda.process-state-names: names for the state elements, which path payoffs refer to.
The constructor takes the parameters as keywords. process-parameter reads one.
Our process will model a fair die with faces faces. The state of the process
will consist of 2 values: the value of the most recent roll, and a running
total of all previous rolls.
(define-process fair-die (stochastic-process) (:state-size 2)
((faces 6d0 :bounds (2 nil) :doc "Number of faces."))
(:documentation "A die rolled once per step. Element 0 is the latest roll,
element 1 the running total."))
(defmethod initial-state ((p fair-die) market)
(declare (ignore market))
(make-array 2 :element-type 'double-float :initial-element 0d0))
(defmethod process-state-names ((p fair-die)) '(:spot :total))
(defmethod make-stepper ((p fair-die) market times)
(declare (ignore market times))
(let ((faces (process-parameter p :faces)))
(declare (type double-float faces))
(lambda (state normals j)
(declare (type (simple-array double-float (*)) state normals) (ignore j))
;; convert standard normal to discrete uniform U(1,FACES)
(let ((roll (+ 1d0 (min (- faces 1d0)
(ffloor (* faces (norm-cdf (aref normals 0))))))))
(setf (aref state 0) roll
(aref state 1) (+ (aref state 1) roll)))
nil)))
A parameter given as (name nil :market-default fn) is taken from the market
when left unset; (name default :parameter nil) is a setting, not a model
parameter.
[macro] FINCL:DEFINE-PROCESS NAME SUPERCLASSES (&KEY STATE-SIZE FACTORS) SLOTS &REST CLASS-OPTIONS
Define the process class NAME and its constructor MAKE-NAME. SUPERCLASSES defaults to (STOCHASTIC-PROCESS). STATE-SIZE and FACTORS, when given, define PROCESS-STATE-SIZE and PROCESS-FACTORS (both default to 1). Each of SLOTS is
(slot-name default &key bounds market-default (parameter t) measure-dependent doc reader type)
DEFAULT is the initform, evaluated per instance.
NIL, with a MARKET-DEFAULT, means "take it from the market".BOUNDS is (lo hi) in interval-designator form: a real is inclusive, (x) exclusive,
NILunbounded.MARKET-DEFAULT names a function (process market horizon) -> double-float.
PARAMETER
NILdeclares a setting: validated, but not a model parameter (not in PROCESS-PARAMETERS or PARAMETER-VECTOR).MEASURE-DEPENDENT
Tmarks a parameter whose physical value may differ from its risk-neutral one (CHANGE-MEASURE's:PARAMETERS); the defaultNILkeeps it fixed under a change of measure.READERdefaults to SLOT-NAME, and the initarg is the keyword SLOT-NAME.TYPEdefaults toDOUBLE-FLOAT, or (OR(01)NULL(01)DOUBLE-FLOAT) when DEFAULT isNIL.
MAKE-NAME takes the initargs of NAME and its DEFINE-PROCESS superclasses as keywords, passing only those given, so omitted ones keep their defaults. The class option (:constructor nil) leaves it out (abstract classes); it signals CONSTRUCTOR-COLLISION at load time if MAKE-NAME is already a function it did not define for NAME. Steppers, characteristic functions and samplers stay ordinary
DEFMETHODs.(define-process heston (stochastic-process) (:state-size 2 :factors 2) ((v0 nil :market-default heston-default-v0 :bounds (0 nil) :doc "Initial variance.") (kappa 2d0 :bounds ((0) nil) :doc "Mean-reversion speed.")) (:documentation "Heston stochastic volatility."))
(make-heston :kappa 1.5d0)
[class] FINCL:STOCHASTIC-PROCESS FINCL:PARAMETERIZED
Dynamics of one or more state variables. Define concrete processes with DEFINE-PROCESS.
[class] FINCL:INDEPENDENT-INCREMENTS
Mixin for processes whose log-increments over [t0, t1] do not depend on the state at t0 (Levy processes with deterministic time dependence, GBM among them). Such processes provide INCREMENT-CHARACTERISTIC-FUNCTION, and Fourier engines can then step backwards through exercise dates.
[function] FINCL:PROCESS-PARAMETERS PROCESS-OR-CLASS
Names of the model parameters of a process, or a process class name, in declaration order. Settings declared with
:PARAMETERNIL(a GARCH period) are excluded.(process-parameters 'heston) => (V0 KAPPA THETA XI RHO)
[function] FINCL:PROCESS-PARAMETER PROCESS NAME &OPTIONAL MARKET (HORIZON 1.0d0)
The value of parameter or setting NAME of PROCESS. NAME is matched by symbol name, so a keyword works from any package. A
NILvalue means the parameter comes from the market. With MARKET, that default is resolved on MARKET at HORIZON (market time); without it,NILis returned.(process-parameter (make-instance 'heston :rho -0.5d0) :rho) => -0.5d0 (process-parameter (make-instance 'heston) :v0) =>
NIL(process-parameter (make-instance 'heston) :v0 market) => 0.04d0
[function] FINCL:PARAMETER-VECTOR PROCESS MARKET &OPTIONAL (HORIZON 1.0d0)
The model parameters of PROCESS as a (
SIMPLE-ARRAYDOUBLE-FLOAT(*)), in the order of PROCESS-PARAMETERS. ANILparameter is replaced by its market default, evaluated on MARKET at HORIZON (market time).(parameter-vector (make-instance 'heston) m) => #(0.04d0 2d0 0.04d0 0.3d0 -0.7d0)
[generic-function] FINCL:PROCESS-FACTORS PROCESS
Independent standard normals consumed per time step.
[generic-function] FINCL:PROCESS-STATE-SIZE PROCESS
Length of the state vector. Element 0 is the observable.
[generic-function] FINCL:RESOLVE-PROCESS PROCESS MARKET HORIZON
PROCESS with every parameter left
NIL(a market default) replaced by its value from MARKET for an instrument expiring at HORIZON (market time), as a new process; PROCESS itself if nothing isNIL. Engines call this once per price, before any other process function, so that every step, sample and characteristic function sees the same parameters. The defaults are documented on each process's slots.(resolve-process (make-instance 'heston) market 2d0) ; v0 = theta = w(2)/2
[condition] FINCL:CONSTRUCTOR-COLLISION FINCL:INVALID-INPUT
A process constructor MAKE-
would replace a function DEFINE-PROCESS did not define for that class.
[function] FINCL:NORM-CDF X
Standard normal CDF: Cody's erfc, and below -10 the asymptotic series of Abramowitz and Stegun 26.2.12, as in Jäckel's LetsBeRational, so the left tail keeps its relative precision.
(norm-cdf 1.96d0) => 0.9750021048517795d0
8.4 define-payoff
Define a payoff class from a formula of the observable at expiry. Slots are
(name type &key initform doc fact); one without an initform is a required
initarg. The class becomes a clause of make-option taking its slots as
keywords. Calls and puts with a strike inherit from strike-payoff,
which supplies phi and strike to the formula.
(define-payoff jackpot (payoff)
((top double-float :initform 6d0 :doc "The face that wins the bonus.")
(bonus double-float :fact :bonus :doc "Paid on top of the face."))
(s)
(+ s (if (>= s top) bonus 0d0)))
Monte Carlo prices any such payoff. Closed-form engines only know the built-in
ones, so :auto falls back to simulation for new payoffs.
[macro] FINCL:DEFINE-PAYOFF NAME SUPERCLASSES SLOTS (OBSERVABLE) &BODY BODY
Define the payoff class NAME and derive PAYOFF-VALUE and PAYOFF-KERNEL from one formula. Each of SLOTS is (slot-name type &key initform reader doc fact); without INITFORM the initarg is required, and FACT names the construction fact that fills the slot (see MAKE-FROM-FACTS). BODY, optionally preceded by a docstring, computes the payoff from OBSERVABLE (a double-float) and may use every slot of NAME, and the variables its superclasses declare, as typed local variables. PAYOFF-KERNEL reads them once and closes over them, so the closure makes no generic call per evaluation.
Inherit from data classes such as CALL-PUT-PAYOFF or STRIKE-PAYOFF, not from a payoff with its own formula: engines with a closed form for the parent would price the subclass with it. Doing so signals FORMULA-PAYOFF-SUPERCLASS at macroexpansion.
(define-payoff digital (call-put-payoff) ((level double-float :doc "Pays 1 beyond this level.")) (s) (if (plusp (* phi (- s level))) 1d0 0d0))
[class] FINCL:CALL-PUT-PAYOFF FINCL:PAYOFF
A payoff that comes as a call or a put.
[class] FINCL:STRIKE-PAYOFF FINCL:CALL-PUT-PAYOFF
A call or put with a strike: the data a struck payoff needs, with no formula. Build new struck payoffs on this, not on VANILLA-PAYOFF: engines with closed forms for VANILLA-PAYOFF would apply them to a subclass and return the vanilla price.
(define-payoff digital (strike-payoff) () (s) (if (plusp (* phi (- s strike))) 1d0 0d0))
[generic-function] FINCL:PAYOFF-KERNEL PAYOFF
Dispatch once, return a typed (double-float -> double-float) closure. Engines call this before entering their loops. The default wraps PAYOFF-VALUE, so any payoff with a PAYOFF-VALUE method works in a closure-driven engine; it dispatches on every call, so DEFINE-PAYOFF's typed kernel is much faster.
[condition] FINCL:FORMULA-PAYOFF-SUPERCLASS FINCL:INVALID-INPUT
DEFINE-PAYOFF was given a payoff with its own formula as a superclass. Engines with closed forms for that superclass would apply them to the subclass and return the superclass's price.
8.5 define-path-payoff
Define a payoff that depends on the path, from clauses run on each path in
the order written. In them s is the observable at the current grid point.
(:accumulate (var init)...): variables kept along a path(:state var name):varis the process state element calledname(:start form...): at the valuation date(:on slot (i) form...): on each date in the date-list slot(:every form...): at every grid point(:final form): the amount paid at expiry
(pay amount) inside :on pays on that date, and (stop) ends the path,
which then pays nothing at expiry. The observation dates become points of the
simulation grid. Path payoffs are European and priced by Monte Carlo.
The bust-game will refer to the fair-die state :total, which
keeps the running total of die rolls. When the die is rolled on a date
in rolls, check if the die rolls 1, the contract goes bust.
(define-path-payoff bust-game (payoff) ((rolls list))
(s)
(:state total :total)
(:on rolls (i)
(when (= s 1d0) (stop)))
(:final total))
[macro] FINCL:DEFINE-PATH-PAYOFF NAME SUPERCLASSES SLOTS (OBSERVABLE) &BODY CLAUSES
Define the payoff class NAME (a PATH-PAYOFF) and its PATH-KERNEL from CLAUSES. SLOTS are as in DEFINE-PAYOFF; a slot holding dates has type
LIST. Every clause may use the slots and the variables SUPERCLASSES declare (PHI, STRIKE) as typed local variables, OBSERVABLE (the observable at the current grid point, a double-float), and the latent state variables of:STATE.(:accumulate (var init) ...) per-path double-float variables, set to INIT at the start of each path (:state var name) VAR is the state component NAME (STATE-INDEX), e.g. (:state v :variance) (:start form ...) at grid index 0 (the valuation date) (:on date-slot (index) form ...) at each date of DATE-SLOT; INDEX is the date's position in the slot (:every form ...) at every grid index (:final form) the amount paid at expiry
In
:ONclauses, (pay amount) pays AMOUNT on the current date and (pay amount i) on date I of the clause's slot. Clauses run in the order written; (stop) in any of them ends the path, which then pays nothing at expiry.(define-path-payoff autocallable (payoff) ((notional double-float) (initial double-float) (barrier double-float) (coupon double-float) (observations list)) (s) (:on observations (i) (when (>= s (* barrier initial)) (pay (+ notional coupon)) (stop))) (:final (min notional (* notional (/ s initial)))))
[class] FINCL:PATH-PAYOFF FINCL:PAYOFF
A payoff defined by DEFINE-PATH-PAYOFF: its PATH-KERNEL holds all of its path logic, so it is European, combines only with PATH-INDEPENDENT, and has no closed form.
[generic-function] FINCL:PATH-KERNEL PAYOFF PATH-FEATURE PROCESS GRID
(values init step final): typed closures over a per-path accumulator ACC, a (
SIMPLE-ARRAYDOUBLE-FLOAT(*)) of PATH-ACCUMULATOR-SIZE.(init acc) resets ACC at the start of a path; (step acc j state pay) sees the full STATE at grid index J (0 included) and returns true to continue,
NILto stop the path; (funcall pay amount k) records AMOUNT paid on payment date K (PATH-PAYMENT-DATES); (final acc state) the amount paid at expiry, if not stopped.PROCESS is resolved; read latent components through STATE-INDEX here, once. GRID is the simulation's TIME-GRID. The default for path-independent payoffs wraps PAYOFF-KERNEL:
STEPdoes nothing and FINAL reads the observable.
[function] FINCL:STATE-INDEX PROCESS DESIGNATOR
The state-vector index of the component DESIGNATOR names: a keyword from PROCESS-STATE-NAMES, or a list whose first element is one (task 23 adds the underlying after it). Resolve names once, outside inner loops.
(state-index (make-heston) :variance) => 1
8.6 define-fact and define-clause
make-option is built from clauses that set named facts. define-fact declares
a fact; define-clause adds a clause setting it with publish, and a payoff
slot with :fact reads it:
(define-fact :bonus double-float "Paid on top of the top face."
:coerce #'real-to-double)
(define-clause option bonus (amount)
(:publishes :bonus)
"Pay AMOUNT on a roll of the top face."
(publish :bonus amount))
so (make-option (jackpot) (bonus 10) ...) fills the bonus slot of jackpot.
A clause lists the facts it may set in (:publishes ...).
[macro] FINCL:DEFINE-FACT NAME TYPE DOCUMENTATION &KEY COERCE
Register the fact NAME (a keyword) with values of
TYPE.COERCE, a function designator, normalizes a value before the type check. A name means the same thing in every language, so define a fact once and share it.(define-fact :strike double-float "The option's strike." :coerce (lambda (x) (float x 1d0)))
[macro] FINCL:DEFINE-CLAUSE LANGUAGE NAME LAMBDA-LIST &BODY BODY
Define the clause NAME of LANGUAGE. LAMBDA-LIST receives the clause's arguments, already evaluated; if it ends in &CLAUSES VAR (after required parameters only), the remaining forms are sub-clauses, bound to VAR as data, for the body to run with APPLY-CLAUSES, usually inside WITH-SCOPE. BODY may start with a docstring and a (
:PUBLISHESfact...) form declaring every fact it may set.(define-clause option expires (when &key from calendar) (:publishes :expiry) "The expiry: a date, or a tenor resolved from FROM." (publish :expiry (resolve-expiry when :from from :calendar calendar)))
[function] FINCL:APPLY-CLAUSES FORMS
Run clause FORMS (data) in order, in the current scope.
[macro] FINCL:WITH-SCOPE (KEY) &BODY BODY
Run BODY one scope deeper, under KEY. Facts published in BODY belong to the new scope; reads fall back to the enclosing scopes.
(with-scope (:pay) (make-from-facts 'leg))
[function] FINCL:MAKE-FROM-FACTS CLASS &REST EXPLICIT-INITARGS
Make an instance of
CLASS(a COMPONENT-CLASS or its name), filling every slot that names a fact from the current fact table. EXPLICIT-INITARGS win over facts. A required slot whose fact is missing signals MISSING-FACT, naming the class, the slot and the clauses that supply the fact.(make-from-facts 'european-exercise) ;
:EXPIRYfrom the table (make-from-facts 'vanilla-payoff :strike 95) ;:STRIKEgiven explicitly
[function] FINCL:FACT FACT
The value of FACT seen from the current scope, deriving it by rule if no clause gave it: (values value t). If neither works, (values nil nil missing-inputs), MISSING-INPUTS being the facts a rule lacked. Marks the fact used.
(fact :calendar) => #
, T
8.7 A dice game
Putting the pieces together. Let us simulate our games played at our casino and price the contracts we'll write on them.
(define-currency :chip :name "Casino chip" :fraction-digits 0)
(define-observance :previous-weekday (date)
(case (day-of-week date)
(6 (date+ date -1))
(7 (date+ date -2))
(t date)))
(define-calendar casino (weekends-only)
"Closed on Christmas Day, and on the 26th, observed on the previous weekday."
(:fixed 12 25)
(:fixed 12 26 :observe :previous-weekday))
(define-process fair-die (stochastic-process) (:state-size 2)
((faces 6d0 :bounds (2 nil) :doc "Number of faces."))
(:documentation "A die rolled once per step. Element 0 is the latest roll,
element 1 the running total."))
(defmethod initial-state ((p fair-die) market)
(declare (ignore market))
(make-array 2 :element-type 'double-float :initial-element 0d0))
(defmethod process-state-names ((p fair-die)) '(:spot :total))
(defmethod make-stepper ((p fair-die) market times)
(declare (ignore market times))
(let ((faces (process-parameter p :faces)))
(declare (type double-float faces))
(lambda (state normals j)
(declare (type (simple-array double-float (*)) state normals) (ignore j))
;; Phi(Z) is uniform on (0, 1), so floor(faces U) + 1 is uniform on 1..faces.
(let ((roll (+ 1d0 (min (- faces 1d0)
(ffloor (* faces (norm-cdf (aref normals 0))))))))
(setf (aref state 0) roll
(aref state 1) (+ (aref state 1) roll)))
nil)))
(define-fact :bonus double-float "Paid on top of the top face."
:coerce #'real-to-double)
(define-clause option bonus (amount)
(:publishes :bonus)
"Pay AMOUNT on a roll of the top face."
(publish :bonus amount))
(define-payoff jackpot (payoff)
((top double-float :initform 6d0 :doc "The face that wins the bonus.")
(bonus double-float :fact :bonus :doc "Paid on top of the face."))
(s)
(+ s (if (>= s top) bonus 0d0)))
(define-path-payoff bust-game (payoff) ((rolls list))
(s)
(:state total :total)
(:on rolls (i)
(when (= s 1d0) (stop)))
(:final total))
Now, pricing two contracts on the die:
(defparameter *today* #D"2026-10-26")
(defparameter *market*
(make-market :valuation-date *today*
:underlyings '((:die :spot 1 :currency :chip :vol 0.2d0))
:curves '((:chip-curve :rate 0d0))
:discounting '((:chip . :chip-curve))))
(defparameter *engine*
(make-engine :mc :process (make-fair-die) :n-paths 200000 :n-steps 3))
;; Pays the last roll, plus 10 chips on a 6: expected 3.5 + 10/6.
(price (make-option (jackpot) (bonus 10) (currency :chip)
(expires #T"2M" :from *today* :calendar +casino+))
*engine* *market*)
;; ==> 5.17...
;; Weekly rolls; pays the total after three rolls unless a 1 shows up.
(price (make-option (bust-game :rolls (list #D"2026-11-02" #D"2026-11-09" #D"2026-11-16"))
(underlying :die) (expires #D"2026-11-16"))
*engine* *market*)
;; ==> 6.96... (exactly (5/6)^3 * 12 = 6.944)