### Run RustQuant Examples Source: https://github.com/avhz/rustquant/blob/main/README.md Command to run specific examples from the RustQuant project. Replace `` with the desired example name. ```bash cargo run --example ``` -------------------------------- ### Install RustQuant via package managers Source: https://github.com/avhz/rustquant/blob/main/bindings/README.md Use these commands to install the RustQuant package from PyPI. ```bash uv add RustQuant ``` ```bash pip install RustQuant ``` -------------------------------- ### Example Output for Option Pricing - Rust Source: https://github.com/avhz/rustquant/blob/main/book/src/Modules/instruments.md Illustrates the expected output format when generating a report for a priced European Vanilla Option. ```rust OptionType: Call Strike: Strike::AtOne Expiry: Expiry::AtOne Underlying price: Price::AtOne Underlying volatility: Volatility::AtOne Underlying dividend: Dividend::Zero Risk-free rate: RiskFreeRate::Zero Price: 0.1909759744734943 Greeks: Delta: 0.6779589746313197 Gamma: 0.2309928313087414 Theta: -0.07811171147103977 Vega: 0.07511171147103977 Rho: 0.03401934910100986 ``` -------------------------------- ### Fit Spot Curve Source: https://github.com/avhz/rustquant/blob/main/book/src/Modules/data.md Example of fitting a spot curve to market data. Ensure necessary imports for curve fitting are included. ```rust use rustquant::prelude::*; use rustquant::time::Date; fn main() { let mut curves = Curves::new(); let mut spot_curve = SpotCurve::new(Date::from_ymd(2021, 1, 1)); spot_curve.set(Date::from_ymd(2021, 1, 1), 0.01); spot_curve.set(Date::from_ymd(2021, 1, 2), 0.011); spot_curve.set(Date::from_ymd(2021, 1, 3), 0.012); curves.insert("spot", spot_curve); let curves = curves; assert_eq!(curves.get("spot").unwrap().get(Date::from_ymd(2021, 1, 3)), 0.012); } ``` -------------------------------- ### Generate Stochastic Processes Source: https://github.com/avhz/rustquant/blob/main/book/src/Modules/stochastics.md Utilize the stochastic processes module to generate paths. Ensure the example file is correctly referenced in the project structure. ```rust {{#include ../../../examples/examples/stochastic_processes.rs:stochastic_processes}} ``` -------------------------------- ### Price Options with Multiple Analytic Models Source: https://context7.com/avhz/rustquant/llms.txt Demonstrates pricing a European vanilla option using various models like Black-Scholes, Merton, and Heston via the AnalyticOptionPricer. ```rust use time::macros::date; use RustQuant::instruments::*; fn main() -> Result<(), Box> { // Define the option contract let option = EuropeanVanillaOptionBuilder::default() .strike(100.0) .expiry(date!(2025 - 12 - 31)) .type_flag(TypeFlag::Call) .build()?; // Define pricing models let bs73 = BlackScholes73::new(100., 0.05, 0.2); // S, r, sigma let m73 = Merton73::new(100., 0.05, 0.03, 0.2); // S, r, q, sigma let b76 = Black76::new(100., 0.05, 0.2); // F, r, sigma let gk83 = GarmanKohlhagen83::new(100., 0.05, 0.03, 0.2); // S, r_d, r_f, sigma let h93 = Heston93::new(100., 0.05, 0.03, 0.2, 0.1, 0.1, 0.1, 0.1); let bch = Bachelier::new(100., 0.05, 0.2); // Price and print full reports with Greeks AnalyticOptionPricer::new(option, bs73).report(); AnalyticOptionPricer::new(option, m73).report(); AnalyticOptionPricer::new(option, b76).report(); AnalyticOptionPricer::new(option, gk83).report(); AnalyticOptionPricer::new(option, h93).report(); AnalyticOptionPricer::new(option, bch).report(); // Output includes: price, delta, gamma, theta, vega, rho, vanna, charm, // vomma, zomma, speed, color, ultima, lambda Ok(()) } ``` -------------------------------- ### Work with Statistical Distributions in Rust Source: https://context7.com/avhz/rustquant/llms.txt Demonstrates creating and using various statistical distributions such as Gaussian, Exponential, Poisson, Binomial, Chi-squared, and Gamma. Includes calculations for PDF, CDF, PMF, mean, and variance. ```rust use RustQuant::math::distributions::*; fn main() { // Gaussian (Normal) distribution let normal = Gaussian::new(0.0, 1.0); // mean, std_dev println!("Normal PDF at 0: {}", normal.pdf(0.0)); println!("Normal CDF at 0: {}", normal.cdf(0.0)); println!("Normal mean: {}", normal.mean()); println!("Normal variance: {}", normal.variance()); // Exponential distribution let exp = Exponential::new(0.5); // lambda println!("Exp PDF at 1: {}", exp.pdf(1.0)); println!("Exp CDF at 1: {}", exp.cdf(1.0)); // Poisson distribution let poisson = Poisson::new(3.0); // lambda println!("Poisson PMF at 2: {}", poisson.pmf(2)); // Binomial distribution let binomial = Binomial::new(10, 0.5); // n, p println!("Binomial PMF at 5: {}", binomial.pmf(5)); // Chi-squared distribution let chi_sq = ChiSquared::new(5.0); // degrees of freedom println!("Chi-squared mean: {}", chi_sq.mean()); // Gamma distribution let gamma = Gamma::new(2.0, 1.0); // shape, rate println!("Gamma variance: {}", gamma.variance()); } ``` -------------------------------- ### Run Development Toolchain Commands Source: https://github.com/avhz/rustquant/blob/main/book/src/Contributing.md Execute these commands to ensure code quality and project integrity before pushing changes. ```bash cargo doc cargo fmt cargo clippy cargo check cargo test cargo build ``` -------------------------------- ### Perform Numerical Integration in Rust Source: https://github.com/avhz/rustquant/blob/main/book/src/Modules/math.md This snippet demonstrates numerical integration using Rust. Ensure the necessary imports are available for the `numerical_integration` function. ```rust fn numerical_integration() { // Example usage of numerical integration // This function is intended to be called with specific parameters // to compute the integral of a given function over a specified range. // For instance, integrating the Gaussian density: // let gaussian = |x: f64| (-(x * x) / 2.0).exp() / (2.0 * std::f64::consts::PI).sqrt(); // let result = integrate(gaussian, -5.0, 5.0, 1000); // println!("Integral of Gaussian: {}", result); } ``` -------------------------------- ### Initialize KaTeX Math Rendering Source: https://github.com/avhz/rustquant/blob/main/crates/RustQuant_iso/katex.html Configures KaTeX to parse and render math expressions within the document body upon DOMContentLoaded. Ensure the KaTeX library is loaded before this script executes. ```javascript document.addEventListener("DOMContentLoaded", function () { renderMathInElement(document.body, { delimiters: [ { left: "$$", right: "$$", display: true }, { left: "\\(", right: "\\)", display: false }, { left: "$", right: "$", display: false }, { left: "\\[", right: "\\]", display: true } ] }); }); ``` -------------------------------- ### Define Pricing Models - Rust Source: https://github.com/avhz/rustquant/blob/main/book/src/Modules/instruments.md Sets up the necessary model definitions for pricing options. This includes defining the underlying asset and the pricing model itself. ```rust let model_definitions = BlackScholesModel { underlying: UnderlyingAsset { price: Price::AtOne, dividend: Dividend::Zero, volatility: Volatility::AtOne, }, risk_free_rate: RiskFreeRate::Zero, expiry: Expiry::AtOne, }; ``` -------------------------------- ### Simulate Stochastic Processes Source: https://context7.com/avhz/rustquant/llms.txt Generates paths for various financial models by initializing a process and passing a StochasticProcessConfig to the generate method. ```rust use RustQuant::stochastics::*; fn main() { const INITIAL_VALUE: f64 = 10.0; const START_TIME: f64 = 0.0; const END_TIME: f64 = 1.0; const NUM_STEPS: usize = 252; const NUM_SIMS: usize = 1; // Create stochastic processes with their parameters let gbm = GeometricBrownianMotion::new(0.05, 0.9); // mu, sigma let cir = CoxIngersollRoss::new(0.05, 0.9, 0.1); // theta, alpha, sigma let ou = OrnsteinUhlenbeck::new(0.05, 0.9, 0.1); // theta, mu, sigma let hw = HullWhite::new(0.1, 0.2, 0.1); // alpha, sigma, theta let fbm = FractionalBrownianMotion::new(0.7, FractionalProcessGeneratorMethod::FFT); let mjd = MertonJumpDiffusion::new(0.05, 0.5, 30.0, 0.0, 5.0); let heston = Heston::new(0.05, 0.04, 0.5, 0.04, -0.7, 0.3); // r, v0, kappa, theta, rho, sigma // Configure simulation let config = StochasticProcessConfig::new( INITIAL_VALUE, START_TIME, END_TIME, NUM_STEPS, StochasticScheme::EulerMaruyama, NUM_SIMS, false, // parallel None ); // Generate paths let gbm_output = gbm.generate(&config); let cir_output = cir.generate(&config); let ou_output = ou.generate(&config); // Access generated paths and times println!("GBM paths: {:?}", gbm_output.paths); println!("Time grid: {:?}", gbm_output.times); } ``` -------------------------------- ### Manage Financial Portfolios in Rust Source: https://context7.com/avhz/rustquant/llms.txt Creates and manages a financial portfolio with multiple positions, including options. Calculates portfolio value, cost, P&L, and position weights. ```rust use std::collections::HashMap; use time::Duration; use RustQuant::portfolios::{Portfolio, Position}; use RustQuant::instruments::options::{BlackScholesMerton, TypeFlag}; use RustQuant::instruments::fx::USD; use RustQuant::time::today; fn main() { // Create a position of 100 call options let call_position = Position { instrument: BlackScholesMerton::new( 0.08, // cost of carry 60.0, // underlying price 65.0, // strike 0.3, // volatility 0.08, // risk-free rate None, // dividend yield today() + Duration::days(91), // expiry TypeFlag::Call, ), quantity: 100, purchase_price: 2.10, current_price: 3.50, currency: Some(USD), }; // Create a position of 100 put options let put_position = Position::new( BlackScholesMerton::new( 0.05, 100.0, 95.0, 0.2, 0.1, None, today() + Duration::days(182), TypeFlag::Put, ), 100, 2.45, 2.00, Some(USD), ); // Build portfolio let positions = HashMap::from([ ("Call Options".to_string(), call_position), ("Put Options".to_string(), put_position), ]); let portfolio = Portfolio::new(positions); // Portfolio analytics println!("Portfolio Value: ${:.2}", portfolio.value()); println!("Portfolio Cost: ${:.2}", portfolio.cost()); println!("Portfolio P&L: ${:.2}", portfolio.profit()); println!("Position Weights: {:?}", portfolio.position_weights()); } ``` -------------------------------- ### Organize Rust Code Structure Source: https://github.com/avhz/rustquant/blob/main/book/src/Contributing.md Follow this recommended layout to improve readability by separating definitions, implementations, and tests. ```rust // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Structs, enums, and traits // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ enum Enum {} struct Struct {} trait Trait {} // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Implementations, functions, and macros // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ impl Struct {} impl Trait for Struct {} // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Unit tests // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #[cfg(test)] mod tests { use super::*; #[test] fn very_thorough_test() {} } ``` -------------------------------- ### Add License Header to New Files Source: https://github.com/avhz/rustquant/blob/main/book/src/Contributing.md Include this header in all new source files to maintain project licensing compliance. ```rust // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // RustQuant: A Rust library for quantitative finance tools. // Copyright (C) 2023 https://github.com/avhz // Dual licensed under Apache 2.0 and MIT. // See: // - LICENSE-APACHE.md // - LICENSE-MIT.md // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ``` -------------------------------- ### Initialize Math Rendering Source: https://github.com/avhz/rustquant/blob/main/crates/RustQuant/katex.html Renders mathematical expressions on the page after the DOM is loaded. Configure delimiters for different rendering modes (display vs. inline). ```javascript document.addEventListener("DOMContentLoaded", function () { renderMathInElement(document.body, { delimiters: [ { left: "$$", right: "$$", display: true }, { left: "\\(", right: "\\)", display: false }, { left: "$", right: "$", display: false }, { left: "\\[", right: \\]", display: true } ] }); }); ``` -------------------------------- ### RustQuant File Template Source: https://github.com/avhz/rustquant/blob/main/book/src/Template.md Use this template for all .rs files to ensure consistent licensing, imports, and structure. Includes placeholders for structs, enums, traits, and unit tests. ```rust // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // RustQuant: A Rust library for quantitative finance tools. // Copyright (C) 2023 https://github.com/avhz // Dual licensed under Apache 2.0 and MIT. // See: // - LICENSE-APACHE.md // - LICENSE-MIT.md // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // IMPORTS // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ use RustQuant::*; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // STRUCTS, ENUMS, AND TRAITS // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ enum Enum {} struct Struct {} trait Trait {} // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // IMPLEMENTATIONS, TRAITS, AND FUNCTIONS // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ impl Struct {} impl Trait for Struct {} // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // UNIT TESTS // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ #[cfg(test)] mod tests { use super::*; #[test] fn very_thorough_test() {} } ``` -------------------------------- ### Compute Black-Scholes Greeks via Autodiff Source: https://context7.com/avhz/rustquant/llms.txt Uses automatic differentiation to calculate option prices and Greeks simultaneously. Requires the RustQuant::autodiff module. ```rust use RustQuant::autodiff::*; fn main() { fn normcdf(x: Variable<'_>) -> Variable<'_> { 0.5 * (-x / core::f64::consts::SQRT_2).erfc() } fn black_scholes<'v>( S: Variable<'v>, // Spot price K: Variable<'v>, // Strike price T: Variable<'v>, // Time to maturity r: Variable<'v>, // Risk-free rate v: Variable<'v>, // Volatility d: Variable<'v>, // Dividend yield ) -> Variable<'v> { let d1 = ((S / K).ln() + (r - d + v * v / 2.0) * T) / (v * T.sqrt()); let d2 = d1 - v * T.sqrt(); S * (-d * T).exp() * normcdf(d1) - K * (-r * T).exp() * normcdf(d2) } let graph = Graph::new(); let s = graph.var(100.0); // Spot let k = graph.var(100.0); // Strike let t = graph.var(1.0); // Time (1 year) let r = graph.var(0.05); // Rate let v = graph.var(0.25); // Volatility let d = graph.var(0.02); // Dividend let call_price = black_scholes(s, k, t, r, v, d); let greeks = call_price.accumulate(); println!("Call Price: {}", call_price.value); println!("Delta (dC/dS): {}", greeks.wrt(&s)); println!("Vega (dC/dv): {}", greeks.wrt(&v)); println!("Theta (dC/dT): {}", greeks.wrt(&t)); println!("Rho (dC/dr): {}", greeks.wrt(&r)); } ``` -------------------------------- ### Price European Vanilla Option and Generate Report - Rust Source: https://github.com/avhz/rustquant/blob/main/book/src/Modules/instruments.md Constructs an AnalyticOptionPricer to calculate the price and Greeks for a defined option and model, then generates a report. ```rust let mut report = AnalyticOptionPricer::new(option_definition, model_definitions); println!("{}", report.generate_report()); ``` -------------------------------- ### Execute Numerical Integration Source: https://context7.com/avhz/rustquant/llms.txt Uses the Tanh-Sinh quadrature method to integrate functions. Suitable for complex financial models like Heston. ```rust use std::f64::consts::PI; use RustQuant::math::*; fn main() { // Define function to integrate: Standard Normal PDF fn normal_pdf(x: f64) -> f64 { (2.0 * PI).sqrt().recip() * (-0.5 * x.powi(2)).exp() } // Integrate from -5 to 5 standard deviations let integral = integrate(normal_pdf, -5.0, 5.0); println!("Integral of Normal PDF: {}", integral); // ~= 1.0 // Another example: e^(sin(x)) fn complex_function(x: f64) -> f64 { (x.sin()).exp() } let result = integrate(complex_function, 0.0, 5.0); println!("Integral of e^sin(x): {}", result); // ~= 7.189 } ``` -------------------------------- ### Construct and Interpolate Yield Curve in Rust Source: https://context7.com/avhz/rustquant/llms.txt Builds a yield curve (spot, discount, forward) using specified dates, rates, and interpolation method. Interpolates rates for a range of new dates. ```rust use time::macros::date; use time::Duration; use RustQuant::data::*; fn main() { let today = date!(2024 - 08 - 01); // Define curve dates and rates (US Treasury curve) let dates = vec![ today + Duration::days(30), // 1 Mo today + Duration::days(60), // 2 Mo today + Duration::days(90), // 3 Mo today + Duration::days(180), // 6 Mo today + Duration::days(365), // 1 Yr today + Duration::days(365 * 2), // 2 Yr today + Duration::days(365 * 5), // 5 Yr today + Duration::days(365 * 10), // 10 Yr today + Duration::days(365 * 30), // 30 Yr ]; let rates = vec![5.55, 5.46, 5.37, 5.08, 4.62, 4.16, 3.84, 3.99, 4.27]; // Create curve with linear interpolation let mut curve = Curve::new( dates, rates, CurveType::Spot, InterpolationMethod::Linear ).unwrap(); // Interpolate rates for new dates let new_dates = (1..365 * 5) .map(|i| today + Duration::days(i)) .collect::>(); curve.get_rates_and_insert(new_dates); // curve.plot(); // Visualize with plotly } ``` -------------------------------- ### Add RustQuant dependency via Cargo Source: https://github.com/avhz/rustquant/blob/main/book/src/Introduction.md Use this command in your terminal to add the RustQuant crate to your project's Cargo.toml file. ```bash cargo add RustQuant ``` -------------------------------- ### Fit Linear Regression Models Source: https://context7.com/avhz/rustquant/llms.txt Fits linear models using QR or SVD decomposition. Requires nalgebra matrices for input data. ```rust use nalgebra::{DMatrix, DVector}; use RustQuant::error::RustQuantError; use RustQuant::ml::*; fn main() -> Result<(), RustQuantError> { // Training data: 4 samples, 3 features let x_train = DMatrix::from_row_slice( 4, 3, &[-0.083, -0.633, -0.399, -0.982, 1.090, -0.468, -1.875, -0.913, 0.326, -0.186, 1.001, -0.412], ); // Test data let x_test = DMatrix::from_row_slice( 4, 3, &[0.562, 0.595, -0.411, 0.663, 0.452, -0.294, -0.602, 0.896, 1.218, 0.698, 0.572, 0.244], ); // Response variable let y = DVector::from_row_slice(&[-0.445, -1.847, -0.628, -0.861]); // Create input and fit model let input = LinearRegressionInput { x: x_train, y }; let output = input.fit(Decomposition::QR)?; // or Decomposition::SVD // Make predictions let predictions = output.predict(x_test)?; println!("Intercept: {:?}", output.intercept); println!("Coefficients: {:?}", output.coefficients); println!("Predictions: {:?}", predictions); Ok(()) } ``` -------------------------------- ### Price European Options with Black-Scholes-Merton Source: https://context7.com/avhz/rustquant/llms.txt Uses the BlackScholesMertonBuilder to define option parameters and calculate price, Greeks, and implied volatility. ```rust use time::macros::date; use RustQuant::instruments::options::*; fn main() -> Result<(), Box> { // Build an option using the builder pattern let option = BlackScholesMertonBuilder::default() .underlying_price(100.0) .strike_price(100.0) .volatility(0.3) .risk_free_rate(0.03) .cost_of_carry(0.05) .expiration_date(date!(2024 - 12 - 31)) .option_type(TypeFlag::Call) .build()?; // Calculate option price and Greeks println!("Call price = {}", option.price()); // Option premium println!("Call delta = {}", option.delta()); // Price sensitivity println!("Call gamma = {}", option.gamma()); // Delta sensitivity println!("Call theta = {}", option.theta()); // Time decay println!("Call vega = {}", option.vega()); // Volatility sensitivity println!("Call rho = {}", option.rho()); // Interest rate sensitivity // Implied volatility from market price let market_price = 10.0; println!("IV = {}", option.implied_volatility(market_price)); Ok(()) } ``` -------------------------------- ### Price Exotic Options with Monte Carlo Source: https://context7.com/avhz/rustquant/llms.txt Uses StochasticProcessConfig to define simulation parameters and OptionContractBuilder to define the contract type for pricing Asian, power, and vanilla options. ```rust use time::macros::date; use RustQuant::instruments::*; use RustQuant::stochastics::*; fn main() { let underlying = 100.0; let strike = 100.0; let rate = 0.05; let time = 1.0; let volatility = 0.2; let expiry = date!(2025 - 01 - 01); // Create GBM stochastic process let process = GeometricBrownianMotion::new(rate, volatility); // Configure simulation: initial value, t0, t_n, steps, scheme, sims, parallel let config = StochasticProcessConfig::new( underlying, 0.0, time, 365, // Daily steps StochasticScheme::EulerMaruyama, 100_000, // Number of simulations true, // Parallel execution None ); // Define option contract let contract = OptionContractBuilder::default() .type_flag(TypeFlag::Call) .exercise_flag(ExerciseFlag::European { expiry }) .strike_flag(Some(StrikeFlag::Fixed)) .build() .unwrap(); // Price different exotic options let vanilla = EuropeanVanillaOption::new(strike, expiry, TypeFlag::Call); let asian = AsianOption::new( contract.clone(), AveragingMethod::ArithmeticDiscrete, Some(strike), ); let power = PowerOption::new(contract.clone(), strike, 2.0); println!("Vanilla: {:?}", vanilla.price_monte_carlo(&process, &config, rate)); println!("Asian: {:?}", asian.price_monte_carlo(&process, &config, rate)); println!("Power: {:?}", power.price_monte_carlo(&process, &config, rate)); } ``` -------------------------------- ### Differentiate simple expressions Source: https://github.com/avhz/rustquant/blob/main/book/src/Modules/autodiff.md Use this for basic scalar mathematical expressions. ```rust {{#include ../../../examples/examples/autodiff.rs:simple_expressions}} ``` -------------------------------- ### Perform Gradient Descent Optimization Source: https://context7.com/avhz/rustquant/llms.txt Optimizes objective functions using automatic differentiation for gradient computation. The optimizer requires a learning rate, iteration limit, and convergence tolerance. ```rust use RustQuant::autodiff::*; use RustQuant::math::optimization::gradient_descent::*; // Define objective function using autodiff Variables fn himmelblau<'v>(variables: &[Variable<'v>]) -> Variable<'v> { let x = variables[0]; let y = variables[1]; (x.powf(2.0) + y - 11.0).powf(2.0) + (x + y.powf(2.0) - 7.0).powf(2.0) } fn main() { // Create optimizer: step_size, max_iterations, tolerance let gd = GradientDescent::new( 0.01, // Learning rate 100, // Max iterations Some(f64::EPSILON.sqrt()) // Convergence tolerance ); // Optimize from initial guess with verbose output let result = gd.optimize(himmelblau, &[5.0, 5.0], true); // Himmelblau function has minima at (3, 2), (-2.805, 3.131), etc. println!("Minimum found at: {:?}", result.minimizer); println!("Function value: {}", result.minimum); } ``` -------------------------------- ### Differentiate closures Source: https://github.com/avhz/rustquant/blob/main/book/src/Modules/autodiff.md Supports differentiation of Rust closures. ```rust {{#include ../../../examples/examples/autodiff.rs:closures}} ``` -------------------------------- ### Compute Gradients with Automatic Differentiation Source: https://context7.com/avhz/rustquant/llms.txt Uses the Graph structure to define variables and expressions, then computes gradients via reverse accumulation. Supports custom functions and Graphviz visualization. ```rust use RustQuant::autodiff::*; fn main() { // Create a computation graph let g = Graph::new(); // Define variables on the graph let x = g.var(69.0); let y = g.var(420.0); // Build expression - supports all standard math operations let f = (x * y).exp() + x.powi(2) + y.sin(); // Compute gradient via reverse accumulation let gradient = f.accumulate(); println!("f(x,y) = {}", f.value); println!("df/dx = {}", gradient.wrt(&x)); println!("df/dy = {}", gradient.wrt(&y)); println!("gradient = {:?}", gradient.wrt(&[x, y])); // Define functions with multiple variables fn custom_function<'v>(vars: &[Variable<'v>], consts: &[f64]) -> Variable<'v> { vars[0].powf(vars[1] + consts[0].cos()) - vars[2].atanh() / consts[1] + consts[0] } let graph = Graph::new(); let variables = graph.vars(&[3.0, 2.0, 1.0]); let constants = [1.0, 2.0]; let result = custom_function(&variables, &constants); let grad = result.accumulate(); println!("Result: {}", result.value); println!("Gradient: {:?}", grad.wrt(&variables)); // Visualize computation graph (Graphviz DOT format) println!("{}", graphviz(&graph, &variables)); } ``` -------------------------------- ### Fit Logistic Regression Model in Rust Source: https://context7.com/avhz/rustquant/llms.txt Fits a logistic regression model using IRLS for binary classification. Requires nalgebra for matrix operations and RustQuant for ML functionalities. Handles potential fitting errors. ```rust use nalgebra::{DMatrix, DVector}; use RustQuant::ml::*; fn main() { // Sample training data: features and binary targets let x_train = DMatrix::from_row_slice(4, 2, &[1.0, 2.0, 2.0, 3.0, 3.0, 1.0, 4.0, 2.0]); let y_train = DVector::from_row_slice(&[0.0, 0.0, 1.0, 1.0]); // Fit logistic regression model let input = LogisticRegressionInput { x: x_train, y: y_train, }; let tolerance = f64::EPSILON.sqrt(); match input.fit(LogisticRegressionAlgorithm::IRLS, tolerance) { Ok(output) => { println!("Coefficients: {:?}", output.coefficients); println!("Iterations: {}", output.iterations); // Predict on new data let x_test = DMatrix::from_row_slice(2, 2, &[2.5, 2.0, 3.5, 1.5]); let x_test_extended = x_test.insert_column(0, 1.0); let eta = &x_test_extended * &output.coefficients; let probabilities = ActivationFunction::logistic(&eta); let predictions = probabilities.map(|p| if p > 0.5 { 1.0 } else { 0.0 }); println!("Probabilities: {:?}", probabilities); println!("Predictions: {:?}", predictions); } Err(e) => println!("Error: {}", e), } } ``` -------------------------------- ### Differentiate functions Source: https://github.com/avhz/rustquant/blob/main/book/src/Modules/autodiff.md Supports differentiation of standard Rust functions. ```rust {{#include ../../../examples/examples/autodiff.rs:functions}} ``` -------------------------------- ### Render Math in Document Body Source: https://github.com/avhz/rustquant/blob/main/crates/RustQuant_data/katex.html This JavaScript code initializes the MathJax library to render mathematical expressions within the document's body. It configures delimiters for inline and display math. ```javascript document.addEventListener("DOMContentLoaded", function () { renderMathInElement(document.body, { delimiters: [ { left: "$$\", right: "$$\", display: true }, { left: "\\(\", right: "\\)\", display: false }, { left: "$\", right: "$\", display: false }, { left: "\\[\", right: "\\]\", display: true } ] }); }); ``` -------------------------------- ### Render Math in Document Body Source: https://github.com/avhz/rustquant/blob/main/crates/RustQuant_autodiff/katex.html This JavaScript code initializes the MathJax library to render mathematical expressions within the document's body. It configures delimiters for inline and display math. ```javascript document.addEventListener("DOMContentLoaded", function () { renderMathInElement(document.body, { delimiters: [ { left: "$$", right: "$$", display: true }, { left: "\\(", right: "\\)", display: false }, { left: "$", right: "$", display: false }, { left: "\[", right: "\]", display: true } ] }); }); ``` -------------------------------- ### Define European Vanilla Option - Rust Source: https://github.com/avhz/rustquant/blob/main/book/src/Modules/instruments.md Defines the parameters for a European Vanilla Option. Ensure all necessary fields are correctly populated. ```rust let option_definition = VanillaOption { option_type: OptionType::Call, strike: Strike::AtOne, expiry: Expiry::AtOne, }; ``` -------------------------------- ### Differentiate block expressions Source: https://github.com/avhz/rustquant/blob/main/book/src/Modules/autodiff.md Supports differentiation of more complex block-based expressions. ```rust {{#include ../../../examples/examples/autodiff.rs:block_expressions}} ``` -------------------------------- ### Calculate Euclidean norm for stationarity condition Source: https://github.com/avhz/rustquant/blob/main/examples/examples/gradient_descent.md Computes the Euclidean norm of the gradient vector to check against a threshold. ```rust gradient.iter().map(|&x| x * x).sum::().sqrt() < std::f64::EPSILON.sqrt() ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.