### Run European option example in Go Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/getting-started.md Command to run the Go example from a source checkout. Requires following the native build and runtime setup. ```sh cd sdk/go go run ./examples/european_option ``` -------------------------------- ### Install Go SDK with go get Source: https://github.com/benbenbang/libitofin/blob/main/README.md Adds the Go SDK module at version v0.24.0. Requires Go 1.27.1, cgo, a C compiler, and the matching native release package; follow the native installation guide first. Use -tags itofin_external for builds, runs, tests, and vet outside this checkout. ```sh go get github.com/benbenbang/libitofin/sdk/go@v0.24.0 ``` -------------------------------- ### Run Go examples from sdk/go Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/go.md Runs the European option and portfolio examples from the sdk/go directory. The European option example returns NPV 2.1333684449. ```sh cd sdk/go go run ./examples/european_option go run ./examples/portfolio ``` -------------------------------- ### Run European option example in Rust Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/getting-started.md Command to run the Rust example from a source checkout. ```bash cargo run --example european_option ``` -------------------------------- ### Run European option example in Python Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/getting-started.md Command to run the Python example from a source checkout. ```bash python example/python/european_option.py ``` -------------------------------- ### Price European option in Go Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/getting-started.md Runnable Go example that prices the same call as the Python example. Requires following the native build and runtime setup for a source checkout, or Go installation for the published module. ```go --8<-- "sdk/go/examples/european_option/main.go" ``` -------------------------------- ### Go example of weighted statistics and risk measures Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/statistics.md Demonstrates using the itofin Go SDK to compute value at risk, expected shortfall, shortfall, and top percentile with weighted observations. Use nil weights for unit weights. Errors are handled with panic in this example. ```Go import itofin "github.com/benbenbang/libitofin/sdk/go" observations := []float64{-5, -2, 1, 2} weights := []float64{1, 10, 1, 8} var90, err := itofin.StatisticsValueAtRisk(observations, weights, 0.9) if err != nil { panic(err) } es90, err := itofin.StatisticsExpectedShortfall(observations, weights, 0.9) if err != nil { panic(err) } _, _ = var90, es90 missed, err := itofin.StatisticsShortfall(observations, weights, 0) if err != nil { panic(err) } upper, err := itofin.StatisticsTopPercentile(observations, weights, 0.5) if err != nil { panic(err) } _, _ = missed, upper ``` -------------------------------- ### Build native package with package_go_native.sh Source: https://github.com/benbenbang/libitofin/blob/main/docs/go-distribution.md Installs cbindgen 0.29.2 and runs the packaging script to build a native package for the current host. Requires a source checkout with the pinned Rust toolchain and Python 3 installed. Produces itofin-native-VERSION-PLATFORM.tar.gz and its .sha256 checksum. ```sh cargo install cbindgen --version 0.29.2 --locked bash scripts/package_go_native.sh /tmp/itofin-native ``` -------------------------------- ### Build and test Go bindings Source: https://github.com/benbenbang/libitofin/blob/main/sdk/go/README.md Builds the native library, sets the library path, and runs Go tests and examples. Requires Go 1.27.1, cgo, a C compiler, and the native library. On macOS, use DYLD_LIBRARY_PATH instead of LD_LIBRARY_PATH. ```sh cargo build -p libitofin-ffi --release export LD_LIBRARY_PATH="$PWD/target/release${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" # On macOS, use DYLD_LIBRARY_PATH instead. cd sdk/go go test ./... go run ./examples/european_option go run ./examples/portfolio ``` -------------------------------- ### Install itofin with pip Source: https://github.com/benbenbang/libitofin/blob/main/README.md Installs the itofin Python package. Requires Python 3.10 or newer. ```sh pip install itofin ``` -------------------------------- ### Go: OHLCPointVolatilityConstantFraction example Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/chart.md Computes pointwise OHLC volatility using the constant-fraction helper in Go. The example calls the function with sample data and a year fraction, panics on error, and accesses the Parkinson sigma values. ```go import itofin "github.com/benbenbang/libitofin/sdk/go" estimates, err := itofin.OHLCPointVolatilityConstantFraction( []float64{100}, []float64{110}, []float64{90}, []float64{105}, 1.0/252, ) if err != nil { panic(err) } _ = estimates.ParkinsonSigma.NullableValues() ``` -------------------------------- ### minimize Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/api/optimize.md Documentation for the `minimize` function from the `itofin.optimize` module, covering supported methods, options, and usage examples. ```APIDOC ## minimize ### Description SciPy-style `minimize` over the finance-independent `itofin-optimize` crate. Python, Go, C and Rust expose Nelder-Mead, BFGS, L-BFGS-B, and SLSQP. The objective runs outside any bootstrap callback, so it may set a `SimpleQuote` and reprice an instrument. An exception raised by `fun`, `jac`, a constraint callback, or `callback` is re-raised as the same object; `StopIteration` from `callback` stops the run with `Status.Cancelled`. ### Method Function call ### Endpoint `itofin.optimize.minimize` ### Parameters - **fun** (callable) - Required - Objective function to minimize. - **x0** (array-like) - Required - Initial guess. - **method** (str) - Optional - Optimization method: `Nelder-Mead`, `BFGS`, `L-BFGS-B`, or `SLSQP`. - **jac** (callable) - Optional - Gradient function. Supported for BFGS, L-BFGS-B, and SLSQP. Not supported for Nelder-Mead. - **bounds** (list of tuples) - Optional - Bounds for L-BFGS-B and SLSQP. Each tuple is `(lower, upper)`; `None` opens a side. Rejected for Nelder-Mead and BFGS. - **constraints** (list of dicts) - Optional - Only for SLSQP. Each dict has `type` (`'eq'` or `'ineq'`), `fun`, and optional `jac`. - **options** (dict) - Optional - Method-specific options. ### Options - **Nelder-Mead**: `maxiter`, `maxfev`, `xatol`, `fatol`, `adaptive` - **BFGS**: `maxiter`, `gtol`, `eps` - **L-BFGS-B**: `maxiter`, `maxfev`, `maxcor`, `ftol`, `gtol`, `eps` - **SLSQP**: `maxiter`, `maxfev`, `ftol` ### Request Example ```python from itofin.optimize import minimize result = minimize(lambda x: (x[0] - 3.0) ** 2, [0.0], options={"xatol": 1e-8}) print(result.x, result.status, result.message) ``` ### Response #### Success Response - **x** (array) - The solution array. - **status** (Status) - The optimization status (integer values match C `ItofinOptimizeStatus` and Go `OptimizeStatus`). - **message** (str) - A message describing the outcome. #### Response Example ```python result.x, result.status, result.message ``` ### Error Handling - Unknown method, invalid numeric input, or unsupported Nelder-Mead option raises `ItofinError`. - Unsupported BFGS options, `jac` with Nelder-Mead, and bounds on Nelder-Mead or BFGS raise `ValueError`. - L-BFGS-B and SLSQP reject an incorrect number of bound pairs before evaluating the objective. - Only SLSQP accepts `constraints`; unsupported options and malformed constraint descriptors are rejected before the objective runs. - Callback output dimensions are checked on every evaluation. - `Status.Infeasible` (integer 8) means the constraints could not be satisfied. ``` -------------------------------- ### Set runtime library path for Linux Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/go.md Sets LD_LIBRARY_PATH to the release build directory so the Go examples can find the native library. Use this on Linux. ```sh export LD_LIBRARY_PATH="$PWD/target/release${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" ``` -------------------------------- ### Build and query a BlackVarianceSurface Source: https://github.com/benbenbang/libitofin/blob/main/wiki/python.md Build a Black volatility surface (strike x expiry) and query it. The example prints 0.18 for a 1-year, 100.0 strike query. ```python from itofin.termstructures import BlackVarianceSurface from itofin.time import Date, DayCounter ref = Date(15, 6, 2026) vols = BlackVarianceSurface( ref, [ref + 365, ref + 730], # expiries [90.0, 100.0, 110.0], # strikes [[0.20, 0.25], # one row per strike, [0.18, 0.22], # one column per expiry [0.16, 0.20]], DayCounter.actual365_fixed(), ) print(f"{vols.black_vol(1.0, 100.0):.2f}") # 0.18 ``` -------------------------------- ### Python: ohlc_point_volatility_constant_fraction example Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/chart.md Computes pointwise OHLC volatility using the constant-fraction helper in Python. The example asserts that the first valid index is 0 and checks the Parkinson sigma value against a known result. ```python from itofin import chart estimates = chart.ohlc_point_volatility_constant_fraction( open=[100.0], high=[110.0], low=[90.0], close=[105.0], year_fraction=1 / 252, ) assert estimates.parkinson_sigma.first_valid == 0 assert abs(estimates.parkinson_sigma.values[0] - 1.9131168640323526) < 1e-12 ``` -------------------------------- ### Price European option in Rust Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/getting-started.md Runnable Rust example that illustrates the same pricing workflow with a different market and maturity. ```rust --8<-- "crates/libitofin/examples/european_option.rs" ``` -------------------------------- ### Build and run seasonality_consistency driver and Rust test Source: https://github.com/benbenbang/libitofin/blob/main/crates/libitofin/tests/fixtures/README.md Build and run the C++ driver against the CSV, then run the Rust integration test. Requires QuantLib built under QuantLib/build; add the Boost include directory if it is outside the compiler's default search path (for example, -I /opt/homebrew/include on Apple Silicon Homebrew). The driver exits nonzero for any outcome differing from the CSV. ```sh c++ -std=c++17 -I QuantLib/build -I QuantLib \ crates/libitofin/tests/fixtures/seasonality_consistency.cpp \ -L QuantLib/build/ql -lQuantLib -Wl,-rpath,"$PWD/QuantLib/build/ql" \ -o /tmp/seasonality-consistency /tmp/seasonality-consistency crates/libitofin/tests/fixtures/seasonality_consistency.csv cargo test -p libitofin --test seasonality_consistency ``` -------------------------------- ### Install libitofin with cargo add Source: https://github.com/benbenbang/libitofin/blob/main/README.md Adds the libitofin crate as a dependency in a Rust project. Use this command in a Rust project directory to install the library. ```sh cargo add libitofin ``` -------------------------------- ### Compute local and constant volatility with constant fraction (Go) Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/chart.md Go example of `itofin.SimpleLocalVolatilityConstantFraction` and `itofin.ConstantVolatility`. The local estimator uses absolute log returns between consecutive positive closes divided by the square root of the year fraction; the first bar is warmup. The constant estimator uses the previous `window` valid volatility values, excluding the current value, following QuantLib's formula. Output retains alignment and warmup slots. ```go import itofin "github.com/benbenbang/libitofin/sdk/go" close := []float64{100, 110, 99} local, err := itofin.SimpleLocalVolatilityConstantFraction(close, 1.0/252) if err != nil { panic(err) } constant, err := itofin.ConstantVolatility(local, 1) if err != nil { panic(err) } _ = constant.NullableValues() ``` -------------------------------- ### Build native library with cargo build --locked Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/go.md Builds the native FFI library from the repository root using the pinned Rust toolchain. Required before running the Go examples. ```sh cargo build --locked -p libitofin-ffi --release ``` -------------------------------- ### Go: OHLCOvernightVolatilityConstantFraction example Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/chart.md Computes overnight volatility estimates in Go, returning an error if invalid. Accesses the GarmanKlassSigma1 nullable values. ```go import itofin "github.com/benbenbang/libitofin/sdk/go" estimates, err := itofin.OHLCOvernightVolatilityConstantFraction( []float64{100, 110}, []float64{100, 120}, []float64{100, 105}, []float64{100, 115}, 1.0/252, 0.25, ) if err != nil { panic(err) } _ = estimates.GarmanKlassSigma1.NullableValues() ``` -------------------------------- ### Set runtime library path for macOS Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/go.md Sets DYLD_LIBRARY_PATH to the release build directory so the Go examples can find the native library. Use this on macOS. ```sh export DYLD_LIBRARY_PATH="$PWD/target/release${DYLD_LIBRARY_PATH:+:$DYLD_LIBRARY_PATH}" ``` -------------------------------- ### Python: ohlc_overnight_volatility_constant_fraction example Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/chart.md Computes overnight volatility estimates with a constant year fraction and overnight fraction. Asserts the first valid index is 1 and checks the Sigma1 value at index 1. ```python from itofin import chart estimates = chart.ohlc_overnight_volatility_constant_fraction( open=[100.0, 110.0], high=[100.0, 120.0], low=[100.0, 105.0], close=[100.0, 115.0], year_fraction=1 / 252, overnight_fraction=0.25, ) assert estimates.garman_klass_sigma1.first_valid == 1 assert abs(estimates.garman_klass_sigma1.values[1] - 2.2159224836472786) < 1e-12 ``` -------------------------------- ### Python: chart.sma and chart.volume_bars usage Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/chart.md Python example showing how to compute a simple moving average with `chart.sma` and volume bars with `chart.volume_bars`. The SMA result has `first_valid` index 2 and `to_list()` returns `None` for warmup bars. Volume direction is `1` for up and `-1` for down. ```python from itofin import chart close = [1.0, 2.0, 3.0, 4.0] average = chart.sma(close, 3) assert average.first_valid == 2 assert average.to_list() == [None, None, 2.0, 3.0] assert average.values.tolist() == [0.0, 0.0, 2.0, 3.0] bars = chart.volume_bars( open=[1.0, 2.0], high=[3.0, 3.0], low=[0.0, 0.0], close=[2.0, 1.0], volume=[10.0, 11.0], ) assert bars.direction.tolist() == [1, -1] ``` -------------------------------- ### Go: itofin.SMA and itofin.ChartVolumeBars usage Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/chart.md Go example showing how to compute a simple moving average with `itofin.SMA` and volume bars with `itofin.ChartVolumeBars`. The SMA result has `FirstValid` equal to 2 and `NullableValues()` returns nil for warmup bars. Volume direction is `[]int8{1, -1}`. ```go import itofin "github.com/benbenbang/libitofin/sdk/go" average, err := itofin.SMA([]float64{1, 2, 3, 4}, 3) if err != nil { panic(err) } // average.FirstValid == 2 // average.NullableValues() has nil in the first two slots. bars, err := itofin.ChartVolumeBars( []float64{1, 2}, []float64{3, 3}, []float64{0, 0}, []float64{2, 1}, []float64{10, 11}, ) if err != nil { panic(err) } // bars.Direction == []int8{1, -1} ``` -------------------------------- ### Validate and order OHLC bars with IntervalPrices (Go) Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/chart.md Go example of `itofin.IntervalPrices` that validates OHLC bars and returns them in date order. Duplicate dates keep the last input bar; prices must be finite with open and close inside the low-to-high range; negative prices are valid. The five input arrays must have equal lengths, and the output leaves input arrays unchanged. ```go import itofin "github.com/benbenbang/libitofin/sdk/go" // dates is a []itofin.Date in input order. bars, err := itofin.IntervalPrices(dates, []float64{11, 10}, []float64{12, 11}, []float64{9, 8}, []float64{10, 9}) if err != nil { panic(err) } // bars[0] is the earliest date. ``` -------------------------------- ### Simulate Heston paths with itofin.simulate_heston and Go SimulateHeston Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/simulation.md Simulate Heston spot and variance paths with the default qem scheme in Python and Go. The Python example shows full paths (shape [100, 13, 2]) and terminal-only output, asserting terminal equals the last time slice. The Go example uses HestonConfig with Scheme: itofin.HestonQEM and prints the returned Paths, Times, and Assets. Both require positive spot, nonnegative variance, positive kappa/theta/sigma, rho in (-1,1), nonnegative horizon, and positive steps/paths/seed. ```python paths = itofin.simulate_heston( spot=100.0, variance=0.04, risk_free_rate=0.05, dividend_yield=0.02, kappa=1.2, theta=0.06, sigma=0.3, rho=-0.5, horizon=1.0, steps=12, paths=100, seed=42, scheme="qem", ) assert paths.shape == (100, 13, 2) assert paths[0, 0].tolist() == [100.0, 0.04] terminal = itofin.simulate_heston( spot=100.0, variance=0.04, risk_free_rate=0.05, dividend_yield=0.02, kappa=1.2, theta=0.06, sigma=0.3, rho=-0.5, horizon=1.0, steps=12, paths=100, seed=42, terminal_only=True, ) assert (terminal == paths[:, -1, :]).all() ``` ```go paths, err := itofin.SimulateHeston(itofin.HestonConfig{ Spot: 100, Variance: 0.04, RiskFreeRate: 0.05, DividendYield: 0.02, Kappa: 1.2, Theta: 0.06, Sigma: 0.3, Rho: -0.5, Horizon: 1, Steps: 12, Paths: 100, Seed: 42, Scheme: itofin.HestonQEM, }) if err != nil { return err } fmt.Println(paths.Paths, paths.Times, paths.Assets) ``` -------------------------------- ### Price a European swaption with the Jamshidian engine Source: https://github.com/benbenbang/libitofin/blob/main/crates/itofin-py/README.md Constructs a payer swaption with physical settlement and sets a Hull-White model with the Jamshidian engine. The example prints the net present value (NPV) of the swaption. The output shows the computed NPV. ```python from itofin import Settings from itofin.indexes import Euribor from itofin.instruments import ( EuropeanExercise, SettlementMethod, SettlementType, Swaption, SwapType, VanillaSwap, ) from itofin.models import HullWhite from itofin.termstructures import FlatForward from itofin.time import BusinessDayConvention, Calendar, Date, DayCounter, Frequency, Schedule s = Settings() s.set_evaluation_date(Date(15, 1, 2026)) curve = FlatForward(Date(15, 1, 2026), 0.03, DayCounter.actual365_fixed()) fixed = Schedule( Date(15, 1, 2028), Date(15, 1, 2033), Frequency.Annual, Calendar.target(), BusinessDayConvention.Unadjusted, ) floating = Schedule( Date(15, 1, 2028), Date(15, 1, 2033), Frequency.Semiannual, Calendar.target(), BusinessDayConvention.Unadjusted, ) index = Euribor.six_months(curve, s) swap = VanillaSwap( SwapType.Payer, 100.0, fixed, 0.03, DayCounter.thirty360_bond_basis(), floating, index, 0.0, DayCounter.actual360(), s, ) swaption = Swaption( swap, EuropeanExercise(Date(15, 1, 2027)), SettlementType.Physical, SettlementMethod.PhysicalOTC, s, ) swaption.set_jamshidian_engine(HullWhite(curve, 0.05, 0.01)) print(f"payer swaption NPV {swaption.npv():.10f}") ``` ```text payer swaption NPV 1.5666103956 ``` -------------------------------- ### Price European option in Python Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/getting-started.md Runnable Python example that builds a Black-Scholes market, wraps it in a vanilla option, attaches the analytic engine, and reads the value and greeks. Expected NPV for the specified call is 2.1333684449. ```python --8<-- "example/python/european_option.py" ``` -------------------------------- ### Query a SwaptionVolatilityMatrix Source: https://github.com/benbenbang/libitofin/blob/main/wiki/python.md Query an ATM swaption volatility matrix. The example prints 0.1800 at a node and 0.1775 via bilinear interpolation. ```python from itofin import Settings from itofin.termstructures import SwaptionVolatilityMatrix, VolatilityType from itofin.time import Date, Period, Calendar, DayCounter, BusinessDayConvention s = Settings() s.set_evaluation_date(Date(15, 6, 2026)) opt = [Period(1, "Years"), Period(5, "Years")] # option tenors (rows) swp = [Period(1, "Years"), Period(5, "Years")] # swap tenors (columns) vols = [[0.20, 0.18], [0.17, 0.16]] svol = SwaptionVolatilityMatrix( Date(15, 6, 2026), Calendar.target(), BusinessDayConvention.Following, opt, swp, vols, DayCounter.actual365_fixed(), VolatilityType.ShiftedLognormal, ) print(f"{svol.volatility(Period(1, 'Years'), Period(5, 'Years'), 0.03):.4f}") # 0.1800 (node) print(f"{svol.volatility(Period(3, 'Years'), Period(3, 'Years'), 0.03):.4f}") # 0.1775 (bilinear) ``` -------------------------------- ### Compute local and constant volatility with constant fraction (Python) Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/chart.md Python example of `chart.simple_local_volatility_constant_fraction` and `chart.constant_volatility`. The local estimator uses absolute log returns between consecutive positive closes divided by the square root of the year fraction; the first bar is warmup. The constant estimator uses the previous `window` valid volatility values, excluding the current value, following QuantLib's formula. Output retains alignment and warmup slots. ```python from itofin import chart close = [100.0, 110.0, 99.0] local = chart.simple_local_volatility_constant_fraction(close, 1 / 252) constant = chart.constant_volatility(local, window=1) assert local.to_list()[0] is None assert constant.first_valid == 2 assert abs(constant.to_list()[2] - 1.0698541148988145) < 1e-12 ``` -------------------------------- ### Import libitofin Date type Source: https://github.com/benbenbang/libitofin/blob/main/crates/libitofin/README.md Shows the import path for the libitofin crate, using the time module's Date type. Use this to start using the library. ```rust use libitofin::time::Date; ``` -------------------------------- ### Simulate GBM paths with itofin.simulate_gbm Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/simulation.md Generates geometric Brownian motion paths with a fixed seed, demonstrating both full paths and terminal-only output. The example asserts the output shape and that terminal values match the last time step of the full paths. ```python import itofin paths = itofin.simulate_gbm( initial=[100.0, 70.0], drift=[0.05, -0.02], volatility=[0.2, 0.3], correlation=[1.0, 0.5, 0.5, 1.0], horizon=1.0, steps=12, paths=100, seed=42, ) assert paths.shape == (100, 13, 2) assert paths[0, 0].tolist() == [100.0, 70.0] terminal = itofin.simulate_gbm( initial=[100.0, 70.0], drift=[0.05, -0.02], volatility=[0.2, 0.3], correlation=[1.0, 0.5, 0.5, 1.0], horizon=1.0, steps=12, paths=100, seed=42, terminal_only=True, ) assert terminal.shape == (100, 2) assert (terminal == paths[:, -1, :]).all() ``` -------------------------------- ### Run Python typing checks Source: https://github.com/benbenbang/libitofin/blob/main/crates/itofin-py/TYPING.md Run from the repository root in a Python 3.10+ virtual environment. Installs pinned dependencies, runs all binding tests, and executes the typing gate. CI and prek run the same checks. ```sh python -m pip install -r crates/itofin-py/typing-requirements.txt python -m unittest discover -s crates/itofin-py/scripts -p 'test_*.py' python crates/itofin-py/scripts/check_typing.py ``` -------------------------------- ### Python example of weighted statistics and risk measures Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/statistics.md Demonstrates using the itofin statistics module in Python to compute value at risk, expected shortfall, mean, shortfall, and top percentile with weighted observations. Observations are signed; negative values are losses. Weights are optional; omit for unit weights. ```Python from itofin import statistics observations = [-5.0, -2.0, 1.0, 2.0] weights = [1.0, 10.0, 1.0, 8.0] assert statistics.value_at_risk(observations, 0.9, weights=weights) == 2.0 assert statistics.expected_shortfall(observations, 0.9, weights=weights) == 5.0 assert statistics.mean([1.0, 3.0], weights=[1.0, 3.0]) == 2.5 assert statistics.shortfall(observations, 0.0, weights=weights) == 11 / 20 assert statistics.top_percentile(observations, 0.5, weights=weights) == -2.0 ``` -------------------------------- ### Develop the itofin docs site with uv and MkDocs Source: https://github.com/benbenbang/libitofin/blob/main/docs/README.md Commands to set up the docs environment and run the MkDocs development server or a strict build. Run from the docs directory after syncing dependencies with uv. ```bash cd docs uv sync uv run mkdocs serve # live preview at http://127.0.0.1:8000 uv run mkdocs build --strict ``` -------------------------------- ### Set up external Go module with native assets Source: https://github.com/benbenbang/libitofin/blob/main/docs/go-distribution.md Download and verify the native archive for the selected platform, set cgo environment variables, and build with the itofin_external tag. The Windows variant uses cygpath and keeps the DLL on PATH. The final commands fetch the Go module and run tests/builds with the external tag. ```sh version=VERSION platform=darwin-arm64 gh release download "v$version" --repo benbenbang/libitofin \ --pattern "itofin-native-$version-$platform.tar.gz*" shasum -a 256 -c "itofin-native-$version-$platform.tar.gz.sha256" tar -xzf "itofin-native-$version-$platform.tar.gz" export ITOFIN_NATIVE="$PWD/itofin-native-$version-$platform" (cd "$ITOFIN_NATIVE" && shasum -a 256 -c SHA256SUMS) export CGO_ENABLED=1 export CGO_CFLAGS="\"-I$ITOFIN_NATIVE/include\"" export CGO_LDFLAGS="\"-L$ITOFIN_NATIVE/lib\" -litofin_ffi \"-Wl,-rpath,$ITOFIN_NATIVE/lib\"" ``` ```sh export ITOFIN_NATIVE="$PWD/itofin-native-$version-windows-amd64" native_windows=$(cygpath -m "$ITOFIN_NATIVE") export CC=gcc CGO_ENABLED=1 export CGO_CFLAGS="\"-I$native_windows/include\"" export CGO_LDFLAGS="\"-L$native_windows/lib\" -litofin_ffi" export PATH="$ITOFIN_NATIVE/lib:$PATH" ``` ```sh go get "github.com/benbenbang/libitofin/sdk/go@v$version" go test -tags itofin_external ./... go build -tags itofin_external ./... ``` -------------------------------- ### Download and configure native package for Go SDK Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/go.md Download, verify, and extract the native package, then set environment variables and fetch the Go module. Requires the GitHub CLI and the version/platform variables set as shown. ```sh gh release download "v$version" --repo benbenbang/libitofin \ --pattern "itofin-native-$version-$platform.tar.gz*" shasum -a 256 -c "itofin-native-$version-$platform.tar.gz.sha256" tar -xzf "itofin-native-$version-$platform.tar.gz" export ITOFIN_NATIVE="$PWD/itofin-native-$version-$platform" (cd "$ITOFIN_NATIVE" && shasum -a 256 -c SHA256SUMS) export CGO_ENABLED=1 export CGO_CFLAGS="\"-I$ITOFIN_NATIVE/include\"" export CGO_LDFLAGS="\"-L$ITOFIN_NATIVE/lib\" -litofin_ffi \"-Wl,-rpath,$ITOFIN_NATIVE/lib\"" go get "github.com/benbenbang/libitofin/sdk/go@v$version" ``` -------------------------------- ### Create session and print native version Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/go.md Minimal Go program that creates a session, prints the native version, and closes the session. Save as `main.go`. ```go package main import ( "fmt" "log" itofin "github.com/benbenbang/libitofin/sdk/go" ) func main() { session, err := itofin.NewSession() if err != nil { log.Fatal(err) } defer session.Close() fmt.Println("Native version:", itofin.Version()) } ``` -------------------------------- ### Build and run the global bootstrap oracle Source: https://github.com/benbenbang/libitofin/blob/main/crates/itofin-py/tests/fixtures/global_bootstrap/README.md Compiles oracle.cpp with C++17 and links against QuantLib, then runs it to produce oracle.csv. Requires the QL and BOOST_INCLUDE environment variables to be set. ```sh c++ -std=c++17 -I "$QL/build" -I "$QL" -I "$BOOST_INCLUDE" \ oracle.cpp -L "$QL/build/ql" -lQuantLib \ -Wl,-rpath,"$QL/build/ql" -o /tmp/global-bootstrap-oracle /tmp/global-bootstrap-oracle > oracle.csv ``` -------------------------------- ### Python: Create Merton76Process and JumpDiffusionEngine Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/jump-diffusion.md Demonstrates constructing a Merton76Process with quotes and term structures, attaching a JumpDiffusionEngine to a VanillaOption, and pricing the option. ```APIDOC ## Python: Merton76Process and JumpDiffusionEngine ### Description Creates a Merton76Process with spot, risk-free rate, dividend yield, diffusion volatility, and jump parameters, then attaches a JumpDiffusionEngine to a VanillaOption for pricing. ### Usage ```python from itofin import Settings from itofin.instruments import OptionType, VanillaOption from itofin.pricingengines import JumpDiffusionEngine from itofin.processes import Merton76Process from itofin.quotes import SimpleQuote from itofin.termstructures import BlackConstantVol, FlatForward from itofin.time import Date, DayCounter today = Date(15, 1, 2025) expiry = Date(15, 1, 2026) dc = DayCounter.actual365_fixed() settings = Settings() settings.set_evaluation_date(today) spot = SimpleQuote(100.0) rate = SimpleQuote(0.05) dividend = SimpleQuote(0.02) diffusion_vol = SimpleQuote(0.20) intensity = SimpleQuote(0.75) log_mean = SimpleQuote(-0.10) log_vol = SimpleQuote(0.25) process = Merton76Process( spot, FlatForward.from_quote(today, rate, dc), FlatForward.from_quote(today, dividend, dc), BlackConstantVol.from_quote(today, diffusion_vol, dc), intensity, log_mean, log_vol, ) engine = JumpDiffusionEngine(process, relative_accuracy=1e-10, max_iterations=1000) option = VanillaOption(OptionType.Call, 100.0, expiry, settings) option.set_jump_diffusion_engine(engine) print(option.npv(), option.delta(), option.vega()) spot.set_value(105.0) print(option.npv()) ``` ### Parameters - `spot` (SimpleQuote) - Required - Spot price quote. - `riskFree` (FlatForward) - Required - Risk-free rate term structure. - `dividend` (FlatForward) - Required - Dividend yield term structure. - `diffusionVol` (BlackConstantVol) - Required - Diffusion volatility term structure. - `intensity` (SimpleQuote) - Required - Jump intensity (expected number of jumps per year). - `logMeanJump` (SimpleQuote) - Required - Mean of log jump multiplier. - `logJumpVolatility` (SimpleQuote) - Required - Standard deviation of log jump multiplier. - `relative_accuracy` (float) - Optional - Default 1e-4. Must be finite and positive. - `max_iterations` (int) - Optional - Default 100. Must be between 1 and 100,000. ### Returns - `option.npv()` - Net present value of the option. - `option.delta()` - Delta of the option. - `option.vega()` - Vega of the option. ### Notes - The process retains market inputs; quote updates invalidate cached price and recompute on next `npv()`. - Process inspection methods: `spot()`, `jump_intensity()`, `log_mean_jump()`, `log_jump_volatility()`, `time(date)`. - Zero intensity recovers Black-Scholes. - American/Bermudan exercise and non-plain-vanilla payoffs are rejected. - Insufficient budget or failure to converge raises an error. ``` -------------------------------- ### IncrementalStatistics Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/statistics.md Documentation for the IncrementalStatistics class, including its methods and usage examples in Python and Go. ```APIDOC ## IncrementalStatistics ### Description `IncrementalStatistics` keeps weighted moments in fixed memory as observations arrive. It accepts finite values and finite nonnegative weights; a zero-weight value still counts and can set the minimum or maximum. A batch is added all at once or leaves the accumulator unchanged on error. `reset` clears the samples. ### Methods - **add_batch(values, weights)** - Adds a batch of observations with optional weights. On error, the accumulator is left unchanged. - **reset()** - Clears all samples. - **samples()** - Returns the number of observations. - **mean()** - Returns the mean of the observations. - **downside_deviation()** - Returns the downside deviation (requires strictly negative observations). ### Notes - Variance, standard deviation, error estimate, skewness and kurtosis use the core's observation-count corrections. - Downside statistics include strictly negative observations. Downside variance requires two such observations with positive combined weight. - Percentile, VaR and ES require the stored-sample statistics facade; the incremental accumulator has no empirical tail queries. ### Example (Python) ```python from itofin import statistics stream = statistics.IncrementalStatistics() stream.add_batch([-4.0, -2.0, 2.0, 8.0], weights=[1.0, 2.0, 1.0, 0.0]) assert stream.samples() == 4 assert stream.mean() == -1.5 assert stream.downside_deviation() == 4.0 stream.reset() ``` ### Example (Go) ```go session, err := itofin.NewSession() if err != nil { panic(err) } defer session.Close() stream, err := session.NewIncrementalStatistics() if err != nil { panic(err) } defer stream.Close() err = stream.AddBatch([]float64{-4, -2, 2, 8}, []float64{1, 2, 1, 0}) if err != nil { panic(err) } mean, err := stream.Mean() if err != nil { panic(err) } _ = mean ``` ``` -------------------------------- ### Project directory layout Source: https://github.com/benbenbang/libitofin/blob/main/wiki/development.md Project layout showing the core library, FFI crate, Python package, Go SDK, Node placeholder, and the git-ignored QuantLib symlink. ```text crates/libitofin/ the core library - FFI-agnostic, idiomatic Rust crates/libitofin-ffi/ extern "C" + cbindgen -> C header + libitofin_ffi crates/itofin-py/ PyO3 + maturin -> the `itofin` package (on PyPI) sdk/go/ Go 1.27.1 cgo package with explicit sessions sdk/node/ Node SDK placeholder (not implemented) QuantLib/ reference C++ tree + test oracle (git-ignored symlink) ``` -------------------------------- ### JointYieldCurves Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/joint-curves.md Documentation for the JointYieldCurves class, including constructor, parameters, methods, and usage examples in Python and Go. ```APIDOC ## JointYieldCurves ### Description Fits two mutually coupled curves in one solve. Both members use Discount traits, LogLinear interpolation and GlobalBootstrap. Member 0 forecasts the base Ibor index; member 1 forecasts the other index. Requires v0.27.0 or newer. ### Constructor #### Python ```python joint = JointYieldCurves( reference_date, fra_helpers, swap_helpers, basis_templates, day_counter, ) ``` #### Go ```go joint, err := session.NewJointYieldCurves(itofin.JointYieldCurvesConfig{ ReferenceDate: reference, FirstHelpers: fraHelpers, SecondHelpers: swapHelpers, BasisHelpers: basisTemplates, DayCounter: dayCounter, Accuracy: 1e-10, }) ``` ### Parameters - **reference_date** (Date) - Required - Reference date for the curves. - **fra_helpers** (list) - Required - Plain helper list for FRA instruments. - **swap_helpers** (list) - Required - Plain helper list for swap instruments. - **basis_templates** (list) - Required - List of `IborIborBasisSwapRateHelper` templates. Each template retains its live quote, tenor, calendar/convention, settlement lag, end-of-month choice, both index prototypes and exogenous discount curve. `bootstrap_base_curve=True` contributes to member 0; `False` contributes to member 1. - **day_counter** (DayCounter) - Required - Day counter for the curves. - **Accuracy** (float) - Optional (Go only) - Solver accuracy, default 1e-10. ### Methods #### curve(index) Returns the curve for the given member index (0 or 1). ##### Python ```python curve3m, curve6m = joint.curve(0), joint.curve(1) ``` ##### Go ```go curve3m, err := joint.Curve(0) ``` ### Notes - The assembler copies basis templates onto private forecast links; their original quote/date inspectors remain usable, but they are not rebound to the joint curves. - Every exported curve retains both contributors. Indices and instruments built from these curves can outlive the assembler and input wrappers. - Plain helper lists must contain distinct helpers with no live curve owner; reserve them for this assembly. - Solver failures remain ordinary errors on curve queries. - `FlatForward.from_quote` / `NewFlatForwardFromQuote` supplies a live discount curve. - `IborIndex.add_fixing` / `AddFixing` notifies retained and cloned indices; conflicting stored fixings are rejected. ### Example #### Python ```python joint = JointYieldCurves( reference_date, fra_helpers, swap_helpers, basis_templates, day_counter, ) curve3m, curve6m = joint.curve(0), joint.curve(1) del joint print(curve3m.discount(5.0)) ``` #### Go ```go joint, err := session.NewJointYieldCurves(itofin.JointYieldCurvesConfig{ ReferenceDate: reference, FirstHelpers: fraHelpers, SecondHelpers: swapHelpers, BasisHelpers: basisTemplates, DayCounter: dayCounter, Accuracy: 1e-10, }) if err != nil { return err } defer joint.Close() curve3m, err := joint.Curve(0) if err != nil { return err } defer curve3m.Close() ``` ``` -------------------------------- ### Go: Create Merton76Process and JumpDiffusionEngine Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/jump-diffusion.md Demonstrates constructing a Merton76Process and JumpDiffusionEngine in Go, attaching the engine to an option, and computing NPV. ```APIDOC ## Go: Merton76Process and JumpDiffusionEngine ### Description Creates a Merton76Process using session.NewMerton76Process, attaches a JumpDiffusionEngine, and computes the option's NPV. ### Usage ```go engine, err := session.NewJumpDiffusionEngine(process, 1e-10, 1000) if err != nil { return err } if err = option.SetJumpDiffusionEngine(engine); err != nil { return err } value, err := option.NPV() if err != nil { return err } fmt.Println(value) ``` ### Parameters - `process` (Merton76Process) - Required - Process created with `session.NewMerton76Process(spot, riskFree, dividend, vol, intensity, logMean, logVol)`. - `relativeAccuracy` (float64) - Required - Must be finite and positive. - `maxIterations` (int) - Required - Must be between 1 and 100,000. ### Returns - `value` (float64) - The option's NPV. ### Notes - The process exposes `Spot`, `JumpIntensity`, `LogMeanJump`, `LogJumpVolatility`, and `Time`. - Close Go handles when finished; dependents retain underlying inputs. Closing a session ends access to its handles. - Zero intensity recovers Black-Scholes. - American/Bermudan exercise and non-plain-vanilla payoffs are rejected. - Insufficient budget or failure to converge raises an error. ``` -------------------------------- ### Import Go SDK with explicit name Source: https://github.com/benbenbang/libitofin/blob/main/docs/docs/go.md Import the Go SDK with an explicit package name. The package name is `itofin`; `go` is only the final directory in the module path. ```go import itofin "github.com/benbenbang/libitofin/sdk/go" ``` -------------------------------- ### Verify a consumer with check_go_consumer.sh Source: https://github.com/benbenbang/libitofin/blob/main/docs/go-distribution.md Runs the consumer verification script from the repository against an extracted native package. CI also runs a companion script for missing-library and ABI checks. ```sh bash scripts/check_go_consumer.sh "$ITOFIN_NATIVE" ```