Tutorial
Motivating example
In the example code below we show, without detailed explanation, how to construct and value a European call option on a single stock using combinations of the basic primitive types. Each of the primitive types and operations utilized will be explained in more detail in subsequent sections.
using Miletus
using Dates
using Miletus.TermStructure
using Miletus.DayCounts
using BusinessDays
import Miletus: When, Give, Receive, Pay, Buy, Both, At, Either, Zero
import Miletus: YieldModel, maturitydate
Acquire the rights to a contract with 100 units
x = Receive(100)
Amount
└─100
Acquire the rights to a contract with 100 units as an obligation
x = Pay(100)
Give
└─Amount
└─100
Acquire the rights to a contract with 100 USD as an obligation
x = Pay(100USD)
Give
└─Amount
└─100USD
Construct an object containing the core properties of our stock model including the start price, yield curve and carry curve
s = SingleStock()
SingleStock
The functional definition for buying a stock at a given price
x = Both(s, Pay(100USD))
Both
├─SingleStock
└─Give
└─Amount
└─100USD
Calling the Buy method defined as in the previous operation
x = Buy(s, 100USD)
Both
├─SingleStock
└─Give
└─Amount
└─100USD
Defining the acquisition of rights to a contract on a given date
x = When(At(Date("2016-12-25")), Receive(100USD))
When
├─{==}
│ ├─DateObs
│ └─2016-12-25
└─Amount
└─100USD
Constructing a zero coupon bond with a function having the same components as in the previous operation
z = ZCB(Date("2016-12-25"), 100USD)
When
├─{==}
│ ├─DateObs
│ └─2016-12-25
└─Amount
└─100USD
One of the most basic of option structures, acquisition of either a stock or an empty contract having no rights and no obligations
x = Either(SingleStock(), Zero())
Either
├─SingleStock
└─Zero
Combining all of the above concepts into the definition of a European call option
x = When(At(Date("2016-12-25")), Either(Buy(SingleStock(), 100USD), Zero()))
When
├─{==}
│ ├─DateObs
│ └─2016-12-25
└─Either
├─Both
│ ├─SingleStock
│ └─Give
│ └─Amount
│ └─100USD
└─Zero
Calling the functional form of a European Call option defined using the same components as in the previous operation
eucall = EuropeanCall(Date("2016-12-25"), SingleStock(), 100USD)
When
├─{==}
│ ├─DateObs
│ └─2016-12-25
└─Either
├─Both
│ ├─SingleStock
│ └─Give
│ └─Amount
│ └─100USD
└─Zero
Construction of a Geometric Brownian Motion Model used for describing the price dynamics of a stock
gbmm = GeomBMModel(Date("2016-01-01"), 100.0USD, 0.1, 0.05, .15)
Geometric Brownian Motion Model
-------------------------------
S₀ = 100.0USD
T = 2016-01-01
Yield Constant Continuous Curve with r = 0.1, T = 2016-01-01
Carry Constant Continuous Curve with r = 0.05, T = 2016-01-01
σ = 0.15
Valuation of our European call option whose underlying stock model uses a Geometric Brownian Motion Model for its price dynamics
value(gbmm, eucall)
8.09128105913761USD
Building Contracts with Primitive and Derived Types
Most of the types defined in Miletus are built upon a small set abstract types (Contract
, Observable{T}
, Process{T}
, TermStruct
, DayCount
, AbstractModel
), and each of the primitive combinators described in the original PJ&E papers are implemented as a typealias
of a set of Julia types having one of these abstract types as a super type.
Contract primitives
The set of Contract
primitives includes the following types:
Zero()
- A "null" contract
Amount(o::Observable)
- Receive an amount of the observable object
o
- Receive an amount of the observable object
Scale(s::Observable, c::Contract)
- Scale the contract
c
bys
- Scale the contract
Both(c1::Contract, c2::Contract)
- Acquire both contracts
c1
andc2
- This type corresponds to the
and
combinator in the PJ&E papers.
- Acquire both contracts
Either(c1::Contract, c2::Contract)
- Acquire either contract
c1
orc2
- This type corresponds to the
or
combinator in the PJ&E papers.
- Acquire either contract
Give(c::Contract)
- Take the opposite side of contract
c
- Acquires the rights to contract
c
as an obligation
- Take the opposite side of contract
Cond(p::Observable{Bool}, c1::Contract, c2::Contract)
- If expression
p
is true at the point of acquisition, then acquire contractc1
, otherwise acquire contractc2
- If expression
When(p::Observable{Bool}, c::Contract)
- Acquire the contract
c
at the point when observable quantityp
becomestrue
.
- Acquire the contract
Anytime(p::Observable{Bool}, c::Contract)
- May acquire the contract
c
at any point when observable quantityp
istrue
.
- May acquire the contract
Until(p::Observable{Bool}, c::Contract)
- A contract that acts like contract
c
untilp
istrue
, at which point the object is abandoned, and hence becomes worthless.
- A contract that acts like contract
Primative Observables
Like Contract
, Observable{T}
is defined as an abstract type. Specific instances of an Observable
type are objects, possibly time-varying, and possibly unknown at contracting time, for which a direct measurement can be made. Example observable quantities include date, price, temperature, population or other objects that can be objectively measured.
Built-in primitive Observable
types include the following:
DateObs() <: Observable{Date}
- A singleton type representing the "free" date observable
AcquisitionDateObs() <: Observable{Date}
- The acquisition date of the contract
ConstObs{T} <: Observable{T}
- A constant observable quantity
ConstObs(x)
- Constructor function for a constant observable of valuex
Derived Observables
Built-in derived observable types include the following:
At(t::Date) <: Observable{Bool}
At(t::Date) = LiftObs(==,DateObs(),ConstObs(t))
- An observable that is
true
when the date ist
- This type of observable is used as part of the construction of the derived contract primitives
ZCB
,WhenAt
,Forward
, andEuropean
BeforeObs(t::Date) <: Observable{Bool}
BeforeObs(t::Date) = LiftObs(<=,DateObs(),ConstObs(t))
- An observable that is
true
when the date is before or equal tot
- This type of observable is useds as part of the construction of the derived contract primitives
AnytimeBefore
andAmerican
Each of these derived Observable
types makes use of a LiftObs
operation.
LiftObs
is defined as an immutable
type whose type constructor applies a function to one or more existing Observable
quantities to produce a new Observable
.
Constructing Observables and Contracts
To provide an example of how one goes about using the above primitive and derived Observable
types, let's return to one of the operations from the opening "Motivting Example" section. We will break apart each piece of the constructed zero coupon bond, to point out the specific Contract
and Observable
components utilized.
Defining the acquisition of rights to a contract on a given date
x = When(At(Date("2016-12-25")), Receive(100USD))
When
├─{==}
│ ├─DateObs
│ └─2016-12-25
└─Amount
└─100USD
Constructing a zero coupon bond with a function having the same components as in the previous operation
z = ZCB(Date("2016-12-25"), 100USD)
When
├─{==}
│ ├─DateObs
│ └─2016-12-25
└─Amount
└─100USD
The most basic primitives in the above zero coupon bond construction are the Amount
primitive Contract
type used for representing the value of 100, the CurrencyUnit
and CurrencyQuantity
types used when representing USD, and the DateObs
primitive Observable
type used for representing the a Date
.
The expression Receive(100USD)
creates a Contract
object that provides acquisition rights to 100USD.
The expression At(Date("2016-12-25"))
creates a new LiftObs
observable object that is true
when the current date in the valuation model is "2016-12-25". The implementation of the At
observable type constructor includes the following operations:
const At = LiftObs{typeof(==),Tuple{DateObs,ConstObs{Date}},Bool}
At(t::Date) = LiftObs(==,DateObs(),ConstObs(t))
const At = At
The arguments to LiftObs
in the definition of At
include:
- The
==
function that will be applied to two observable values on date quantities - A
DateObs
object that acts as a reference observable quantity for the "Current Date" when valuing a model - An input date
t
which becomes a constant observable quantityConstObs(t)
to which the reference observable is compared when valuing a contract.
The commands below show both the hierarchy of observables and the type of the result returned by a call to At
.
At(Date("2016-12-25"))
{==}
├─DateObs
└─2016-12-25
typeof(At(Date("2016-12-25")))
Miletus.LiftObs{typeof(==), Tuple{Miletus.DateObs, Miletus.ConstObs{Dates.Date}}, Bool}
With use of the When
primitive Contract
, the combination of our defined Receive(100USD)
Contract
object with the above At(Date("2016-12-25"))
Observable
object constructs new a zero coupon bond Contract
that defines a payment of 100USD to the holder on December 25th, 2016.
The concept of optionality provides a contract acquirer with a choice on whether to exercise particular rights embedded in that contract. The most basic Contract
primitives representing optionality in Miletus are the Either
and Cond
primitives described previously.
Adjusting the zero coupon bond example above to incorporate the Either
, Both
and At
Contract
and Observable
primitives allow for implementing a European Call option as repeated below.
x = When(At(Date("2016-12-25")), Either(Both(SingleStock(), Pay(100USD)), Zero()))
When
├─{==}
│ ├─DateObs
│ └─2016-12-25
└─Either
├─Both
│ ├─SingleStock
│ └─Give
│ └─Amount
│ └─100USD
└─Zero
The above operations are defined as the typealias EuropeanCall
eucall = EuropeanCall(Date("2016-12-25"), SingleStock(), 100USD)
When
├─{==}
│ ├─DateObs
│ └─2016-12-25
└─Either
├─Both
│ ├─SingleStock
│ └─Give
│ └─Amount
│ └─100USD
└─Zero
By combining various Contract
and Observable
primitives, contract payoffs of arbitrary complexity can be constructed easily.
The next section lists a number of built-in derived contracts that combine the above primitives in the defintion of various types of options instruments.
Built-in Derived Contracts
By combining these contract primitives, a set of typealias
quantities are defined that allow for more compact syntax when creating various derived contracts. Using these type aliases, a set of constructors for these derived contracts are defined as shown below:
Receive(x::Union{Real,CurrencyQuantity}) = Amount(ConstObs(x))
- Receive an amount of a particular real valued object or currency
Pay(x::Union{Real,CurrencyQuantity}) = Give(Receive(x))
- Pay an amount of a particular real valued object or currency
Buy(c::Contract, x::Union{Real,CurrencyQuantity}) = Both(c, Pay(x))
- Purchase a contract
c
for an amount of a particular real valued object or currency
- Purchase a contract
Sell(c::Contract, x::Union{Real,CurrencyQuantity}) = Both(Give(c), Receive(x))
- Sell a contract
c
for an amount of a particular real valued object or currency
- Sell a contract
ZCB(date::Date, x::Union{Real,CurrencyQuantity}) = When(At(date), Receive(x))
- A "Zero Coupon Bond" that provides for obtaining a particular amount of a real valued object or currency on a particular maturity
date
- A "Zero Coupon Bond" that provides for obtaining a particular amount of a real valued object or currency on a particular maturity
WhenAt(date::Date, c::Contract) = When(At(date), c)
- Activate the contract
c
on the particular maturitydate
- Activate the contract
Forward(date::Date, c::Contract, strike::Union{Real,CurrencyQuantity}) = WhenAt(date, Buy(c, strike))
- Purchase a contract
c
for a particular amount of a real valued object or currency (strike
) on a particular maturitydate
- Purchase a contract
Option(c::Contract) = Either(c, Zero())
- Activate either contract
c
or nothing
- Activate either contract
European(date::Date, c::Contract) = WhenAt(date, Option(c))
- On a particular maturity
date
acquire either contractc
or nothing
- On a particular maturity
EuropeanCall(date::Date, c::Contract, strike::Union{Real,CurrencyQuantity}) = European(date, Buy(c, strike))
- A European call contract, with maturity
date
, on underlying contractc
at pricestrike
- A European call contract, with maturity
EuropeanPut(date::Date, c::Contract, strike::Union{Real,CurrencyQuantity}) = European(date, Sell(c, strike))
- A European put contract, with maturity
date
, on underlying contractc
at pricestrike
- A European put contract, with maturity
AnytimeBefore(date::Date, c::Contract) = Anytime(BeforeObs(date), c)
- Activate the contract
c
anytime before a particular maturitydate
- Activate the contract
American(date::Date, c::Contract) = AnytimeBefore(date, Option(c))
- Either activate the contract
c
or nothing anytime before a particular maturitydate
- Either activate the contract
AmericanCall(date::Date, c::Contract, strike::Union{Real,CurrencyQuantity}) = American(date, Buy(c, strike))
- An American call contract, with maturity
date
, on underlying contractc
at pricestrike
- An American call contract, with maturity
AmericanPut(date::Date, c::Contract, strike::Union{Real,CurrencyQuantity}) = American(date, Sell(c, strike))
- An American put contract, with maturity
date
, on underlying contractc
at pricestrike
- An American put contract, with maturity
AsianFixedStrikeCall(dt::Date, c::Contract, period::Period, strike) = European(dt, Buy(MovingAveragePrice(c, period), strike))
- An Asian option contract where the strike price is constant and whose pay off is based on the moving average price of the underlying over the life of the contract.
AsianFloatingStrikeCall(dt::Date, c::Contract, period::Period, strike) = European(dt, Both(c, Give(MovingAveragePrice(c, period))))
- An Asian option contract where the strike price and payoff are based on the moving average price of the underlying over the life of the contract.
DayCounts
Miletus provides implementations of a number of separate calendar implementations that take into consideration day count conventions from different countries and financial organizations worldwide. Each day count type is an instance of an abstract DayCount
type.
Specific DayCount
instances present in Miletus include:
- Actual360 - Uses a coupon factor equal to the number of days between two dates in a Julian calendar divided by 360.
- Actual365 - Uses a coupon factor equal to the number of days between two dates in a Julian calendar divided by 365.
- BondThirty360 / USAThirty360 - Uses a coupon factor equal to the number of days between two dates assuming 30 days in any month and 360 days in a year. Used for the pricing of US Corporate Bonds and many US agency bond issues.
- EuroBondThirty360 / EuroThirty360 - Uses a coupon factor equal to the number of days between two dates assuming 30 days in any month and 360 dates in a year.
- ItalianThirty360
- ISMAActualActual
- ISDAActualActual
- AFBActualActual
For each DayCount
type, the yearfraction
function provides the fractional position within the associated year for a provided input date.
Modifying a particular date in the course of a calculation often needs to take into account the above DayCount
convention, as well as a relevant holiday calendar. The adjust
function takes into account holidays through functionality used from the HolidayCalendar
included BusinessDays
package.
Processes
In the context of the contract definition language implemented by Miletus, a Process
, p(t)
, is a mapping from time to a random variable of a particular type. Both Contract
objects and Observable
objects can be modeled as a Process
. Like Contract
and Observable
, a Process
is defined in Miletus as an abstract type, where subtypes of Process
are implemented as immutable types.
The following Process
types are available for operating on Contract
and Observable
objects
DateProcess()
- maps anObservable
date to the given date.ConstProcess(val::T)
- maps anObservable
value to a constant value (val::T
) for all times.CondProcess(cond::Process{Bool}, a::Process{T}, b::Process{T})
- based on firstProcess
boolean value, maps to one of two distinctProcess
values.
Term Structures
Term Structures provide a framework for representing how interest rates for a given set of modeling assumptions change through time.
TermStruct - An abstract type that is a super type to all Term Structures implmented in Miletus
YieldTermStructure - An abstract type that encompasses various interest rate term structure models
VolatilityTermStructure - An abstract type that encompasses various volatility term structure models
ConstantYieldCurve - A concrete type encompassing a constant interest rate model
ConstantVolatilityCurve - A concrete type encompassing a constant volatility model
compound_factor - Multiplicative factor using the frequency and method by accumulated interest is included in principle for the purporses of interest rate calculations
discountfactor - Inverse of the above compoundfactor
implied_rate - Determination of the current interest rate implied from the compounding factor
forward_rate - A rate of interest as implied by the current zero rate of a given YieldTermStructure for periods of time in the future.
zero_rate - The implied spot interest rate for a given YieldTermStructure and time horizon
par_rate - A coupon rate for which a bond price equals its nominal value
Models
A valuation model encompasses both the analytical mathematical description of the dynamics involved in how an observable quantity changes through time, as well as a numerical method used for discretizing and solving those analytical equations.
There are a wide variety of different analytical models for describing the value dynamics of interest rates, stocks, bonds, credit instruments (e.g. mortgages, credit cards, other loans) and other securities. With regards to numerical methods, most techniques fall into one of four distinct categories; Analytical Methods (closed-form equations), Lattice Methods (e.g. trees), Monte Carlo Methods, and Partial Differential Equation solvers (e.g. finite difference, finite element).
The Contract
and Observable
primitives described previously are used for setting up payoffs that act as boundary conditions and final conditions on the use of a model to value an instrument.
Implemented Models and Valuation methods
Core Model (objective assumptions underlying the model. everything except volatility. objective parameters that can be observed in the market)
Core Forward Model
Yield Curves and Dates
Geometric Brownian Motion
GeomBMModel(startdate, startprice, interestrate, carryrate, volatility)
A model for a
SingleStock
, following a geometric Brownian motion that includes the following fields:startdate
startprice
: initial price atstartdate
interestrate
: risk free rate of return.carryrate
: the carry rate, i.e. the net return for holding the asset:- for stocks this is typically positive (i.e. dividends)
- for commodities this is typically negative (i.e. cost-of-carry)
volatility
:- The
interestrate
,carryrate
andvolatility
are all specified on a continously compounded, Actual/365 basis. - The price is assumed to follow the PDE:
$dS_t = (\kappa - \sigma^2/2) S_t dt + \sigma S_t dW_t$
- where $W_t$ is a Wiener process, and
κ = interestrate - carryrate
.
- The
Associated valuation routines make use of analytical methods for solving the Black-Scholes equation, or when determining implied volatitilies based on the Black-Scholes equation.
Binomial Geometric Random Walk
BinomialGeomRWModel(startdate, enddate, nsteps, S₀, Δt, iR, logu, logd, p, q)
A model for a Binomial Geometric Random Walk (aka Binomial tree)
The valuation routines for binomial trees are initialized using the payoff condition of the associated contract at expiry(
enddate
) and subsequently work backward in time through the tree to determine the value of the contract at the initial time (startdate
).Includes the following fields (or the
log
of those values)startdate
: start date of processenddate
: end date of processnsteps
: number of steps in the treeS₀
: inital valueΔt
: the time-difference between steps, typicallydays(startdate - enddate) / (365*nsteps)
iR
: discount rate,exp(-Δt*interestrate)
u
: scale factor for upd
: scale factor for downp
: up probabilityq
: down probability,1-p
Plot of the underlying stock price dynamics on the binomial tree.
Cox-Ross-Rubenstein Model
- Makes use of a risk-neutral valuation principle wherein the expected return from the traded security is the risk-free interest rate, and all future cash flows can be valued by discounting their respective cashflows at that risk-free interest rate.
- Imposes the condition that d = 1/u
- u = exp(σ*√Δt)
- d = exp(-σ*√Δt)
- p = (exp(r*Δt)-d)/(u-d)
- q = (u-exp(r*Δt))/(u-d)
Plot of the underlying stock price dynamics on the binomial tree for the Cox-Ross-Rubenstein Model.
Jarrow-Rudd Model
- u = exp((r-σ^2/2)Δt + σ√Δt)
- d = exp((r-σ^2/2)Δt - σ√Δt)
- p = q = 0.5
- NOTE: not risk-neutral
Jarrow-Rudd Risk Neutral
- u = exp((r-σ^2/2)Δt + σ√Δt)
- d = exp((r-σ^2/2)Δt - σ√Δt)
- p = (exp(r*Δt)-d)/(u-d)
- q = (u-exp(r*Δt))/(u-d)
Tian
- u = 1/2exp(rΔt)v(v+1+sqrt(v^2+2v-3)), where v = exp(σ^2*Δt)
- d = 1/2exp(rΔt)v(v+1-sqrt(v^2+2v-3)), where v = exp(σ^2*Δt)
- p = (exp(r*Δt)-d)/(u-d)
- q = (u-exp(r*Δt))/(u-d)
Monte Carlo Model
montecarlo(m::GeomBMModel, dates, n)
- Accepts a Geometrical Brownian Motion model of the underlying asset dynamics.
- Samples
n
Monte Carlo paths of the modelm
, at timedates
. - Returns a
MonteCarloModel
MonteCarloModel(core, dates, paths)
- A
MonteCarloModel
is a type that represents the result of a simulation of a series of asset prices and includes the following fields: core
: a referenceCoreModel
dates
: anAbstractVector{Date}
paths
: a matrix of the scenario paths: the rows are the scenarios, and the columns are the values at each date indates
.
- A
MonteCarloScenario(core, dates, path)
- A
MonteCarloScenario
is a single simulation scenario of aMonteCarloModel
and includes the following fields: core
: a referenceCoreModel
dates
: anAbstractVector{Date}
paths
: anAbstractVector
of the values at each date indates
.
- A
Functions available for operating on a Model
value()
valueAt()
forwardprice()
yearfraction()
yearfractionto()
numeraire()
startdate()
ivol()
Implied Volatlity calculations
SplineInterpolation
- This is used to model interpolation between any two discrete points on a discrete convex curve. This implements double quadratic interpolation.
* `x`: An Array of the discrete values on the x axis * `y`: An Array of the discrete values on the y axis * `weights`: An Array of tuples of the weights of every quadratic curve modelled between two discrete points on the curve
SplineVolatilityModel
ivol(m::SplineInterpolation, c::European)
- Compute the implied Black-Scholes volatility of an option
c
under the SplineVolatilityModelm
.
- Compute the implied Black-Scholes volatility of an option
fit(SplineVolatilityModel, mcore::CoreModel, contracts, prices)
- Fit a
SplineVolatilityModel
using from a collection of contracts (contracts
) and their respective prices (prices
), under the assumptions ofmcore
.
- Fit a
fit_ivol(SplineVolatilityModel, mcore::CoreModel, contracts, ivols)
- Fit a
SplineVolatilityModel
using from a collection of contracts (contracts
) and their respective implied volatilities (ivols
), under the assumptions ofmcore
.
- Fit a
GeomBMModel
ivol(m::CoreModel, c::Contract, price)
- Compute the Black-Scholes implied volatility of contract
c
atprice
, under the assumptions of modelm
(ignoring the volatility value ofm
).
- Compute the Black-Scholes implied volatility of contract
fitvol(GeomBMModel, m::CoreModel, c::Contract, price)
- Fit a
GeomBMModel
using the implied volatility ofc
atprice
, using the parametersof theCoreModel
m
.
- Fit a
SABRModel
ivol(m::SABRModel, c::European)
- Compute the implied Black-Scholes volatility of an option
c
under the SABR modelm
.
- Compute the implied Black-Scholes volatility of an option
fit_ivol(SABRModel, mcore::CoreModel, contracts, ivols)
- Fit a
SABRModel
using from a collection of contracts (contracts
) and their respective implied volatilities (ivols
), under the assumptions ofmcore
.
- Fit a
sabr_alpha(F, t, σATM, β, ν, ρ)
- Not currently exported- Compute the α parameter (initial volatility) for the SABR model from the Black-Scholes at-the-money volatility.
F
: Forward pricet
: time to maturityσATM
: Black-Scholes at-the-money volatilityβ
,ν
,ρ
: parameters from SABR model.
- Compute the α parameter (initial volatility) for the SABR model from the Black-Scholes at-the-money volatility.
Greeks
Miletus allows for generic derivatives of contract prices with respect to different metrics (otherwise known as greeks)
Consider the following contract:
using Miletus, Dates
d1 = today()
d2 = d1 + Day(150)
c = EuropeanCall(d2, SingleStock(), 56.5USD)
When
├─{==}
│ ├─DateObs
│ └─2023-03-17
└─Either
├─Both
│ ├─SingleStock
│ └─Give
│ └─Amount
│ └─56.5USD
└─Zero
Now let us set up a model according to which we want the contract valued
core = CoreModel(d1, 47.32USD, 0.0, 0.0)
gbm = GeomBMModel(core, 0.1)
Geometric Brownian Motion Model
-------------------------------
S₀ = 47.32USD
T = 2022-10-18
Yield Constant Continuous Curve with r = 0.0, T = 2022-10-18
Carry Constant Continuous Curve with r = 0.0, T = 2022-10-18
σ = 0.1
Calculate delta
greek:
delta(gbm, c)
0.0031304604618523175
Other functions available:
vega
rho
gamma
Miletus also allows you to calculate generic nth derivatives with respect to various metrics. The following expression evaluates the third derivative of the contract value with respect to volatility:
greek(gbm, c; metric = :vol, n = 3)
1025.3504215786893USD