Package: rustquant
Rust library for quantitative finance tools.:dart: I want to hit a stable and legitimatev1.0.0by the end of 2023, so any and all feedback, suggestions, or contributions are strongly welcomed!Contact:rustquantcontact@gmail.comDisclaimer: This is currently a free-time project and not a professional financial software library. Nothing in this library should be taken as financial advice, and I do not recommend you to use it for trading or making financial decisions.:newspaper: Latest featuresDownload time series data fromYahoo! Finance.Read (write) from (to).csv,.json, and.parquetfiles, usingPolarsDataFrames.Arithmetic Brownian Motion generator.Gamma, exponential, and chi-squared distributions.Forward start option pricer (Rubinstein 1990 formula).Gap option and cash-or-nothing option pricers (currently adding more binary options).Asian option pricer (closed-form solution for continuous geometric average).Heston Model option pricer (uses the tanh-sinh quadrature numerical integrator).Tanh-sinh (double exponential) quadrature for evaluating integrals.Plus other basic numerical integrators (midpoint, trapezoid, Simpson's 3/8).Characteristic functions and density functions for common distributions:Gaussian, Bernoulli, Binomial, Poisson, Uniform, Chi-Squared, Gamma, and Exponential.Table of ContentsAutomatic DifferentiationOption PricersStochastic Processes and Short Rate ModelsBondsDistributionsMathematicsHelper Functions and MacrosHow-tosReferences:link: Automatic DifferentiationCurrently only gradients can be computed. Suggestions on how to extend the functionality to Hessian matrices are definitely welcome.Reverse (Adjoint) ModeImplementation via Operator and Function Overloading.Useful when number of outputs issmallerthan number of inputs.i.e for functions $f:\mathbb{R}^n \rightarrow \mathbb{R}^m$, where $m \ll n$Forward (Tangent) ModeImplementation via Dual Numbers.Useful when number of outputs islargerthan number of inputs.i.e. for functions $f:\mathbb{R}^n \rightarrow \mathbb{R}^m$, where $m \gg n$:money_with_wings: Option PricersClosed-form price solutions:Heston ModelBarrierEuropeanGreeks/SensitivitiesLookbackAsian: Continuous Geometric AverageForward StartBasketRainbowAmericanLattice models:Binomial Tree (Cox-Ross-Rubinstein)The stochastic process generators can be used to price path-dependent options via Monte-Carlo.Monte Carlo pricing:LookbackAsianChooserBarrier:chart_with_upwards_trend: Stochastic Processes and Short Rate ModelsThe following is a list of stochastic processes that can be generated.Brownian MotionArithmetic Brownian Motion$dX_t = \mu dt + \sigma dW_t$Geometric Brownian Motion$dX_t = \mu X_t dt + \sigma X_t dW_t$Models: Black-Scholes (1973), Rendleman-Bartter (1980)Cox-Ingersoll-Ross (1985)$dX_t = (\theta - \alpha X_t)dt + \sqrt{r_t} \sigma dW_t$Ornstein-Uhlenbeck process$dX_t = \theta(\mu - X_t)dt + \sigma dW_t$Models: Vasicek (1977)Ho-Lee (1986)$dX_t = \theta_t dt + \sigma dW_t$Hull-White (1990)$dX_t = (\theta - \alpha X_t)dt + \sigma_t dW_t$Black-Derman-Toy (1990)$d\ln(X) = \left[ \theta_t + \frac{\sigma_t'}{\sigma_t}\ln(X) \right]dt + \sigma_t dW_t$$d\ln(X) = \theta_t dt + \sigma dW_t$Merton's model (1973)$X_t = X_0 + at + \sigma W_t^*$$dX_t = adt + \sigma dW_t^*$:chart_with_downwards_trend: BondsPrices:The Vasicek ModelThe Cox, Ingersoll, and Ross ModelThe Rendleman and Bartter ModelThe Ho–Lee ModelThe Hull–White (One-Factor) ModelThe Black–Derman–Toy ModelThe Black–Karasinski ModelDurationConvexity:bar_chart: DistributionsProbability density/mass functions, distribution functions, characteristic functions, etc.GaussianBernoulliBinomialPoissonUniform (discrete & continuous)Chi-SquaredGammaExponential:triangular_ruler: MathematicsNumerical Integration (needed for Heston model, for example):Tanh-Sinh (double exponential) quadratureComposite Midpoint RuleComposite Trapezoidal RuleComposite Simpson's 3/8 RuleRisk-Reward Measures (Sharpe, Treynor, Sortino, etc)Newton-RaphsonStandard Normal Distribution (Distribution/Density functions, and generation of variates)Interpolation:handshake: Helper Functions and MacrosA collection of utility functions and macros.Plot a vector.Write vector to file.Cumulative sum of vector.Linearly spaced sequence.assert_approx_equal!:heavy_check_mark: How-tosI would not recommend using RustQuant within any other libraries for some time, as it will most likely go through many breaking changes as I learn more Rust and settle on a decent structure for the library.:pray: I would greatly appreciate contributions so it can get to thev1.0.0mark ASAP.Download data from Yahoo! Finance:You can download data from Yahoo! Finance into a PolarsDataFrame.useRustQuant::data::*;usetime::macros::date;fnmain(){// New YahooFinanceData instance.// By default, date range is: 1970-01-01 to present.letmutyfd=YahooFinanceData::new("AAPL".to_string());// Can specify custom dates (optional).yfd.set_start_date(time::macros::datetime!(2019-01-010:00UTC));yfd.set_end_date(time::macros::datetime!(2020-01-010:00UTC));// Download the historical data.yfd.get_price_history();println!("Apple's quotes: {:?}",yfd.price_history)}Apple'squotes:Some(shape:(252,7)┌────────────┬───────────┬───────────┬───────────┬───────────┬────────────┬───────────┐
│date┆open┆high┆low┆close┆volume┆adjusted│
│---┆---┆---┆---┆---┆---┆---│
│date┆f64┆f64┆f64┆f64┆f64┆f64│
╞════════════╪═══════════╪═══════════╪═══════════╪═══════════╪════════════╪═══════════╡
│2019-01-02┆38.7225┆39.712502┆38.557499┆39.48┆1.481588e8┆37.994499│
│2019-01-03┆35.994999┆36.43┆35.5┆35.547501┆3.652488e8┆34.209969│
│2019-01-04┆36.1325┆37.137501┆35.950001┆37.064999┆2.344284e8┆35.670372│
│2019-01-07┆37.174999┆37.2075┆36.474998┆36.982498┆2.191112e8┆35.590965│
│…┆…┆…┆…┆…┆…┆…│
│2019-12-26┆71.205002┆72.495003┆71.175003┆72.477501┆9.31212e7┆70.798401│
│2019-12-27┆72.779999┆73.4925┆72.029999┆72.449997┆1.46266e8┆70.771545│
│2019-12-30┆72.364998┆73.172501┆71.305┆72.879997┆1.441144e8┆71.191582│
│2019-12-31┆72.482498┆73.419998┆72.379997┆73.412498┆1.008056e8┆71.711739│
└────────────┴───────────┴───────────┴───────────┴───────────┴────────────┴───────────┘)Read/write data:useRustQuant::data::*;fnmain(){// New `Data` instance.letmutdata=Data::new(format:DataFormat::CSV,// Can also be JSON or PARQUET.path:String::from("./file/path/read.csv"))// Read from the given file.data.read().unwrap();// New path to write the data to.data.path=String::from("./file/path/write.csv")data.write().unwrap();println!("{:?}",data.data)}Compute gradients:useRustQuant::autodiff::*;fnmain(){// Create a new Tape.lett=Tape::new();// Assign variables.letx=t.var(0.5);lety=t.var(4.2);// Define a function.letz=x*y+x.sin();// Accumulate the gradient.letgrad=z.accumulate();println!("Function = {}",z);println!("Gradient = {:?}",grad.wrt([x,y]));}Compute integrals:useRustQuant::math::*;fnmain(){// Define a function to integrate: e^(sin(x))fnf(x:f64)->f64{(x.sin()).exp()}// Integrate from 0 to 5.letintegral=integrate(f,0.0,5.0);// ~ 7.18911925println!("Integral = {}",integral);}Price options:useRustQuant::options::*;fnmain(){letVanillaOption=EuropeanOption{initial_price:100.0,strike_price:110.0,risk_free_rate:0.05,volatility:0.2,dividend_rate:0.02,time_to_maturity:0.5,};letprices=VanillaOption.price();println!("Call price = {}",prices.0);println!("Put price = {}",prices.1);}Generate stochastic processes:useRustQuant::stochastics::*;fnmain(){// Create new GBM with mu and sigma.letgbm=GeometricBrownianMotion::new(0.05,0.9);// Generate path using Euler-Maruyama scheme.// Parameters: x_0, t_0, t_n, n, sims, parallel.letoutput=(&gbm).euler_maruyama(10.0,0.0,0.5,10,1,false);println!("GBM = {:?}",output.trajectories);}:book: References:John C. Hull -Options, Futures, and Other DerivativesDamiano Brigo & Fabio Mercurio -Interest Rate Models - Theory and Practice (With Smile, Inflation and Credit)Paul Glasserman -Monte Carlo Methods in Financial EngineeringAndreas Griewank & Andrea Walther -Evaluating Derivatives - Principles and Techniques of Algorithmic DifferentiationSteven E. Shreve -Stochastic Calculus for Finance II: Continuous-Time ModelsEspen Gaarder Haug -Option Pricing FormulasAntoine Savine -Modern Computational Finance: AAD and Parallel Simulations