Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
80 commits
Select commit Hold shift + click to select a range
63f3bbe
Add OptionStyle to handle Call and Put payoffs
joaquinbejar Aug 4, 2024
d3fd1fe
Refactor OptionType with detailed documentation
joaquinbejar Aug 4, 2024
a432801
Improve logo display and update README with recent changes
joaquinbejar Aug 4, 2024
848001a
Adjust logo dimensions in README.md
joaquinbejar Aug 4, 2024
52e22bb
Update logo height in README.md
joaquinbejar Aug 4, 2024
712b672
Add binomial tree pricing and visualization.
joaquinbejar Aug 5, 2024
da0431f
Add utility functions and refactor binomial model
joaquinbejar Aug 5, 2024
908087b
Resize binomial tree plot and update drawing elements.
joaquinbejar Aug 5, 2024
c9790e1
Merge pull request #2 from joaquinbejar/feature/draw-binomial-tree
joaquinbejar Aug 5, 2024
20296a2
Update calculation methods and add unit tests
joaquinbejar Aug 5, 2024
ea906b2
Add calculate_option_node_value function
joaquinbejar Aug 5, 2024
1a8c45e
Refactor payoff calculation in binomial model
joaquinbejar Aug 6, 2024
2f84905
Refactor and remove commented-out code in utils.rs
joaquinbejar Aug 6, 2024
c415542
Add detailed doc comments to pricing utility functions
joaquinbejar Aug 6, 2024
b3bb523
Refactor option node value calculation and add new tests
joaquinbejar Aug 6, 2024
a74485b
Refactor option node value calculation
joaquinbejar Aug 6, 2024
a4ffff5
Refactor payoff function to use PayoffInfo struct
joaquinbejar Aug 7, 2024
fc30327
Add Clone derive to enums and update Payoff logic
joaquinbejar Aug 7, 2024
8b1bee3
Refactor payoff calculation to use PayoffInfo struct
joaquinbejar Aug 7, 2024
f7ab69f
Refactor `PayoffInfo` structure.
joaquinbejar Aug 7, 2024
56b33bc
Add detailed documentation for `PayoffInfo` struct
joaquinbejar Aug 7, 2024
7e22451
Refactor common payoff logic into standard function
joaquinbejar Aug 8, 2024
6ded181
Add unit tests for various option payoff calculations
joaquinbejar Aug 9, 2024
c4f94d2
Format and implement Default for PayoffInfo
joaquinbejar Aug 9, 2024
140fc68
Refactor payoff calculation for option types.
joaquinbejar Aug 9, 2024
b4318a9
Add Black-Scholes model and remove current price from options
joaquinbejar Aug 11, 2024
892d0a1
Refactor Black-Scholes model and enhance `utils` documentation.
joaquinbejar Aug 11, 2024
52f3560
Refactor Black-Scholes model functions for clarity
joaquinbejar Aug 11, 2024
22834ce
Refactor pricing module and comment out unused dependencies
joaquinbejar Aug 11, 2024
295b9e3
Add dividend_yield to Options and implement Greek equations
joaquinbejar Aug 11, 2024
27287a7
Add unit tests for Greeks calculations
joaquinbejar Aug 12, 2024
3c07bda
Refactor expiration date handling in options model
joaquinbejar Aug 13, 2024
d3795c4
Refactor `Options` struct initialization.
joaquinbejar Aug 13, 2024
3432cef
Add new examples and refine models for financial calculations
joaquinbejar Aug 14, 2024
2a46d7b
Add tests for expiration date handling and update Black-Scholes model
joaquinbejar Aug 14, 2024
3e4e47e
Refactor Black-Scholes implementation and add new tests
joaquinbejar Aug 14, 2024
30e23b6
Add volatility module
joaquinbejar Aug 14, 2024
03b88c5
Add Monte Carlo option pricing module
joaquinbejar Aug 14, 2024
583941f
Add payoff calculation and Wiener process increment
joaquinbejar Aug 15, 2024
7269607
Add spot prices, min, and max for various options
joaquinbejar Aug 15, 2024
d66768f
Refactor Options struct and related methods for exotic options
joaquinbejar Aug 15, 2024
45b8444
Refactor Monte Carlo option pricing function and add tests
joaquinbejar Aug 15, 2024
54444df
Add volatility utility functions and tests
joaquinbejar Aug 15, 2024
645905e
Add Greeks calculation methods and implied volatility utility.
joaquinbejar Aug 15, 2024
1053feb
Add time_value computation for options
joaquinbejar Aug 15, 2024
fac5561
Simplify comments in volatility example
joaquinbejar Aug 15, 2024
bd7a257
Add PnL calculation module and introduce the premium attribute
joaquinbejar Aug 16, 2024
966c6d0
Refactor P&L calculations and add tests
joaquinbejar Aug 16, 2024
b49fe46
Refactor option payoff logic and fix formatting issues
joaquinbejar Aug 16, 2024
06d752d
Add bilinear interpolation to volatility surface utility
joaquinbejar Aug 16, 2024
7e5383a
Format multiline code blocks for readability
joaquinbejar Aug 16, 2024
15428fe
Remove redundant comments from volatility_utils.rs
joaquinbejar Aug 16, 2024
ce7ae22
Refactor uncertainty bounds calculation, add comprehensive tests
joaquinbejar Aug 16, 2024
15e07da
Remove obsolete TODO comments in binomial model tests
joaquinbejar Aug 16, 2024
33f3695
Add modular structure for surface operations
joaquinbejar Aug 16, 2024
9eece72
Add models and structures for surface types and configurations
joaquinbejar Aug 16, 2024
adf6525
Add zero volatility handling and probability calculation function
joaquinbejar Aug 18, 2024
e683fda
Refactor volatility handling and add zero expiration tests
joaquinbejar Aug 18, 2024
fe7ecb9
Use ZERO constant instead of 0.0 for clarity
joaquinbejar Aug 18, 2024
c5a3c63
Refactor: Replace magic number 0.0 with defined constant ZERO
joaquinbejar Aug 18, 2024
2a5042e
Add #[allow(dead_code)] attribute to suppress warnings
joaquinbejar Aug 18, 2024
b823a65
Remove 'premium' field from Options struct
joaquinbejar Aug 18, 2024
dc1c328
Refactor PNL calculation methods and update tests
joaquinbejar Aug 19, 2024
4af118d
Ensure positive premium values in Position struct
joaquinbejar Aug 19, 2024
9713730
Refactor: Replace numeric zero with named constant `ZERO`
joaquinbejar Aug 19, 2024
95c870a
Add PnL struct and PnLCalculator trait
joaquinbejar Aug 19, 2024
c05ee9d
Add Telegraph process for pricing
joaquinbejar Aug 19, 2024
6486f32
Refactor random number generation in telegraph.rs
joaquinbejar Aug 19, 2024
aa6f68f
Refactor telegraph and add unit tests
joaquinbejar Aug 20, 2024
15c8c35
Add Display and Debug implementations for options
joaquinbejar Aug 20, 2024
d5a943c
Refactor imports and clean up formatting
joaquinbejar Aug 20, 2024
4e1aad4
Refactor telegraph pricing and update tests
joaquinbejar Aug 20, 2024
02694d6
Add PnL calculation for options and positions
joaquinbejar Aug 20, 2024
87fc5b5
Add graphing capability for options
joaquinbejar Aug 20, 2024
d648bb2
Make `position` module public and enhance PnL calculation
joaquinbejar Aug 20, 2024
eedd94a
Refactor position graph rendering logic
joaquinbejar Aug 20, 2024
83e49a8
Improve break-even calculation and expiration format
joaquinbejar Aug 21, 2024
ff511bf
Add Debug and Display implementations for Position
joaquinbejar Aug 21, 2024
fd25c6d
Enhance PNL graph with color-coded segments and adjustments
joaquinbejar Aug 21, 2024
8c7a3f5
Adjust PNL computation and refine chart rendering
joaquinbejar Aug 21, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 25 additions & 24 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,32 +21,33 @@ exclude = [
"Cargo.lock"
]

