lmfinance skill

Use lmfinance from an LMScript _lmcode_ block to price options, bonds, swaps, caps, floors and swaptions with QuantLib, compute Greeks and risk figures, and calibrate volatility models. Every command and output on this page was run with lmscript 0.2.482 and the lmfinance 0.1.4 release.

Purpose

lmfinance exposes QuantLib through seven context objects (market, instrument, model, pricing, risk, calibration, lmf). A program builds curves, instruments, models and engines by chained method calls, asks for prices and sensitivities as floats, checks them with assertions, and writes tables to text files or returns values to the calling script. Results are deterministic: the evaluation date defaults to 2024-01-02 and never comes from the system clock, and Monte Carlo needs an explicit seed.

When to use it

Do not use it for live market data, trading, calendars other than the built-in conventions, multi-curve discounting, callable or floating-rate bonds, or short-rate models: none of these exist in the host.

Install

npm install -g @lmctl-ai/lmctl

That installs lmscript and lmctl. The host itself needs no manual installation: a block that declares cli="lmfinance" install="github:lmctl-ai/lmfinance@latest" makes lmscript use lmfinance from PATH or download the release binary for the platform into its tool cache on the first real run. Linux binaries need dynamic glibc 2.35 or newer. If an unrelated program named lmfinance is first on PATH, remove it or put the real host first.

lmscript --check needs the host schema; it is cached by the first real run of a block with the install attribute. On a fresh machine run the script once before relying on --check.

Commands

CommandUse
lmscript FILE.lmsCompile the _lmcode_ blocks and run the script; run_lmcode starts the host
lmscript --check FILE.lmsCompile and type-check the blocks against the host schema without running
lmscript --dry-run FILE.lmsPrint the plan; the host run is simulated and run_lmcode returns ok true, result null, dry true
lmctl URLRun a published example script from its raw URL in the current directory
lmfinance --versionPrint the host version
lmfinance --lmcode-schema --jsonPrint the embedded schema
lmfinance --lmcode-signaturesPrint every callable signature, one per line
lmfinance --noticesPrint third-party license notices
lmfinance [--dry-run] --lmcode FILE [FILE ...]Host protocol used by run_lmcode for compiled programs; not meant to be typed by hand

Inputs and outputs

Safety rules

Worked examples

Price an option and return the numbers

# bs.lms
prog = _lmcode_ cli="lmfinance" install="github:lmctl-ai/lmfinance@latest";
let m = model.black_scholes(100.0, 0.05, 0.0, 0.2);
let call = instrument.european_call(100.0, 1.0);
let res = pricing.price(call, m, pricing.analytic());
lmf.print("price " + str(res.price()) + " delta " + str(res.delta()));
lmf.assert_close(res.price(), 10.4506, 0.00005);
lmcode_return_put("price", res.price());
lmcode_return_put("delta", res.delta());
end _lmcode_
r = run_lmcode(prog);
println(json_stringify(r));
require(r.ok, "pricing run failed");
lmscript bs.lms
price 10.4505835721856 delta 0.636830651175619
{"ok":true,"result":{"price":10.450583572185577,"delta":0.6368306511756194}}

Bootstrap a curve and price a bond and a swap

This is examples/bond_curve.lms from the repository. The curve is built from deposit and swap quotes, reprices its own inputs, and is written to build/examples/curve.csv.

mkdir("build/examples");
p = _lmcode_ cli="lmfinance" install="github:lmctl-ai/lmfinance@latest";
market.set_date("2024-01-02");
let curve = market.bootstrap_curve()
  .deposit("3M", 0.0300).deposit("6M", 0.0310)
  .swap("2Y", 0.0350).swap("5Y", 0.0400).swap("10Y", 0.0420).swap("30Y", 0.0410).build();
curve.save_csv("build/examples/curve.csv", 30.0, 120);
lmf.print("5y zero rate " + str(curve.zero(5.0)) + ", discount factor " + str(curve.discount(5.0)));
lmf.assert_close(pricing.swap_par_rate(instrument.swap(1.0, 0.04, 5.0), curve), 0.0400, 0.0000001);
lmf.assert_close(pricing.swap_par_rate(instrument.swap(1.0, 0.04, 30.0), curve), 0.0410, 0.0000001);
let bond = instrument.bond(100.0, 0.045, 7.0, 2);
let clean = pricing.bond_clean_price(bond, curve);
let ytm = pricing.bond_yield(bond, clean);
lmf.print("bond price " + str(clean) + ", yield " + str(ytm) + ", modified duration " + str(pricing.bond_duration(bond, ytm)));
lmf.print("DV01 per 100 face: " + str(risk.bond_dv01(bond, curve)));
lmf.assert_close(pricing.bond_price_from_yield(bond, ytm), clean, 0.00001);
lmf.check(clean > 100.0, "coupon 4.5% above the 7y rate prices over par");
let swap = instrument.swap(10000000.0, 0.04, 5.0);
lmf.assert_close(pricing.swap_npv(swap, curve), 0.0, 0.01);
lmf.print("swap DV01 on 10mm: " + str(risk.swap_dv01(swap, curve)));
end _lmcode_
r = run_lmcode(p);
assert(r.ok);
lmscript bond_curve.lms
5y zero rate 0.0393682606026068, discount factor 0.82132096413317
bond price 102.607265385808, yield 0.0406823456712827, modified duration 5.97449256081373
DV01 per 100 face: 0.0625244693126277
swap DV01 on 10mm: 4631.7195172942

