lmfinance reference

Complete reference for lmfinance 0.1.4: command-line flags, exit codes, environment, the seven context objects, every host type and method of the embedded schema, and the standard lmcode_std_v3 library the host vendors. Signatures are taken from schema/lmfinance.dsl.json in the repository.

Command line

FlagBehavior
--versionPrint lmfinance X.Y.Z
--noticesPrint the embedded third-party notices
--lmcode-schema --jsonPrint the embedded effective schema as JSON (host declarations merged with the standard library)
--lmcode-schemaPrint the registry signatures as text
--lmcode-signaturesPrint the registry signatures as text: context, method and function lines
--lmcode FILE [FILE ...]Load and verify every compiled program, run them in order, stop at the first failure, write one result frame to standard output
--dry-run --lmcode FILE [FILE ...]Load and verify every program without running any; must come first; contradicting real-mode invocation metadata is a usage error

Exit codes

CodeMeaning
0Success
2Command-line or invocation metadata error (failure phase cli, code CLI_USAGE); usage text on stderr
3Program load error (phase load) or run error (phase run), including failed assertions, QuantLib errors and an exceeded memory budget
4Application failure (phase app, code APP_FAIL) or failure writing output

Environment

VariableMeaning
LMFINANCE_MAX_MEMORY_MBTotal memory budget in MiB, a positive whole number; default 4096. An invalid value is a usage error (exit 2)
LMCODE_INVOCATION_FILESet by run_lmcode to pass invocation metadata, including dry mode; not set by hand

Result envelope

FieldPresentMeaning
okalwaystrue on success, false on failure
resultsuccessValue set with lmcode_return_set or lmcode_return_put, else null
phasefailurecli, load, run or app
codefailureError code such as CLI_USAGE, LOAD_BAD_BYTECODE or RUN_HOST
messagefailureDiagnostic text; run errors start with the block line and column
line, columnrun failurePosition in the block

Context objects

NameTypePurpose
marketMarketApievaluation date and yield curves.
instrumentInstrumentApipayoffs and fixed-income instruments.
modelModelApiequity market models.
pricingPricingApiengines and valuations.
riskRiskApibumped Greeks, rate risk, value at risk.
calibrationCalibrationApiimplied volatility and Heston fitting.
lmfLmfApichecks and output.

Host types and methods

The host schema declares 19 types with 107 method signatures and no free functions. Float parameters must be finite. Objects live until the host exits; at most 4000000 objects of each kind can be created.

MarketApi

Context object market: evaluation date and yield curves.

MethodSignatureDescription
set_date(string) -> voidSet the evaluation date from a YYYY-MM-DD string (years 1901 to 2199). Set it before building curves
date() -> stringCurrent evaluation date as YYYY-MM-DD; default 2024-01-02
flat_curve(float) -> CurveFlat continuously compounded curve at the given rate
zero_curve() -> CurveBuilderBuilder for a curve from zero-rate nodes; add nodes with zero
bootstrap_curve() -> CurveBuilderBuilder for a curve bootstrapped from deposit and swap quotes

CurveBuilder

Returned by market.zero_curve and market.bootstrap_curve; methods chain.

MethodSignatureDescription
zero(float, float) -> CurveBuilderAdd a node (years, zero rate); zero_curve builders only; nodes must be at distinct maturities
deposit(string, float) -> CurveBuilderAdd a deposit quote (tenor such as 3M, rate); bootstrap builders only
swap(string, float) -> CurveBuilderAdd a swap quote (tenor such as 5Y, rate); bootstrap builders only
build() -> CurveBuild the Curve; needs at least one node or quote

Curve

An immutable yield curve anchored to the evaluation date at which it was built.

MethodSignatureDescription
discount(float) -> floatDiscount factor at t years
zero(float) -> floatContinuously compounded zero rate at t years; t must be positive
forward(float, float) -> floatContinuously compounded forward rate between t1 and t2 years; needs 0 <= t1 < t2
bumped(float) -> CurveNew curve with dr added to every continuously compounded zero rate
save_csv(string, float, int) -> voidWrite (path, max years, points): space-separated rows of time, zero rate, discount factor, forward rate; 2 to 1000000 points

InstrumentApi

Context object instrument: payoffs and fixed-income instruments.