[toolchain]
channel = "nightly"

[dependencies]
tokio = { version = "1.39.2", features = ["rt", "rt-multi-thread", "macros", "time", "signal"] }
futures-util = "0.3.30"
dotenv = "0.15.0"
thiserror = "1.0.63"
serde_json = "1.0.121"
serde = { version = "1.0.204", features = ["derive"] }
redis = { version = "0.26.0", features = ["cluster", "cluster-async", "aio", "async-std-comp"] }
mongodb-aggregations = "0.1.0"
mongodb = { version = "=2.8.2" }
futures = "0.3.30"
#tokio = { version = "1.39.2", features = ["rt", "rt-multi-thread", "macros", "time", "signal"] }
#futures-util = "0.3.30"
#dotenv = "0.15.0"
#thiserror = "1.0.63"
#serde_json = "1.0.121"
#serde = { version = "1.0.204", features = ["derive"] }
#redis = { version = "0.26.0", features = ["cluster", "cluster-async", "aio", "async-std-comp"] }
#mongodb-aggregations = "0.1.0"
#mongodb = { version = "=2.8.2" }
#futures = "0.3.30"
chrono = "0.4.38"
regex = "1.10.5"
rand = "0.8.5"
sha2 = "0.10.8"
reqwest = { version = "0.12.5", features = ["json"] }
anyhow = "1.0.86"
tracing = "0.1.40"
tracing-subscriber = "0.3.18"
async-trait = "0.1.80"
sqlx = { version = "0.8.0", features = ["runtime-tokio", "macros", "mysql"] }
chrono-tz = "0.9.0"
#regex = "1.10.5"
#rand = "0.8.5"
#sha2 = "0.10.8"
#reqwest = { version = "0.12.5", features = ["json"] }
#anyhow = "1.0.86"
#tracing = "0.1.40"
#tracing-subscriber = "0.3.18"
#async-trait = "0.1.80"
#sqlx = { version = "0.8.0", features = ["runtime-tokio", "macros", "mysql"] }
#chrono-tz = "0.9.0"
approx = "0.5.1"
plotters = "0.3"
statrs = "0.17.1"
rayon = "1.10.0"
rand = "0.8.5"


