Skip to content

Commit

Permalink
feat: improve docs
Browse files Browse the repository at this point in the history
  • Loading branch information
dancixx committed Oct 6, 2024
1 parent 627db05 commit 7ef6dcd
Show file tree
Hide file tree
Showing 12 changed files with 99 additions and 24 deletions.
2 changes: 1 addition & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
{
"rust-analyzer.cargo.features": ["yahoo"]
"rust-analyzer.cargo.features": ["malliavin", "yahoo"]
}
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,9 @@ yahoo_finance_api = { version = "2.3.0", optional = true }

[features]
default = ["jemalloc", "yahoo"]
mimalloc = ["dep:mimalloc"]
jemalloc = ["dep:tikv-jemallocator"]
malliavin = []
mimalloc = ["dep:mimalloc"]
yahoo = ["dep:time", "dep:yahoo_finance_api"]

[lib]
Expand Down
52 changes: 35 additions & 17 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,28 +1,46 @@
#![allow(non_snake_case)]
#![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)]

//! # Stochastic Processes
//! # Stochastic Processes in Rust
//!
//! `stochastic-rs` is a Rust library designed for simulating and analyzing various types of stochastic processes.
//! It offers an extensive set of tools for researchers, financial engineers, and developers interested in modeling random phenomena in diverse fields.
//!
//! ## Getting Started
//!
//! `stochastic-rs` is a Rust library that provides a comprehensive set of tools to simulate and analyze stochastic processes.
//! This library is useful for researchers, practitioners, and anyone interested in modeling and simulating various types of stochastic processes.
//! To start using the library, add `stochastic-rs` to your `Cargo.toml`:
//! ```toml
//! [dependencies]
//! stochastic-rs = "*"
//! ```
//!
//! ## Features
//! ## Modules
//!
//! - Simulation of various diffusion processes including Brownian motion, geometric Brownian motion, Ornstein-Uhlenbeck process, and more.
//! - Generation of noise processes such as Gaussian noise, fractional Gaussian noise, and Poisson processes.
//! - Modeling with advanced stochastic models like the Heston model and the Bates model.
//! - Calculation of fractal dimensions and other statistical properties of time series data.
//! - Support for jump processes and compound Poisson processes.
//! | Module | Description |
//! |----------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
//! | **stochastic** | High-performance data generation for stochastic processes. Optimized for AI training and similar purposes where large amounts of synthetic data are required. It includes efficient algorithms for simulating various stochastic processes with a focus on performance and scalability. |
//! | **quant** | Leveraging stochastic models for quantitative finance analysis. Includes tools for modeling financial instruments, pricing derivatives, risk assessment, and other financial computations using stochastic methods. It aims to bridge the gap between theoretical models and practical financial applications. |
//! | **stats** | Focused on statistical analysis related specifically to stochastic processes. While Rust has several excellent statistical libraries, this module provides functions for parameter estimation, calculating fractal dimensions, time-series analysis, and other specialized statistical tools relevant to stochastic processes. |
//! | **ai** | Provides out-of-the-box AI and deep neural network (DNN) solutions. Initially developed for PhD research problems, it offers tools and models that can be applied to more general AI topics, facilitating research and development in machine learning and data science. |
//!
//! ## Performance Optimization
//!
//! For performance reasons, the default allocator used in `stochastic-rs` is `jemalloc`, which is known for its efficient memory allocation in high-performance scenarios.
//! If you prefer to use the system allocator, simply disable the default features in your `Cargo.toml` like this:
//! ```toml
//! [dependencies]
//! stochastic-rs = { version = "*", default-features = false }
//! ```
//!
//! ## License
//!
//! This project is licensed under the MIT License.
//! This project is licensed under the MIT License. For more details, see the [LICENSE](LICENSE) file.
//!
//! ## Contributions and Acknowledgments
//!
//! ## Acknowledgements
//! Contributions are welcome! Feel free to open issues or submit pull requests on [GitHub](https://github.com/dancixx/stochastic-rs).
//! - Developed and maintained by [dancixx](https://github.com/dancixx).
//!
//! - Developed by [dancixx](https://github.com/dancixx).
//! - Contributions and feedback are welcome!
#![allow(non_snake_case)]
#![allow(clippy::type_complexity)]
#![allow(clippy::too_many_arguments)]