MethodSignatureDescription
european_call(float, float) -> Option(strike, years) European call
european_put(float, float) -> Option(strike, years) European put
american_call(float, float) -> Option(strike, years) American call
american_put(float, float) -> Option(strike, years) American put
barrier_call(float, float, float, string) -> Option(strike, years, barrier, type) barrier call; type is up-in, up-out, down-in or down-out
barrier_put(float, float, float, string) -> Option(strike, years, barrier, type) barrier put; same types
asian_call(float, float, string, int) -> Option(strike, years, averaging, fixings) Asian call; averaging is geometric or arithmetic; 1 to 10000 equally spaced fixings ending at expiry
asian_put(float, float, string, int) -> Option(strike, years, averaging, fixings) Asian put
cap(float, float, float) -> CapFloor(notional, strike, years) cap on Euribor 6M; maturity in whole half years, 1 to 100 years
floor(float, float, float) -> CapFloor(notional, strike, years) floor on Euribor 6M
swaption(Swap, float) -> Swaption(swap, expiry years) option to enter the swap; expiry a whole number of months up to 50 years
bond(float, float, float, int) -> Bond(face, coupon, years, frequency) fixed-rate bond; frequency 1, 2, 4 or 12; maturity a whole number of coupon periods, at most 100 years
zero_bond(float, float) -> Bond(face, years) zero-coupon bond
swap(float, float, float) -> Swap(notional, fixed rate, years) payer swap; maturity in whole years, 1 to 100

CapFloor

A cap or floor.

MethodSignatureDescription
strike() -> floatStrike rate
years() -> floatMaturity in years

Swaption

A swaption.

MethodSignatureDescription
expiry() -> floatExpiry in years

Option

An option payoff and exercise style.

MethodSignatureDescription
strike() -> floatStrike
years() -> floatMaturity in years

Bond

A fixed-rate or zero-coupon bond.

MethodSignatureDescription
years() -> floatMaturity in years

Swap

A fixed-for-floating swap; the methods modify the swap and return it.

MethodSignatureDescription
receiver() -> SwapMake it a receiver swap (receives fixed)
payer() -> SwapMake it a payer swap (pays fixed); the default
spread(float) -> SwapSet the floating-leg spread; ignored inside a swaption

ModelApi

Context object model: equity market models.

MethodSignatureDescription
black_scholes(float, float, float, float) -> Model(spot, rate, dividend yield, volatility) Black-Scholes-Merton model; spot and volatility positive
heston(float, float, float, float, float, float, float, float) -> Model(spot, rate, dividend yield, v0, kappa, theta, sigma, rho) Heston model; v0, kappa, theta, sigma positive, rho inside (-1, 1)

Model

A Black-Scholes-Merton or Heston market.

MethodSignatureDescription
spot() -> floatSpot price
param(string) -> floatParameter by name: spot, rate, dividend; vol for Black-Scholes; v0, kappa, theta, sigma, rho for Heston
with_spot(float) -> ModelCopy with another spot
with_rate(float) -> ModelCopy with another rate
with_vol(float) -> ModelCopy with another volatility; Black-Scholes models only

PricingApi

Context object pricing: engines and valuations.

