OptionStratLib
OptionStratLib is a comprehensive Rust library for options trading and strategy development across multiple asset classes.
Install / Use
npx skills add joaquinbejar/OptionStratLibInstalls into whichever agent you are using.
README
OptionStratLib v0.18.0: Financial Options Library
Table of Contents
- Introduction
- Features
- Core Modules
- Trading Strategies
- Setup Instructions
- Library Usage
- Usage Examples
- Testing
- Contribution and Contact
Introduction
OptionStratLib is a comprehensive Rust library for options trading and strategy development across multiple asset classes. This versatile toolkit enables traders, quants, and developers to model, analyze, and visualize options strategies with a robust, type-safe approach. The library focuses on precision with decimal-based calculations, extensive test coverage, and a modular architecture built on modern Rust 2024 edition.
Features
1. Pricing Models
- Black-Scholes Model: European options pricing with full Greeks support
- Binomial Tree Model: American and European options with early exercise capability
- Monte Carlo Simulations: Complex pricing scenarios and path-dependent options
- Telegraph Process Model: Advanced stochastic modeling for jump-diffusion processes
- American Options: Barone-Adesi-Whaley approximation for early exercise
- Exotic Options: Complete support for 14 exotic option types (see below)
2. Greeks Calculation
- Complete Greeks suite: Delta, Gamma, Theta, Vega, Rho, Vanna, Vomma, Veta, Charm, Color
- Real-time sensitivity analysis
- Greeks visualization and risk profiling
- Custom Greeks implementations with adjustable parameters
3. Volatility Models
- Implied volatility calculation using Newton-Raphson method
- Volatility surface construction and interpolation
- Historical volatility estimation
- Advanced volatility modeling tools
4. Option Chain Management
- Complete option chain construction and analysis
- Strike price generation algorithms
- Chain data import/export (CSV/JSON formats)
- Advanced filtering and selection tools
- Option data grouping and organization
5. Trading Strategies (25+ Strategies)
- Single Leg: Long/Short Calls and Puts
- Spreads: Bull/Bear Call/Put Spreads
- Butterflies: Long/Short Butterfly Spreads, Call Butterfly
- Complex: Iron Condor, Iron Butterfly
- Volatility: Long/Short Straddles and Strangles
- Income: Covered Calls (with spot leg support), Poor Man's Covered Call
- Protection: Protective Puts, Collars
- Custom: Flexible custom strategy framework
- Multi-Asset: Strategies combining options with spot, futures, or perpetuals
6. Risk Management & Analysis
- Position tracking and management
- Break-even analysis with multiple break-even points
- Profit/Loss calculations at various price points
- Risk profiles and comprehensive visualizations
- Delta neutrality analysis and adjustment
- Probability analysis for strategy outcomes
7. Backtesting Framework
- Comprehensive backtesting engine
- Performance metrics calculation
- Strategy optimization tools
- Historical analysis capabilities
8. Simulation Tools
- Monte Carlo simulations for strategy testing
- Telegraph process implementation
- Random walk simulations
- Custom simulation frameworks
- Parametrized simulations with adjustable inputs
9. Visualization & Plotting
- Strategy payoff diagrams
- Greeks visualization
- 3D volatility surfaces
- Risk profiles and P&L charts
- Interactive charts (powered by
plotly.rs) - Binomial tree visualization
- Comprehensive plotting utilities
10. Data Management
- Efficient decimal-based calculations using
rust_decimal - CSV/JSON import/export functionality
- Time series data handling
- Price series management and manipulation
- Robust data validation and error handling
11. Mathematical Tools
- Curve interpolation techniques
- Surface construction and analysis
- Geometric operations for financial modeling
- Advanced mathematical utilities for options pricing
12. Exotic Option Pricing
Complete pricing support for all exotic option types:
- Asian: Arithmetic and geometric average price options
- Barrier: Up/Down, In/Out barrier options with rebates
- Binary: Cash-or-nothing and asset-or-nothing options
- Lookback: Fixed and floating strike lookback options
- Compound: Options on options
- Chooser: Options to choose call or put at future date
- Cliquet: Forward-starting options with local caps/floors
- Rainbow: Multi-asset best-of/worst-of options
- Spread: Kirk's approximation for price differentials
- Quanto: Currency-protected options
- Exchange: Margrabe's formula for asset exchange
- Power: Non-linear payoff options
Quality & Discipline (0.16.x)
The 0.16 line is a quality-hardening release. Every change below is
enforced crate-wide and documented in CHANGELOG.md:
- Checked
Decimalarithmetic. Every monetary-path kernel routes throughd_add/d_sub/d_mul/d_div/d_sum/d_sum_iterinmodel::decimal. Overflow on any monetary expression surfacesDecimalError::Overflow { operation, lhs, rhs }tagged with a static call-site string; no silent wraparound. - Non-finite
f64guards. Everyf64 → Decimalboundary inside pricing, Greeks, volatility, and simulation is wrapped withfinite_decimal(..)and surfaces a domain-specificNonFinite { context, value }variant (PricingError,GreeksError,VolatilityError,SimulationError) instead of collapsing silently toDecimal::ZERO. NonZeroUsizestep counts.price_binomial,monte_carlo_option_pricing,telegraphand related kernels takestd::num::NonZeroUsizeforsteps/simulations; zero is structurally invalid at the type level. Use thenz!(N)macro at literal call sites.Positiveat every public boundary. Monetary values, strikes, quantities, volatilities arePositive(newtype aroundDecimal). Strategy-level P&L goes throughPositive::new_decimal(..)at every point where a signedDecimalwould otherwise be clamped toPositive, so inverted strikes or out-of-range optimizer candidates return typedStrategyErrorrather than panicking.- Zero unchecked indexing in production code.
#![deny(clippy::indexing_slicing)]is enforced crate-wide with scoped, documented escapes per module. Tests stay permissive via#![cfg_attr(test, allow(..))]. Production paths use.get(..).ok_or_else(..)with typed errors. - Doc coverage floor.
#![deny(missing_docs, rustdoc::broken_intra_doc_links)]. Everypubitem has a///summary; everyResultreturner documents its# Errorscontract. - Structured tracing.
#[tracing::instrument]on the public hot paths:pricing::black_scholes,pricing::monte_carlo_option_pricing,pricing::price_binomial,volatility::implied_volatility, and the strategy optimizer entry pointsget_best_ratio/get_best_area. Noprintln!/eprintln!/dbg!/log::anywhere insrc/. - Compiler-attribute discipline.
#[must_use]on every pure function and builder,#[inline]on small hot-path helpers,#[cold] #[inline(never)]on every error constructor,#[repr(u8)]on small stable enums, canonical#[derive]ordering. - Deterministic simulation tests.
utils::deterministic_rng(seed)provides a canonical seededStdRngfor Monte-Carlo / simulation tests, so precision shifts in upstream arithmetic cannot flip assertions by luck. - Pricing-identity regression tests.
tests/unit/pricing/identities_test.rslocks put-call parity on a grid, CRR binomial convergence to Black-Scholes, and the Greek sanity identities (Γ_c = Γ_p,Vega_c = Vega_p,Δ_c − Δ_p ≈ e^{-qT}).
Arithmetic-Error Cascade
flowchart LR
subgraph Kernels["Numeric kernels (model / pricing / greeks / volatility / simulation)"]
DADD["d_add / d_sub / d_mul / d_div"]
DSUM["d_sum / d_sum_iter"]
FD["finite_decimal(f64)"]
end
subgraph Errors["Typed errors (error/*)"]
DOV["DecimalError::Overflow { operation, lhs, rhs }"]
PNF["PricingError::NonFinite { context, value }"]
GNF["GreeksError::NonFinite"]
VNF["VolatilityError::NonFinite"]
SNF["SimulationEr
Related Skills
clawhub
385.5kSearch ClawHub for skills when a requested capability is not already available; install, verify, update, uninstall, publish, or sync skills.
coding-agent
385.5kDelegate coding work to Codex, Claude Code, or OpenCode as background workers; not simple edits or read-only code lookup.
node-connect
385.5kDiagnose OpenClaw Android, iOS, or macOS node pairing, QR/setup code, route, auth, and connection failures.
taskflow
385.5kCoordinate multi-step detached tasks as one durable TaskFlow job with owner context, state, waits, and child tasks.
