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 Base.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)
Miletus.GeomBMModel{Miletus.CoreModel{Miletus.Currency.CurrencyQuantity{Miletus.Currency.CurrencyUnit{:USD},Float64},Miletus.TermStructure.ConstantYieldCurve,Miletus.TermStructure.ConstantYieldCurve}}(Miletus.CoreModel{Miletus.Currency.CurrencyQuantity{Miletus.Currency.CurrencyUnit{:USD},Float64},Miletus.TermStructure.ConstantYieldCurve,Miletus.TermStructure.ConstantYieldCurve}(100.0USD,Miletus.TermStructure.ConstantYieldCurve(Miletus.DayCounts.Actual365(),0.1,:Continuous,-1,2016-01-01),Miletus.TermStructure.ConstantYieldCurve(Miletus.DayCounts.Actual365(),0.05,:Continuous,-1,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
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.
The set of Contract primitives includes the following types:
- Zero()
 
- Amount(o::Observable)
 
- Scale(s::Observable, c::Contract)
 
- Both(c1::Contract, c2::Contract)
 
- Either(c1::Contract, c2::Contract)
 
- Give(c::Contract)
 
- Cond(p::Observable{Bool}, c1::Contract, c2::Contract)
 
- When(p::Observable{Bool}, c::Contract)
 
- Anytime(p::Observable{Bool}, c::Contract)
 
- Until(p::Observable{Bool}, c::Contract)
 
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}
 
- AcquisitionDateObs() <: Observable{Date}
 
- ConstObs{T} <: Observable{T}
 
Built-in derived observable types include the following:
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.
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:
typealias AtObs LiftObs{typeof(==),Tuple{DateObs,ConstObs{Date}},Bool}
AtObs(t::Date) = LiftObs(==,DateObs(),ConstObs(t))
typealias At AtObs
WARNING: Method definition (::Type{Miletus.LiftObs{Base.#==, Tuple{Miletus.DateObs, Miletus.ConstObs{Base.Dates.Date}}, Bool}})(Base.Dates.Date) in module Miletus at /Users/aviks/.julia/v0.5/Miletus/src/observables.jl:65 overwritten in module ex-lift at none:2.
The arguments to LiftObs in the definition of AtObs include:
- The - ==function that will be applied to two observable values on date quantities
 
- A - DateObsobject that acts as a reference observable quantity for the "Current Date" when valuing a model
 
- An input date - twhich becomes a constant observable quantity- ConstObs(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{Base.#==,Tuple{Miletus.DateObs,Miletus.ConstObs{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 AtObs 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.
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))
 
- Pay(x::Union{Real,CurrencyQuantity}) = Give(Receive(x))
 
- Buy(c::Contract, x::Union{Real,CurrencyQuantity}) = Both(c, Pay(x))
 
- Sell(c::Contract, x::Union{Real,CurrencyQuantity}) = Both(Give(c), Receive(x))
 
- ZCB(date::Date, x::Union{Real,CurrencyQuantity}) = When(AtObs(date), Receive(x))
 
- WhenAt(date::Date, c::Contract) = When(AtObs(date), c)
 
- Forward(date::Date, c::Contract, strike::Union{Real,CurrencyQuantity}) = WhenAt(date, Buy(c, strike))
 
- Option(c::Contract) = Either(c, Zero())
 
- European(date::Date, c::Contract) = WhenAt(date, Option(c))
 
- EuropeanCall(date::Date, c::Contract, strike::Union{Real,CurrencyQuantity}) = European(date, Buy(c, strike))
 
- EuropeanPut(date::Date, c::Contract, strike::Union{Real,CurrencyQuantity}) = European(date, Sell(c, strike))
 
- AnytimeBefore(date::Date, c::Contract) = Anytime(BeforeObs(date), c)
 
- American(date::Date, c::Contract) = AnytimeBefore(date, Option(c))
 
- AmericanCall(date::Date, c::Contract, strike::Union{Real,CurrencyQuantity}) = American(date, Buy(c, strike))
 
- AmericanPut(date::Date, c::Contract, strike::Union{Real,CurrencyQuantity}) = American(date, Sell(c, strike))
 
- AsianFixedStrikeCall(dt::Date, c::Contract, period::Period, strike) = European(dt, Buy(MovingAveragePrice(c, period), strike))
 
- AsianFloatingStrikeCall(dt::Date, c::Contract, period::Period, strike) = European(dt, Both(c, Give(MovingAveragePrice(c, period))))
 
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.
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 an- Observabledate to the given date.
 
- ConstProcess(val::T)- maps an- Observablevalue to a constant value (- val::T) for all times.
 
- CondProcess(cond::Process{Bool}, a::Process{T}, b::Process{T})- based on first- Processboolean value, maps to one of two distinct- Processvalues.
 
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 
- discount_factor - Inverse of the above compound_factor 
- 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 
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.
- 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 at- startdate
 
- interestrate: risk free rate of return.
 
- carryrate: the carry rate, i.e. the net return for holding the asset:
 
 
- volatility:
 - The - interestrate,- carryrateand- volatilityare 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.
 
- 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 - logof those values)
 - startdate: start date of process
 
- enddate: end date of process
 
- nsteps: number of steps in the tree
 
- S₀: inital value
 
- Δt: the time-difference between steps, typically- days(startdate - enddate) / (365*nsteps)
 
- iR: discount rate,- exp(-Δt*interestrate)
 
- u: scale factor for up
 
- d: scale factor for down
 
- p: up probability
 
- q: 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/2*exp(r*Δt)*v*(v+1+sqrt(v^2+2v-3)), where v = exp(σ^2*Δt)
  * d = 1/2*exp(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 - nMonte Carlo paths of the model- m, at time- dates.
 
- Returns a - MonteCarloModel
 
 
- MonteCarloModel(core, dates, paths) - A - MonteCarloModelis a type that represents the result of a simulation of a series of asset prices and includes the following fields:
 
- core: a reference- CoreModel
 
- dates: an- AbstractVector{Date}
 
- paths: a matrix of the scenario paths: the rows are the scenarios, and the columns are the values at each date in- dates.
 
 
- MonteCarloScenario(core, dates, path) - A - MonteCarloScenariois a single simulation scenario of a- MonteCarloModeland includes the following fields:
 
- core: a reference- CoreModel
 
- dates: an- AbstractVector{Date}
 
- paths: an- AbstractVectorof the values at each date in- dates.
 
 
 
- value()
 
- valueAt()
 
- forwardprice()
 
- yearfraction()
 
- yearfractionto()
 
- numeraire()
 
- startdate()
 
- ivol()