MethodSignatureDescription
analytic() -> EngineClosed-form engine: European options under Black-Scholes or Heston, barrier and geometric Asian options
baw() -> EngineBarone-Adesi-Whaley approximation engine
binomial(int) -> EngineBinomial tree engine (Cox-Ross-Rubinstein) with 2 to 20000 steps
binomial_tree(string, int) -> Engine(tree, steps) binomial engine; tree is crr, jr, tian or lr
finite_diff(int, int) -> Engine(time steps, grid points) finite-difference engine; 2 to 100000 time steps, 10 to 100000 grid points
monte_carlo(int, int) -> Engine(paths, seed) Monte Carlo engine; 16 to 100000000 paths, seed at least 1
price(Option, Model, Engine) -> ResultPrice an option under a model with an engine
bond_clean_price(Bond, Curve) -> floatClean price per 100 face on the curve
bond_npv(Bond, Curve) -> floatDirty value in currency on the curve
bond_accrued(Bond) -> floatAccrued amount
bond_price_from_yield(Bond, float) -> float(bond, yield) clean price per 100 face
bond_yield(Bond, float) -> float(bond, clean price) yield compounded at the coupon frequency
bond_duration(Bond, float) -> float(bond, yield) modified duration
bond_macaulay_duration(Bond, float) -> float(bond, yield) Macaulay duration
bond_convexity(Bond, float) -> float(bond, yield) convexity
swap_npv(Swap, Curve) -> floatNet present value on the curve
swap_par_rate(Swap, Curve) -> floatFair fixed rate on the curve
swap_annuity(Swap, Curve) -> floatFixed-leg annuity on the curve
capfloor_npv(CapFloor, Curve, float) -> float(cap or floor, curve, volatility) Black value with a flat lognormal volatility
capfloor_implied_vol(CapFloor, Curve, float) -> float(cap or floor, curve, price) Black implied volatility
capfloor_atm_rate(CapFloor, Curve) -> floatAt-the-money strike rate, where cap and floor have equal value
swaption_npv(Swaption, Curve, float) -> float(swaption, curve, volatility) Black value with a flat lognormal volatility
swaption_implied_vol(Swaption, Curve, float) -> float(swaption, curve, price) Black implied volatility
swaption_forward_rate(Swaption, Curve) -> floatFair rate of the forward-starting underlying swap

Engine

A numerical method.

MethodSignatureDescription
name() -> stringOne of analytic, binomial, finite_diff, monte_carlo, baw

Result

Returned by pricing.price. A Greek the engine does not provide is a run error.

MethodSignatureDescription
price() -> floatPrice
stderr() -> floatMonte Carlo standard error
delta() -> floatDelta
gamma() -> floatGamma
vega() -> floatVega per 1.00 of volatility
theta() -> floatTheta per year
rho() -> floatRho per 1.00 of rate

RiskApi

Context object risk: bumped Greeks, rate risk, value at risk.

MethodSignatureDescription
delta(Option, Model, Engine) -> floatCentral-difference delta (1% spot bump) with any engine; Black-Scholes model
gamma(Option, Model, Engine) -> floatCentral-difference gamma
vega(Option, Model, Engine) -> floatCentral-difference vega (volatility bump 0.001)
rho(Option, Model, Engine) -> floatCentral-difference rho (rate bump 0.0001)
theta(Option, Model, Engine) -> floatFinite-difference theta over one day; needs more than two days to expiry
save_profile(Option, Model, Engine, float, float, int, string) -> void(option, model, engine, low spot, high spot, points, path) write space-separated rows of spot, price, delta, gamma; 2 to 100000 points
bond_dv01(Bond, Curve) -> floatFall in bond value for +1 basis point of continuous zero rate
swap_dv01(Swap, Curve) -> floatSigned NPV change for +1 basis point; positive for a payer swap
var_normal(float, float, float, float) -> float(value, annual volatility, confidence, horizon days) parametric normal value at risk; 252 days per year
es_normal(float, float, float, float) -> float(value, annual volatility, confidence, horizon days) parametric normal expected shortfall
series(string) -> SeriesRead numbers from a file (whitespace or comma separated, one header line allowed) into a Series

Series

A set of samples read by risk.series; up to 100000000 values.

MethodSignatureDescription
size() -> intNumber of samples
get(int) -> floatSample at a zero-based index, in file order
mean() -> floatMean
std() -> floatSample standard deviation; needs at least 2 values
min() -> floatMinimum
max() -> floatMaximum
quantile(float) -> floatQuantile for p in [0, 1], linear interpolation between order statistics
var(float) -> floatEmpirical value at risk: minus the quantile at 1 - confidence; confidence inside (0.5, 1)
es(float) -> floatEmpirical expected shortfall: minus the mean of the samples at or below that quantile

CalibrationApi

Context object calibration: implied volatility and Heston fitting.

MethodSignatureDescription
implied_vol(Option, Model, Engine, float) -> float(option, model, engine, price) Black-Scholes implied volatility by Brent search in 0.0001 to 5
heston(float, float, float) -> HestonFit(spot, rate, dividend yield) start a Heston fit

HestonFit

A Heston calibration job; quote and guess chain.