[dev-dependencies]
Expand All @@ -59,7 +60,7 @@ lazy_static = "1.5.0"

[[example]]
name = "example"
path = "examples/example.rs"
path = "examples/volatility.rs"

[[test]]
name = "tests"
Expand Down
Binary file added Draws/Binomial Tree/binomial_tree.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Draws/Options/intrinsic_value_chart.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Draws/Position/pnl_at_expiration_chart.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
39 changes: 37 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@

![OptionStratLib](doc/images/logo.png)
<div style="text-align: center;">
<img src="doc/images/logo.png" alt="OptionStratLib" style="width: 100%; height: 200px;">
</div>

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:

Expand All @@ -19,4 +21,37 @@ Risk analysis tools
Backtesting capabilities
Performance visualization

Empower your options trading with OptionStratLib – the all-in-one solution for option strategy development and analysis.
Empower your options trading with OptionStratLib – the all-in-one solution for option strategy development and analysis.


## Recent Updates

### Implementation of the Binomial Model for Option Pricing

We have successfully implemented a robust binomial model for option pricing. This implementation includes:

1. **Flexible Option Types**: Our model now supports various option types including European, American, and exotic options like Asian, Barrier, and more.

2. **Comprehensive Pricing Parameters**: We've introduced a `BinomialPricingParams` struct that encapsulates all necessary parameters for option pricing, including asset price, volatility, interest rate, strike price, time to expiry, number of steps, option type, option style (Call/Put), and trade side (Long/Short).

3. **Efficient Pricing Algorithm**: The `price_binomial` function implements an efficient binomial tree algorithm for option pricing. It handles special cases such as zero time to expiry and zero volatility.

4. **Support for Both Call and Put Options**: Our implementation allows pricing of both call and put options through the `OptionStyle` enum.

5. **Long and Short Positions**: The model accounts for both long and short positions in options through the `Side` enum.

6. **Payoff Trait**: We've introduced a `Payoff` trait that allows for easy extension to new option types in the future.

7. **Comprehensive Test Suite**: We've developed a suite of unit tests to ensure the accuracy of our pricing model under various scenarios, including edge cases.

8. **Code Optimization**: We've addressed Clippy warnings and optimized our code for better performance and readability.

9. **Detailed Documentation**: We've added comprehensive documentation to our main pricing function, explaining its usage, parameters, and providing examples.

### Future Work

- Implement additional exotic option types
- Enhance the model to handle dividends
- Develop a user-friendly interface for easy option pricing
- Implement additional pricing models (e.g., Black-Scholes, Monte Carlo) for comparison