Rate and equity risk of a small book

This is examples/portfolio_risk.lms: DV01 of a bond and a receiver swap on a zero curve, then 10-day 99% normal value at risk and expected shortfall.

p = _lmcode_ cli="lmfinance" install="github:lmctl-ai/lmfinance@latest";
market.set_date("2024-01-02");
let curve = market.zero_curve().zero(1.0, 0.040).zero(5.0, 0.042).zero(10.0, 0.044).build();
let bond = instrument.bond(1000000.0, 0.043, 8.0, 2);
let swap = instrument.swap(5000000.0, 0.042, 5.0).receiver();
let bond_dv01 = risk.bond_dv01(bond, curve);
let swap_dv01 = risk.swap_dv01(swap, curve);
lmf.print("bond DV01 " + str(bond_dv01) + ", receiver swap DV01 " + str(swap_dv01));
lmf.check(bond_dv01 > 0.0, "a long bond loses when rates rise");
lmf.check(swap_dv01 < 0.0, "a receiver swap loses when rates rise");
let m = model.black_scholes(100.0, 0.042, 0.0, 0.25);
let call = instrument.european_call(105.0, 0.5);
let value = 10000.0 * pricing.price(call, m, pricing.analytic()).price();
let var99 = risk.var_normal(value + 1000000.0, 0.15, 0.99, 10.0);
let es99 = risk.es_normal(value + 1000000.0, 0.15, 0.99, 10.0);
lmf.print("10-day 99% VaR " + str(var99) + ", ES " + str(es99));
lmf.check(es99 > var99, "expected shortfall exceeds VaR");
end _lmcode_
r = run_lmcode(p);
assert(r.ok);
lmscript portfolio_risk.lms
bond DV01 682.710483783041, receiver swap DV01 -2298.77368069818
10-day 99% VaR 73567.8336761393, ES 84284.0567715592

Errors and exit codes

WhereCodeMeaningFix
lmfinance host0SuccessNone
lmfinance host2Bad flags, missing program file argument, invalid LMFINANCE_MAX_MEMORY_MB, or --dry-run contradicting real-mode invocation metadata; usage text on stderr and a cli failure frameLet run_lmcode call the host; set the variable to a positive whole number of MiB
lmfinance host3Program load or run error: unreadable or mismatched bytecode, failed assert_close or check, QuantLib error, invalid argument, memory budget exceededRead message, line and column in the run_lmcode result
lmfinance host4Application failure (APP_FAIL) or failure writing outputCheck that standard output is writable
lmscript2Compile error in a block, for example a wrong argument type or unknown method, or the host schema is not availableFix the reported line and column; run once with install to cache the schema
lmscript1The outer script failed, for example require(r.ok, ...) after a failed host runInspect the printed run_lmcode result

A run-time failure is reported in the value returned by run_lmcode, and the host message is also echoed. This block asks a binomial result for vega, which that engine does not provide:

prog = _lmcode_ cli="lmfinance" install="github:lmctl-ai/lmfinance@latest";
let m = model.black_scholes(100.0, 0.05, 0.0, 0.2);
let put = instrument.american_put(100.0, 1.0);
let res = pricing.price(put, m, pricing.binomial(500));
lmf.print("vega " + str(res.vega()));
end _lmcode_
r = run_lmcode(prog);
println(json_stringify(r));
lmscript fail.lms
dsl line 5:29: Result.vega: this engine does not provide it; use the risk functions (bumped Greeks)
{"ok":false,"phase":"run","code":"RUN_HOST","message":"dsl line 5:29: Result.vega: this engine does not provide it; use the risk functions (bumped Greeks)","line":5,"column":29}

A failed assertion has the same shape, with a message such as: dsl line 2:5: assert_close failed: 1 vs 2 (tolerance 0.001). A compile error is reported by lmscript before the host runs; passing the integer 100 where a float is required gives:

lmscript --check bad.lms
error:bad.lms:2:29: _lmcode_: method ModelApi.black_scholes expects float for argument 1; found int

The file path in that message was shortened from an absolute path.

How to verify

  1. Run lmscript --check on the script: exit 0 means every block type-checks against the lmfinance schema.
  2. Run the script and require r.ok. Print json_stringify(r) while developing.
  3. Put known answers in the block with lmf.assert_close and lmf.check. Useful anchors from the repository tests: the Black-Scholes call with spot 100, strike 100, rate 5%, volatility 20% and one year is 10.4506 and the put 5.5735; the American put on the same market converges to 6.0903; a par bond prices at 100.
  4. Cross-check engines against each other: a binomial or finite-difference price should approach the analytic one, and a Monte Carlo price should lie within about four standard errors (Result.stderr).
  5. Check written files exist and have the expected number of rows.
  6. Confirm the host version and surface when a result looks wrong:
lmfinance --version
lmfinance 0.1.4

When lmscript downloaded the host, the binary is in the lmscript tool cache rather than on PATH; lmf.version() inside a block returns the same string.