MethodSignatureDescription
quote(float, float, float) -> HestonFit(strike, years, implied volatility) add a quote; at least 5 are needed
guess(float, float, float, float, float) -> HestonFit(v0, kappa, theta, sigma, rho) starting point; the default is 0.04, 1.5, 0.04, 0.5, -0.5
fit() -> ModelRun Levenberg-Marquardt and return the fitted Heston Model; non-convergence is a run error
error() -> floatCalibration error after fit

LmfApi

Context object lmf: checks and output.

MethodSignatureDescription
assert_close(float, float, float) -> void(a, b, tolerance) run error unless the absolute difference is within the tolerance
check(bool, string) -> void(condition, message) run error with the message when the condition is false
save_text(string, string) -> void(path, text) write a text file
print(string) -> voidWrite a line to standard output
version() -> stringThe string lmfinance X.Y.Z

String enumerations

Used byAccepted values
instrument.barrier_call, barrier_put (type)up-in, up-out, down-in, down-out
instrument.asian_call, asian_put (averaging)geometric, arithmetic
pricing.binomial_tree (tree)crr, jr, tian, lr
Model.param (name)spot, rate, dividend, vol (Black-Scholes); spot, rate, dividend, v0, kappa, theta, sigma, rho (Heston)
Engine.name (return value)analytic, binomial, finite_diff, monte_carlo, baw
CurveBuilder.deposit, swap (tenor)Period strings such as 3M, 6M, 2Y, 30Y
market.set_date (date)YYYY-MM-DD

Standard library (lmcode_std_v3)

lmfinance 0.1.4 vendors the lmcode_std_v3 schema from lmcode-cpp at the commit pinned in sdk.lock. That vendored catalog has 206 canonical signatures: 83 function signatures and 123 method signatures on 16 standard types. They are available in every lmfinance block without declaration, next to the host types above. The file functions are unrestricted byte operations relative to the working directory.

Function groups

GroupSignaturesPurpose
String17Byte-string search, slicing, case, split, replace, numeric parsing and glob match
Encoding4Base64 and hexadecimal encode and decode
Math16Integer and float overloads of abs, ceil, floor, max, min, pow, round and sqrt
File5Unrestricted whole-file byte read, write, append, existence test and LF line split
Collection constructors15Create empty lists, maps, queues, stacks and priority queues of int, float and string
JSON and templates2Parse JSON text into a Json value; render a text template from a Json value
Result sink24Set the value that run_lmcode returns as result: one value, or named fields
Collection and Json methods123Methods of the 16 standard types listed below
Total20683 function signatures plus 123 method signatures

Standard functions

GroupFunctionSignatures
Stringstr_contains(string, string) -> bool
Stringstr_ends_with(string, string) -> bool
Stringstr_find(string, string) -> int
Stringstr_is_float(string) -> bool
Stringstr_is_int(string) -> bool
Stringstr_len(string) -> int
Stringstr_lower(string) -> string
Stringstr_match(string, string) -> bool
Stringstr_repeat(string, int) -> string
Stringstr_replace(string, string, string) -> string
Stringstr_split(string, string) -> StrList
Stringstr_starts_with(string, string) -> bool
Stringstr_substr(string, int, int) -> string
Stringstr_to_float(string) -> float
Stringstr_to_int(string) -> int
Stringstr_trim(string) -> string
Stringstr_upper(string) -> string
Encodingstr_base64_encode(string) -> string
Encodingstr_base64_decode(string) -> string
Encodingstr_hex_encode(string) -> string
Encodingstr_hex_decode(string) -> string
Mathmath_abs(int) -> int; (float) -> float
Mathmath_ceil(int) -> int; (float) -> float
Mathmath_floor(int) -> int; (float) -> float
Mathmath_max(int, int) -> int; (float, float) -> float
Mathmath_min(int, int) -> int; (float, float) -> float
Mathmath_pow(int, int) -> int; (float, float) -> float
Mathmath_round(int) -> int; (float) -> float
Mathmath_sqrt(int) -> int; (float) -> float
Filefile_append(string, string) -> void
Filefile_exists(string) -> bool
Filefile_lines(string) -> StrList
Filefile_read(string) -> string
Filefile_write(string, string) -> void
Collection constructorsfloat_list() -> FloatList
Collection constructorsfloat_map() -> FloatMap
Collection constructorsfloat_pq() -> FloatPQ
Collection constructorsfloat_queue() -> FloatQueue
Collection constructorsfloat_stack() -> FloatStack
Collection constructorsint_list() -> IntList
Collection constructorsint_map() -> IntMap
Collection constructorsint_pq() -> IntPQ
Collection constructorsint_queue() -> IntQueue
Collection constructorsint_stack() -> IntStack
Collection constructorsstr_list() -> StrList
Collection constructorsstr_map() -> StrMap
Collection constructorsstr_pq() -> StrPQ
Collection constructorsstr_queue() -> StrQueue
Collection constructorsstr_stack() -> StrStack
JSON and templatesjson_parse(string) -> Json
JSON and templatestemplate_render(string, Json) -> string
Result sinklmcode_return_null() -> void
Result sinklmcode_return_put(string, bool) -> void; (string, float) -> void; (string, FloatList) -> void; (string, FloatMap) -> void; (string, int) -> void; (string, IntList) -> void; (string, IntMap) -> void; (string, Json) -> void; (string, StrList) -> void; (string, StrMap) -> void; (string, string) -> void
Result sinklmcode_return_put_null(string) -> void
Result sinklmcode_return_set(bool) -> void; (float) -> void; (FloatList) -> void; (FloatMap) -> void; (int) -> void; (IntList) -> void; (IntMap) -> void; (Json) -> void; (StrList) -> void; (StrMap) -> void; (string) -> void