37 changes: 37 additions & 0 deletions examples/option_graph.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/******************************************************************************
Author: Joaquín Béjar García
Email: jb@taunais.com
Date: 20/8/24
******************************************************************************/
use optionstratlib::model::option::Options;
use optionstratlib::model::types::{ExpirationDate, OptionStyle, OptionType, Side};
use optionstratlib::visualization::utils::Graph;
use std::error::Error;

fn create_sample_option() -> Options {
Options::new(
OptionType::European,
Side::Long,
"AAPL".to_string(),
100.0,
ExpirationDate::Days(30.0),
0.2,
1,
105.0,
0.05,
OptionStyle::Call,
0.0,
None,
)
}
fn main() -> Result<(), Box<dyn Error>> {
let option = create_sample_option();

// Define a range of prices for the graph
let price_range: Vec<f64> = (50..150).map(|x| x as f64).collect();

// Generate the intrinsic value graph
option.graph(&price_range, "Draws/Options/intrinsic_value_chart.png")?;

Ok(())
}
37 changes: 37 additions & 0 deletions examples/position_graph.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
/******************************************************************************
Author: Joaquín Béjar García
Email: jb@taunais.com
Date: 20/8/24
******************************************************************************/
use chrono::Utc;
use optionstratlib::model::option::Options;
use optionstratlib::model::position::Position;
use optionstratlib::model::types::{ExpirationDate, OptionStyle, OptionType, Side};
use optionstratlib::visualization::utils::Graph;
use std::error::Error;

fn create_sample_option() -> Options {
Options::new(
OptionType::European,
Side::Long,
"AAPL".to_string(),
100.0,
ExpirationDate::Days(30.0),
0.2,
10,
105.0,
0.05,
OptionStyle::Call,
0.0,
None,
)
}
fn main() -> Result<(), Box<dyn Error>> {
let position = Position::new(create_sample_option(), 5.71, Utc::now(), 1.0, 1.0);

let price_range: Vec<f64> = (50..150).map(|x| x as f64).collect();

position.graph(&price_range, "Draws/Position/pnl_at_expiration_chart.png")?;

Ok(())
}
66 changes: 66 additions & 0 deletions examples/risk-free-rate.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
use optionstratlib::greeks::utils::big_n;

fn black_scholes_call(s: f64, k: f64, t: f64, r: f64, sigma: f64) -> f64 {
let d1 = (s.ln() / k + (r + sigma * sigma / 2.0) * t) / (sigma * t.sqrt());
let d2 = d1 - sigma * t.sqrt();

s * big_n(d1) - k * (-r * t).exp() * big_n(d2)
}

fn implied_risk_free_rate(
s: f64,
k: f64,
t: f64,
sigma: f64,
market_price: f64,
epsilon: f64,
max_iterations: usize,
) -> Option<f64> {
let mut r_low = -1.0;
let mut r_high = 1.0;

for _ in 0..max_iterations {
let r_mid = (r_low + r_high) / 2.0;
let price = black_scholes_call(s, k, t, r_mid, sigma);

if (price - market_price).abs() < epsilon {
return Some(r_mid);
}

if price > market_price {
r_high = r_mid;
} else {
r_low = r_mid;
}
}

None
}

fn main() {
let s = 2476.6; // Current gold price
let k = 2470.0; // Strike price
let t = 3.0 / 365.0; // Time to expiration in years
let sigma = 0.216875; // Volatility
let market_price = 22.5; // Market price of the option
let epsilon = 0.0001; // Desired precision
let max_iterations = 1000;

match implied_risk_free_rate(s, k, t, sigma, market_price, epsilon, max_iterations) {
Some(r) => println!("The implied risk-free rate is: {:.4}%", r * 100.0),
None => println!("Could not converge to a solution"),
}

// Test with the other set of parameters
let k2 = 2390.0;
let sigma2 = 0.199375;
let market_price2 = 87.8;

match implied_risk_free_rate(s, k2, t, sigma2, market_price2, epsilon, max_iterations) {
Some(r) => println!(
"The implied risk-free rate for the second set is: {:.4}%",
r * 100.0
),
None => println!("Could not converge to a solution for the second set"),
}
}
Loading