RustQuant Documentation

repository·main·Indexed 23 days ago

https://github.com/avhz/rustquant

A specialized Rust library for quantitative finance. It provides tools for stochastic processes, financial instrument pricing, mathematical modeling, and machine learning. Key modules include autodiff for algorithmic adjoint differentiation (AAD), instruments for pricing bonds and options, stochastics for process generators like Brownian Motion, and a math module for statistical distributions and numerical integration.

Tokens
42.9K
Snippets
83
Records
288
Agent score
83%

What's inside RustQuant

  1. Overview of RustQuant modules

    main

    RustQuant is a Rust library for quantitative finance. It is organized into several specialized modules:

    • autodiff: Algorithmic adjoint differentiation (AAD) for computing gradients of scalar output functions.
    • cashflows: Implementations for Cashflows, Quotes, and related types.
    • data: Data types for pricing (curves, term-structures, surfaces) and methods for reading/writing (CSV, JSON, Parquet) or downloading from Yahoo! Finance.
    • error: Error handling module.
    • instruments: Financial instrument implementations (e.g., Bonds, Options, Money) and their pricing logic.
    • iso: ISO code implementations for currencies (ISO-4217), countries (ISO-3166), and market identifiers (ISO-10383).
    • math: Statistical distributions (PDF, CDF, CF), FFT, numerical integration, optimization/root-finding (gradient descent, Newton-Raphson), risk-reward metrics, and sequence methods.
    • ml: Machine learning implementations including linear/logistic regression and k-nearest neighbours.
    • macros: Utility macros like plot_vector!() and assert_approx_equal!().
    • models: Quantitative finance models (Brownian Motion, short rate models, curve models, etc.).
    • portfolio: Portfolio implementation using a HashMap of Positions.
    • stochastics: Stochastic process generators (Brownian Motion, CIR, OU, Vasicek, Hull-White, etc.).
    • time: Time and date functionality including DayCounter, calendars, constants, and schedules.
    • trading: Basic limit order book (LOB) implementation.
  2. Use Gradient Descent for unconstrained optimization

    main

    To solve unconstrained optimization problems of the form $\min_{x \in \mathbb{R}^n} f(x)$ where the objective function $f(x)$ and its gradient $\nabla f(x)$ are known, you can use the GradientDescent algorithm.

    The algorithm starts with an initial guess $x_0$ and iteratively updates the position using the descent direction (the negative gradient) and a step size $\alpha_k$:

    $x_{k+1} = x_k - \alpha_k \nabla f(x_k)$

    Convergence is typically reached when the Euclidean norm of the gradient falls below a threshold $\epsilon$ (i.e., $| \nabla f(x_{k+1}) | \leq \epsilon$).

  3. Understand the `data` module purpose

    main

    The data module in rustquant is responsible for managing all forms of observable and derived information. This includes:

    1. Market Data: Anything observable in markets or derived from market observable data.
    2. Contextual/Reference Data: Data such as calendars and date conventions (though the underlying implementations for these often reside in other modules like time).
    3. Data Management: Facilities to manage and process these data types.
  4. Price a European Vanilla Option using AnalyticOptionPricer

    main

    To price a vanilla European option in rustquant, you follow a three-step workflow:

    1. Define the Option: Specify the instrument details (e.g., strike, expiry, option type).
    2. Define the Model: Select a pricing model (e.g., Black-Scholes) and provide necessary parameters like volatility and risk-free rate.
    3. Execute Pricing: Use an AnalyticOptionPricer to combine the option and the model. This pricer can generate a report containing the option details, the model used, the calculated price, and the Greeks.

    Note: The code snippets below use placeholders from the option_pricing_vanilla.rs example.

  5. Generate stochastic processes in Rust

    main
    The stochastics module provides tools to generate various stochastic processes. You can use these processes for simulations, modeling, or testing quantitative strategies. While the specific implementation details are contained in the stochastic_processes example, the module is designed to allow the generation of common models like Geometric Brownian Motion (GBM).
  6. Use the RustQuant file structure template

    main

    When creating new .rs files in the RustQuant repository, follow the standardized file structure template. This template organizes code into specific sections: Copyright/License headers, Imports, Type definitions (Structs, Enums, Traits), Implementations, and Unit Tests. This ensures consistency across the library.

    // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    // 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() {}
    }
  7. Plot stochastic process paths

    main

    Once you have generated paths for a stochastic process, you can visualize them using two primary methods:

    1. plot_vector! macro: A convenient macro for quick plotting of vectors.
    2. plotly: A more robust library for creating interactive or high-quality plots.

    Commonly used processes for plotting include Geometric Brownian Motion (GBM).

  8. Overview of the Mathematics module

    main

    The math crate provides a suite of quantitative tools including:

    • Optimization and Root Finding: Gradient Descent (using autodiff) and Newton-Raphson.
    • Numerical Integration: Tanh-Sinh (double exponential) quadrature.
    • Risk-Reward Metrics: Measures such as Sharpe, Treynor, and Sortino ratios.
    • Statistical Distributions: Various probability distributions.
    • Fast Fourier Transform (FFT): Frequency domain transformations.
    • Interpolation: Routines for estimating values between known data points.
    • Sequences: Number sequences and associated mathematical functions.
    • Statistics: A statistic trait for statistical operations.
  9. Overview of supported option types and pricing methods

    main

    The RustQuant_instruments crate provides various financial instrument types and pricing engines. The following table summarizes the supported option types and their available pricing methodologies:

    OptionAnalyticMonte-CarloFinite DifferenceLatticeGreeks
    Asian
    Barrier
    Basket
    Binary
    Chooser
    Cliquet
    Compound
    Exchange
    Forward Start
    Log
    Lookback
    Power
    Quanto
    Spread
    Supershare
    Vanilla

    Supported Models

    • Closed-form price solutions: Generalised Black-Scholes-Merton, Bachelier and Modified Bachelier, and Heston Model.
    • Lattice models: Binomial Tree (Cox-Ross-Rubinstein).