Standard types and methods

TypeMethodSignature
FloatListadd(float) -> FloatList
FloatListat(int) -> float
FloatListclear() -> FloatList
FloatListcontains(float) -> bool
FloatListindex_of(float) -> int
FloatListlen() -> int
FloatListset(int, float) -> FloatList
FloatMaplen() -> int
FloatMaphas(string) -> bool
FloatMapget(string) -> float
FloatMapget_or(string, float) -> float
FloatMapset(string, float) -> FloatMap
FloatMapkey_at(int) -> string
FloatMapremove(string) -> bool
FloatMapclear() -> FloatMap
FloatMapkeys() -> StrList
FloatMapvalues() -> FloatList
FloatPQpush(float, float) -> FloatPQ
FloatPQpop() -> float
FloatPQpeek() -> float
FloatPQlen() -> int
FloatPQempty() -> bool
FloatPQclear() -> FloatPQ
FloatQueuepush(float) -> FloatQueue
FloatQueuepop() -> float
FloatQueuepeek() -> float
FloatQueuelen() -> int
FloatQueueempty() -> bool
FloatQueueclear() -> FloatQueue
FloatQueueat(int) -> float
FloatStackpush(float) -> FloatStack
FloatStackpop() -> float
FloatStackpeek() -> float
FloatStacklen() -> int
FloatStackempty() -> bool
FloatStackclear() -> FloatStack
FloatStackat(int) -> float
IntListadd(int) -> IntList
IntListat(int) -> int
IntListclear() -> IntList
IntListcontains(int) -> bool
IntListindex_of(int) -> int
IntListlen() -> int
IntListset(int, int) -> IntList
IntMaplen() -> int
IntMaphas(string) -> bool
IntMapget(string) -> int
IntMapget_or(string, int) -> int
IntMapset(string, int) -> IntMap
IntMapkey_at(int) -> string
IntMapremove(string) -> bool
IntMapclear() -> IntMap
IntMapkeys() -> StrList
IntMapvalues() -> IntList
IntPQpush(int, float) -> IntPQ
IntPQpop() -> int
IntPQpeek() -> int
IntPQlen() -> int
IntPQempty() -> bool
IntPQclear() -> IntPQ
IntQueuepush(int) -> IntQueue
IntQueuepop() -> int
IntQueuepeek() -> int
IntQueuelen() -> int
IntQueueempty() -> bool
IntQueueclear() -> IntQueue
IntQueueat(int) -> int
IntStackpush(int) -> IntStack
IntStackpop() -> int
IntStackpeek() -> int
IntStacklen() -> int
IntStackempty() -> bool
IntStackclear() -> IntStack
IntStackat(int) -> int
Jsonkind() -> string
Jsonlen() -> int
Jsonat(int) -> Json
Jsonget(string) -> Json
Jsonhas(string) -> bool
Jsonkeys() -> StrList
Jsonas_string() -> string
Jsonas_int() -> int
Jsonas_float() -> float
Jsonas_bool() -> bool
Jsonto_json() -> string
StrListadd(string) -> StrList
StrListat(int) -> string
StrListclear() -> StrList
StrListcontains(string) -> bool
StrListindex_of(string) -> int
StrListjoin(string) -> string
StrListlen() -> int
StrListset(int, string) -> StrList
StrMapclear() -> StrMap
StrMapget(string) -> string
StrMapget_or(string, string) -> string
StrMaphas(string) -> bool
StrMapkey_at(int) -> string
StrMaplen() -> int
StrMapremove(string) -> bool
StrMapset(string, string) -> StrMap
StrMapkeys() -> StrList
StrMapvalues() -> StrList
StrPQpush(string, float) -> StrPQ
StrPQpop() -> string
StrPQpeek() -> string
StrPQlen() -> int
StrPQempty() -> bool
StrPQclear() -> StrPQ
StrQueuepush(string) -> StrQueue
StrQueuepop() -> string
StrQueuepeek() -> string
StrQueuelen() -> int
StrQueueempty() -> bool
StrQueueclear() -> StrQueue
StrQueueat(int) -> string
StrStackpush(string) -> StrStack
StrStackpop() -> string
StrStackpeek() -> string
StrStacklen() -> int
StrStackempty() -> bool
StrStackclear() -> StrStack
StrStackat(int) -> string

