Manual 13 Your own models and payoffs
Extending the package
Models and payoffs are open for extension: implement a struct and one method, and all metrics, simulation methods, positions and portfolios work with it.
A new model
- Define a struct subtyping the abstract type that describes it (see the hierarchy in Models): an
AbstractMonteCarloEngineif it knows nothing about rates and dividends, otherwise one of theAbstractMonteCarloProcesssubtypes. It holds only its parameters: the spot and the dividends come with theUnderlyingpassed next to it. - Implement
FinancialMonteCarlo.simulate!(S, model, underlying, rfCurve, mcConfig, T)(engines: withoutunderlyingandrfCurve) filling the preallocatedNsim × (Nstep + 1)matrixS.
Reusing an engine for the random part is usually enough. For instance, Black-Scholes parametrised by the variance instead of the volatility:
using FinancialMonteCarlo
struct BlackScholesVarianceProcess{num <: Number} <: FinancialMonteCarlo.ItoProcess{num}
v::num # variance
end
function FinancialMonteCarlo.simulate!(S, model::BlackScholesVarianceProcess, underlying::FinancialMonteCarlo.AbstractUnderlying, rfCurve::FinancialMonteCarlo.AbstractZeroRateCurve, mcConfig::FinancialMonteCarlo.AbstractMonteCarloConfiguration, T::Number)
μ = rfCurve.r - underlying.d # risk neutral drift
FinancialMonteCarlo.simulate!(S, GeometricBrownianMotion(sqrt(model.v), μ, underlying.S0), mcConfig, T)
return nothing
end
model = BlackScholesVarianceProcess(0.04)
underlying = Underlying(100.0, 0.01)
mcConfig = MonteCarloConfiguration(10_000, 30)
pricer(model, underlying, ZeroRate(0.02), mcConfig, EuropeanOption(1.0, 100.0))8.243560026581395A model built on an engine inherits everything the engine supports: antithetic variates, Sobol sequences, time dependent rates (μ above is a curve when rfCurve is one) and, with CUDA.jl loaded, the GPU. Nothing else needs to be written.
A model that needs its own time stepping can still support all of them with a single simulate! body, built on the hooks the built-in models use (see src/02_models/models/paths.jl):
step_drifts(μ, dt, Nstep)anddrift_of_step(drifts, j): the drift of each step, a single number for a constant rate and a vector only for a curve;path_sides(X, mcConfig): the paths to fill with the sign of their normal draws, all of them, or the two halves with antithetic variates;draw_buffer(mcConfig, type, N)anddraw_normals!(Z, mcConfig): buffers and normal draws on the device of the mode of the configuration (CPU, or GPU withCudaMode).
Sobol sequences draw path by path, so they need a separate method dispatching on FinancialMonteCarlo.SobolConfig, a MonteCarloConfiguration with SobolMC sampling.
A new payoff
- Define a struct subtyping the payoff family (
EuropeanPayoff,PathDependentPayoff,AmericanPayoff, ...), with the maturity in a field namedT. - Implement
FinancialMonteCarlo.payout: for European and American payoffs it takes the value of the underlying at one time, for path dependent payoffs the whole path.
The generic engine of the family takes care of picking the right time steps, discounting and, for early exercise, of the Longstaff-Schwartz regression. A capped call:
struct CappedCall{num <: Number} <: FinancialMonteCarlo.EuropeanPayoff{num}
T::num
K::num
cap::num
end
FinancialMonteCarlo.payout(ST::Number, p::CappedCall) = min(max(ST - p.K, zero(ST)), p.cap)
capped = CappedCall(1.0, 100.0, 10.0)
pricer(model, underlying, ZeroRate(0.02), mcConfig, capped)3.710496033734819The new payoff takes part in the contract algebra like the built-in ones:
pricer(model, underlying, ZeroRate(0.02), mcConfig, 2.0 * capped - EuropeanOption(1.0, 110.0))2.887928074623059Automatic differentiation friendliness
To keep dual numbers working:
- keep numeric fields parametric (
CappedCalluses one shared parameter, the built-in structs one per field) so that they can hold dual numbers; - allocate with the number type returned by
FinancialMonteCarlo.price_type(inputs...), neverFloat64; - validate in a named function marked
ChainRulesCore.@non_differentiableand called directly (not in aChainRulesCore.@ignore_derivativesblock, whose closure Zygote traces at every call).
For Enzyme as well:
- draw scalar random numbers with
FinancialMonteCarlo.draw_uniform,draw_exponentialanddraw_normal, which the extension marks inactive, rather thanrand(rng): Enzyme cannot analyse the scalar draws of theMersenneTwister; - go through the paths of
FinancialMonteCarlo.path_sideswithforeach, not with aforloop over the tuple, whose iteration state Enzyme cannot type; - avoid LAPACK factorizations (
lu,qr) inside the simulation or the payoff, Enzyme has no rule for them.