#[cfg(feature = "mimalloc")]
#[global_allocator]
Expand Down
1 change: 0 additions & 1 deletion src/quant/volatility.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,6 @@ where
fn jacobian(&self) -> Option<DMatrix<f64>> {
let derivates = self.derivates.borrow();
let derivates = derivates.iter().flatten().cloned().collect::<Vec<f64>>();
println!("{:?}", derivates.len());

// The Jacobian matrix is a matrix of partial derivatives
// of the residuals with respect to the parameters.
Expand Down
20 changes: 20 additions & 0 deletions src/stochastic.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,24 @@
//! # Stochastic Process Simulation Modules
//!
//! `stochastic` provides various modules to simulate and analyze stochastic processes efficiently.
//!
//! ## Modules
//!
//! | Module | Description |
//! |-----------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
//! | **diffusion** | Handles diffusion processes, such as Brownian motion and Geometric Brownian motion, commonly used in physics and finance to model random behavior over time. |
//! | **interest** | Provides models for simulating stochastic interest rates, including well-known models like the Cox-Ingersoll-Ross (CIR) model used in financial mathematics. |
//! | **jump** | Implements jump processes, where sudden changes occur at random intervals, such as in the Poisson process or in financial models like the Bates model. |
//! | **malliavin** | Tools for working with the Malliavin calculus, which is used to compute derivatives of stochastic processes for sensitivity analysis and other advanced applications. |
//! | **noise** | Generates various noise processes, including Gaussian and fractional Gaussian noise, which are essential for simulating random perturbations in stochastic models. |
//! | **process** | Provides general abstractions and implementations for creating, simulating, and sampling stochastic processes, supporting both regular and parallelized workflows. |
//! | **volatility** | Focuses on modeling stochastic volatility, including processes like the Heston model, which are used to simulate changes in volatility over time in financial markets. |
//!
pub mod diffusion;
pub mod interest;
pub mod jump;
#[cfg(feature = "malliavin")]
pub mod malliavin;
pub mod noise;
pub mod process;
Expand Down Expand Up @@ -45,6 +63,7 @@ pub trait Sampling<T: Clone + Send + Sync + Zero>: Send + Sync {
fn distribution(&mut self) {}

/// Malliavin derivative of the process
#[cfg(feature = "malliavin")]
fn malliavin(&self) -> Array1<T> {
unimplemented!()
}
Expand Down Expand Up @@ -82,6 +101,7 @@ pub trait Sampling2D<T: Clone + Send + Sync + Zero>: Send + Sync {
fn m(&self) -> Option<usize>;

/// Malliavin derivative of the process
#[cfg(feature = "malliavin")]
fn malliavin(&self) -> [Array1<T>; 2] {
unimplemented!()
}
Expand Down
1 change: 1 addition & 0 deletions src/stochastic/diffusion/cev.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,7 @@ impl Sampling<f64> for CEV {
/// D_r S_t = \sigma S_t^{\gamma} * 1_{[0, r]}(r) exp(\int_0^r (\mu - \frac{\gamma^2 \sigma^2 S_u^{2\gamma - 2}}{2}) du + \int_0^r \gamma \sigma S_u^{\gamma - 1} dW_u)
///
/// The Malliavin derivative of the CEV process shows the sensitivity of the stock price with respect to the Wiener process.
#[cfg(feature = "malliavin")]
fn malliavin(&self) -> Array1<f64> {
self.malliavin.lock().unwrap().clone().unwrap()
}
Expand Down
7 changes: 7 additions & 0 deletions src/stochastic/diffusion/gbm.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#[cfg(feature = "malliavin")]
use std::sync::Mutex;

use ndarray::Array1;
Expand All @@ -20,7 +21,9 @@ pub struct GBM {
pub t: Option<f64>,
pub m: Option<usize>,
pub distribution: Option<LogNormal>,
#[cfg(feature = "malliavin")]
pub calculate_malliavin: Option<bool>,
#[cfg(feature = "malliavin")]
malliavin: Mutex<Option<Array1<f64>>>,
}

Expand All @@ -35,7 +38,9 @@ impl GBM {
t: params.t,
m: params.m,
distribution: None,
#[cfg(feature = "malliavin")]
calculate_malliavin: Some(false),
#[cfg(feature = "malliavin")]
malliavin: Mutex::new(None),
}
}
Expand All @@ -54,6 +59,7 @@ impl Sampling<f64> for GBM {
gbm[i] = gbm[i - 1] + self.mu * gbm[i - 1] * dt + self.sigma * gbm[i - 1] * gn[i - 1]
}

#[cfg(feature = "malliavin")]
if self.calculate_malliavin.is_some() && self.calculate_malliavin.unwrap() {
let mut malliavin = Array1::zeros(self.n + 1);
for i in 1..=self.n {
Expand Down Expand Up @@ -95,6 +101,7 @@ impl Sampling<f64> for GBM {
/// D_r S_t = \sigma S_t * 1_[0, r](r)
///
/// The Malliavin derivate of the GBM shows the sensitivity of the stock price with respect to the Wiener process.
#[cfg(feature = "malliavin")]
fn malliavin(&self) -> Array1<f64> {
self.malliavin.lock().unwrap().as_ref().unwrap().clone()
}
Expand Down
4 changes: 2 additions & 2 deletions src/stochastic/malliavin/malliavin_1d.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub trait Malliavin {
let mut derivates = Array1::zeros(path.len() + 1);
let f_original = f(&path);

for i in 1..self.path().len() {
for i in 1..=self.path().len() {
let original_value = path[i];
path[i] += epsilon;
let f_perturbed = f(&path);
Expand All @@ -44,7 +44,7 @@ pub trait Malliavin {
let final_value = |path: &Array1<f64>| -> f64 { *path.last().unwrap() };
let f_original = final_value(&path);

for i in 1..path.len() {
for i in 1..=path.len() {
let original_value = path[i];
path[i] += epsilon;
let f_perturbed = final_value(&path);
Expand Down
4 changes: 2 additions & 2 deletions src/stochastic/malliavin/malliavin_2d.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ pub trait Malliavin2D {
let mut derivates = Array1::zeros(path.len() + 1);
let f_original = f(&path);

for i in 1..self.path().len() {
for i in 1..=self.path().len() {
let original_value = path[i];
path[i] += epsilon;
let f_perturbed = f(&path);
Expand All @@ -44,7 +44,7 @@ pub trait Malliavin2D {
let final_value = |path: &Array1<f64>| -> f64 { *path.last().unwrap() };
let f_original = final_value(&path);

for i in 1..path.len() {
for i in 1..=path.len() {
let original_value = path[i];
path[i] += epsilon;
let f_perturbed = final_value(&path);
Expand Down
8 changes: 8 additions & 0 deletions src/stochastic/process/fbm.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#[cfg(feature = "malliavin")]
use std::sync::Mutex;

use ndarray::{s, Array1};
#[cfg(feature = "malliavin")]
use statrs::function::gamma;

use crate::stochastic::{noise::fgn::FGN, Sampling};
Expand All @@ -12,7 +14,9 @@ pub struct Fbm {
pub t: Option<f64>,
pub m: Option<usize>,
pub fgn: FGN,
#[cfg(feature = "malliavin")]
pub calculate_malliavin: Option<bool>,
#[cfg(feature = "malliavin")]
malliavin: Mutex<Option<Array1<f64>>>,
}

Expand All @@ -30,7 +34,9 @@ impl Fbm {
n: params.n,
m: params.m,
fgn,
#[cfg(feature = "malliavin")]
calculate_malliavin: Some(false),
#[cfg(feature = "malliavin")]
malliavin: Mutex::new(None),
}
}
Expand All @@ -46,6 +52,7 @@ impl Sampling<f64> for Fbm {
fbm[i] += fbm[i - 1];
}

#[cfg(feature = "malliavin")]
if self.calculate_malliavin.is_some() && self.calculate_malliavin.unwrap() {
let mut malliavin = Array1::zeros(self.n + 1);
let dt = self.t.unwrap_or(1.0) / self.n as f64;
Expand Down Expand Up @@ -76,6 +83,7 @@ impl Sampling<f64> for Fbm {
/// where B^H_t is the fractional Brownian motion with Hurst parameter H in Mandelbrot-Van Ness representation as
/// B^H_t = 1 / Γ(H + 1/2) ∫_0^t (t - s)^{H - 1/2} dW_s
/// which is a truncated Wiener integral.
#[cfg(feature = "malliavin")]
fn malliavin(&self) -> Array1<f64> {
self.malliavin.lock().unwrap().clone().unwrap()
}
Expand Down
12 changes: 12 additions & 0 deletions src/stochastic/volatility/heston.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#[cfg(feature = "malliavin")]
use std::sync::Mutex;

use ndarray::Array1;
Expand Down Expand Up @@ -38,10 +39,13 @@ pub struct Heston {
/// Noise generator
pub cgns: CGNS,
/// Calculate the Malliavin derivative
#[cfg(feature = "malliavin")]
pub calculate_malliavin: Option<bool>,
/// Malliavin derivative of the volatility
#[cfg(feature = "malliavin")]
malliavin_of_vol: Mutex<Option<Array1<f64>>>,
/// Malliavin derivative of the price
#[cfg(feature = "malliavin")]
malliavin_of_price: Mutex<Option<Array1<f64>>>,
}

Expand Down Expand Up @@ -69,8 +73,11 @@ impl Heston {
use_sym: params.use_sym,
m: params.m,
cgns,
#[cfg(feature = "malliavin")]
calculate_malliavin: Some(false),
#[cfg(feature = "malliavin")]
malliavin_of_vol: Mutex::new(None),
#[cfg(feature = "malliavin")]
malliavin_of_price: Mutex::new(None),
}
}
Expand Down Expand Up @@ -104,6 +111,7 @@ impl Sampling2D<f64> for Heston {
}
}

#[cfg(feature = "malliavin")]
if self.calculate_malliavin.is_some() && self.calculate_malliavin.unwrap() {
let mut det_term = Array1::zeros(self.n + 1);
let mut malliavin = Array1::zeros(self.n + 1);
Expand Down Expand Up @@ -152,6 +160,7 @@ impl Sampling2D<f64> for Heston {
///
/// The Malliavin derivative of the 3/2 Heston model is given by
/// D_r v_t = \sigma v_t^{3/2} / 2 * exp(-(\kappa \theta / 2 + 3 \sigma^2 / 8) * v_t * dt)
#[cfg(feature = "malliavin")]
fn malliavin(&self) -> [Array1<f64>; 2] {
[
Array1::zeros(self.n + 1),
Expand Down Expand Up @@ -188,8 +197,11 @@ mod tests {
use_sym: Some(true),
m: Some(1),
cgns: CGNS::default(),
#[cfg(feature = "malliavin")]
calculate_malliavin: Some(false),
#[cfg(feature = "malliavin")]
malliavin_of_vol: Mutex::new(None),
#[cfg(feature = "malliavin")]
malliavin_of_price: Mutex::new(None),
});
let mut plot = Plot::new();
Expand Down
9 changes: 9 additions & 0 deletions src/stochastic/volatility/sabr.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#[cfg(feature = "malliavin")]
use std::sync::Mutex;

use ndarray::Array1;
Expand All @@ -16,8 +17,11 @@ pub struct Sabr {
pub t: Option<f64>,
pub m: Option<usize>,
pub cgns: CGNS,
#[cfg(feature = "malliavin")]
pub calculate_malliavin: Option<bool>,
#[cfg(feature = "malliavin")]
malliavin_of_vol: Mutex<Option<Array1<f64>>>,
#[cfg(feature = "malliavin")]
malliavin_of_price: Mutex<Option<Array1<f64>>>,
}

Expand All @@ -41,8 +45,11 @@ impl Sabr {
t: params.t,
m: params.m,
cgns,
#[cfg(feature = "malliavin")]
calculate_malliavin: Some(false),
#[cfg(feature = "malliavin")]
malliavin_of_vol: Mutex::new(None),
#[cfg(feature = "malliavin")]
malliavin_of_price: Mutex::new(None),
}
}
Expand All @@ -63,6 +70,7 @@ impl Sampling2D<f64> for Sabr {
v[i] = v[i - 1] + self.alpha * v[i - 1] * cgn2[i - 1];
}

#[cfg(feature = "malliavin")]
if self.calculate_malliavin.is_some() && self.calculate_malliavin.unwrap() {
// Only volatility Malliavin derivative is supported
let mut malliavin_of_vol = Array1::<f64>::zeros(self.n + 1);
Expand Down Expand Up @@ -93,6 +101,7 @@ impl Sampling2D<f64> for Sabr {
///
/// The Malliavin derivative of the volaility process in the SABR model is given by:
/// D_r \sigma_t = \alpha \sigma_t 1_{[0, T]}(r)
#[cfg(feature = "malliavin")]
fn malliavin(&self) -> [Array1<f64>; 2] {
[
Array1::zeros(self.n + 1),
Expand Down

0 comments on commit 7ef6dcd

Please sign in to comment.