Standard REST and CLI interfaces (current catalog, not yet in this host)

The current lmcode_std_v3 catalog in lmcode-cpp has 226 canonical signatures. The 20 signatures beyond the 206 that lmfinance vendors are the former lmcode_std_rest_v1 module: 5 functions and 15 RestExchange methods, together with 10 standard interfaces. lmfinance does not ship them yet; it picks them up when it syncs its pinned lmcode-cpp SDK and publishes a release. Until then a lmfinance program that calls rest_route or declares a RestGet handler does not compile against the lmfinance schema.

InterfaceSignatureRole
RestGet(RestExchange exchange) -> voidHandler for GET routes
RestPost(RestExchange exchange) -> voidHandler for POST routes
RestPut(RestExchange exchange) -> voidHandler for PUT routes
RestDelete(RestExchange exchange) -> voidHandler for DELETE routes
RestPatch(RestExchange exchange) -> voidHandler for PATCH routes
RestHead(RestExchange exchange) -> voidHandler for HEAD routes
RestOptions(RestExchange exchange) -> voidHandler for OPTIONS routes
RestHandler(RestExchange exchange) -> voidGeneric handler bound by rest_route to an annotation name
CliCommand(RestExchange exchange) -> voidHandler for a command dispatched by rest_cli
CliOption(RestExchange exchange) -> voidHandler for an option dispatched by rest_cli
FunctionSignatureBehavior
rest_config(string, string) -> voidStore a configuration key and value; the keys prefix and base_path set the route prefix and max_body_bytes sets the request body limit
rest_route(string, string, string) -> voidRegister method, path template and handler annotation; templates accept {param} and {rest...} or :param and :rest... placeholders
rest_serve() -> voidRequest serving after the program body; routes are frozen from this call on
rest_stop() -> voidStop serving
rest_cli(StrList) -> stringStateless CLI mode: dispatch an argument vector to options, commands and REST routes and return the response text
RestExchange methodSignatureBehavior
method() -> stringRequest method
path() -> stringRequest path
query(string) -> stringQuery parameter value, empty when absent
has_query(string) -> boolWhether a query parameter is present
param(string) -> stringRoute template parameter value, empty when absent
header(string) -> stringRequest header value; repeated headers are joined with a comma and a space
has_header(string) -> boolWhether a request header is present
body() -> stringRequest body bytes
status(int) -> voidSet the response status; values outside 200..599 are a host error
set_header(string, string) -> voidSet a response header; Content-Length, Connection and Transfer-Encoding are managed by the server
send(string) -> voidSet the response body
json(string) -> voidSet the response body and the Content-Type application/json
get(string) -> stringRead a shared state value, empty when absent
set(string, string) -> voidWrite a shared state value
increment(string) -> intIncrement a shared named counter and return it