Figure out fast_io
LinkedIn | Website | GitHub | Contact Info
-
II: Implementation Details
-
III: Usage, Installation & Getting Started
File Hierarchy
Current Tech Stack [view more details]
black-scholes-cpp
is a comprehensive C++ program designed to calculate the price of European options using the Black-Scholes formula.
Going beyond the basic implementation, this project showcases an array of advanced features and enhancements, demonstrating a deep understanding of mathematical finance, numerical methods, and programming best practices.
- Input Modes: The program supports various input modes to cater to diverse user needs.
- User Input: Users can interactively input option parameters through a command-line interface.
- File Input: Option parameters can be read from external files, providing flexibility and ease of data input.
- Database Input: Retrieve option parameters from a database, enabling integration with data storage systems.
- Market Data Feeds/APIs: Fetch real-time market data from external sources or APIs, ensuring dynamic and up-to-date pricing information.
- Option Greeks Calculation: The implementation includes a sophisticated module for calculating option Greeks, providing insights into the sensitivity of option prices to various factors.
- Delta: Measures the sensitivity of the option price to changes in the underlying asset price.
- Gamma: Reflects the rate of change of delta concerning changes in the underlying asset price.
- Vega: Captures the sensitivity of the option price to changes in volatility.
- Theta: Represents the time decay of the option price.
- Rho: Illustrates the sensitivity of the option price to changes in the risk-free interest rate.
- Implied Volatility Calculation:
A function to calculate implied volatility, an important parameter in option pricing.
- Heston Model Integration:
black-scholes-cpp
is enhanced to incorporate equations from the Heston model, allowing for a more nuanced understanding of volatility dynamics.
- Calibration Procedure for Heston Model:
The implementation includes a robust calibration procedure to estimate Heston model parameters based on market data.
- Calibration ensures that the model aligns with observed market prices, enhancing its predictive power.
- Volatility Surface Calculation:
black-scholes-cpp
calculates the implied volatility surface using the Heston model, offering a comprehensive view of implied volatilities across various strike prices and maturities.
- Monte Carlo Simulation:
A sophisticated Monte Carlo simulation is implemented to generate random paths for both the underlying asset price and volatility based on the Heston model.
- This feature adds a layer of realism to the pricing model.
- Historical Volatility Analysis:
Functionality is incorporated to calculate historical volatility based on historical price data.
- This analysis provides insights into the historical behavior of the underlying asset's volatility.
- Sensitivity Analysis:
black-scholes-cpp
extends its capabilities to perform sensitivity analysis using the Heston model.
- Exploring the impact of varying input parameters, such as mean reversion speed, volatility of volatility, and correlation, allows users to assess the model's sensitivity to different market conditions.
- Visualizations:
To enhance user understanding,
black-scholes-cpp
incorporates visualizations using plotting libraries. Users can intuitively interpret option prices, implied volatility surfaces, Greeks, and other relevant metrics.
-
Figure out how to rewrite Makefile✓ -
Re-install libcURL/cURL-openssl via Homebrew (incompatible w/ arm64?)✓ -
Review MAKEFILE documentation: esp✓$(LIBS), $ (LDFLAGS), $(LXXFLAGS). -
From CLI, understand exporting $(PATH)(s) to libcURL in root/.zshrc.✓ -
Fix Git VS issues w/ SSH/GPG keys (ed25519, RSA) and/or authentication w/ fine-grained PACs. ✓ -
Finalize high-level project structure (i.e. where driver goes, basic .cpp/.h division, basic class (and other high-level data structure) organization based on functionality).✓ -
Handle all inputModes.
- User Input: Done, not tested.
- File Input: Done, not tested.
- Database Input: Haven't started, but know to use SQLite.
- External market data feeds / APIs: Haven't started, but have cURL set up. Also using Alpha Vantage Rapid API and already have private key. "Just" need to figure out configuration.
-
Begin TESTING AND DEBUGGING!
-
Figure out
CMake
+Ninja
+Google Test
stack- POSIX, multi-threading, parallelization, etc.
-
Optimizing code.
- Obv some stuff will optimize a lot and take barely any time. Some stuff will make zero-to-nil difference and take hours. Gotta prioritize.
-
- Optimization ideas listed below, but some of it is obvious throughout code.
-
Figure out what additional features to implement.
-
Option Greeks (calculating, setting, getting)✓ -
Enhanced Black-Scholes pricing models incorporating option Greeks (constructor, calculating, setting, getting)✓ -
Enhanced Black-Scholes pricing models incorporating implied volatility (constructor, calculating, setting, getting)✓
- Heston Model
- Enhanced Black-Scholes pricing models incorporating Heston model equations
- Calibration procedure to estimate the Heston model parameters based on market data
- Volatility surface calculation: calculate the implied volatility surface using the Heston Model
- By solving the Heston model equations and comparing the model prices with market prices, you can derive the implied volatility at different strikes and maturities, thus constructing the volatility surface.
- Greeks calculation: Enhance your project to calculate option Greeks, such as delta, gamma, vega, theta, and rho, using the Heston Model.
- These measures provide valuable insights into the sensitivity of option prices to changes in underlying factors.
- You can use finite difference methods or other numerical techniques to estimate these sensitivities based on the Heston model equations.
- Monte Carlo Simulation: Implement Monte Carlo simulation to generate random paths for both the underlying asset price and volatility based on the Heston model.
- Historical Volatility Analysis: Incorporate functionality to calculate historical volatility based on historical price data.
- This can be useful for comparing the implied volatility from the Heston model with realized historical volatility.
- You can calculate rolling or weighted average volatilities to capture different time horizons.
- Sensitivity Analysis: Extend your project to perform sensitivity analysis using the Heston model.
- Explore the impact of varying input parameters, such as mean reversion speed, volatility of volatility, and correlation, on option prices and Greeks.
- This analysis can help assess the model's sensitivity to different market conditions.
- Visualizations: Enhance your project by adding visualizations to present the results more intuitively.
- Plot option prices, implied volatility surfaces, Greeks, or other relevant metrics to provide a graphical representation of the Heston model outputs.
- Divided Difference approach
-
-
Perpetual American Options
-
Matrix Math
C++
remains the primary language for its efficiency and performance in numerical computations.
CMake
facilitates the building and compilation of thisC++
project.- It's widely used and supports various platforms.
Ninja
is a small build system automation tool forC++
andPython
, used as an alternative forMake
.- In conjunction with
CMake
,Ninja
runs builds as fast as possible.
- Design a RESTful API to expose your option pricing functionalities.
- This allows for easy integration with different platforms and technologies.
Boost
C++ Libraries:
Boost
libraries forC++
offer utilities and functionalities that can enhance your project.
QuantLib
(Optional):
QuantLib
provides tools for quantitative finance, including derivative pricing and risk management.
Google Test
(for Unit Testing):
Google Test
is a widely used testing framework forC++
.
- It supports test fixtures, test discovery, and various assertions.
Google Mock
(for Mocking):
Google Mock
is a framework for creating mock classes and performing mock-based testing.
Clang
Static Analyzer (Optional):
Clang Static Analyzer
is a powerful tool for static code analysis, helping to identify potential issues in the code.
SQLite
is a lightweight, embedded database that can be used for local storage of option parameters.
- A
C++
library for creating HTTP servers, enabling communication with your application via HTTP.
spdlog
is a fastC++
logging library that can be used for error handling and logging.
- It provides various logging sinks and is easy to configure.
Swagger
/OpenAPI
(Optional):
Swagger
orOpenAPI
can be used to document your RESTful API. It provides a standardized way to describe and document APIs.
Doxygen
:
Doxygen
can generate documentation from your code comments. It's especially useful for documenting functions, classes, and project structure.
- Web Interface (HTML/CSS/JavaScript):
- If you plan to create a web-based interface for interacting with your application, standard web technologies can be used.
- Setting up continuous integration ensures that your project is automatically built and tested whenever changes are pushed to the repository.
- Use a dependency manager like
Conan
orvcpkg
to manage external libraries and ensure consistent builds across different environments.
Docker
can be used to containerize your application, making it easy to deploy and run in different environments.
- Study Black-Scholes Model (5 hours):
- Dive into academic papers, online resources, and books to understand the mathematical foundations of the Black-Scholes model.
- Familiarize yourself with the Black-Scholes formula, its assumptions, and risk-neutral pricing.
- Explore Additional Concepts (5 hours):
- Delve into option Greeks (delta, gamma, vega, theta, rho), implied volatility, and the Heston model.
- Gather insights from advanced topics such as calibration procedures, Monte Carlo simulation, and sensitivity analysis.
- Resource Review (5 hours):
- Explore online tutorials, courses, and books recommended in the project description.
- Investigate GitHub repositories like QuantLib for practical implementations.
- Summarize key learnings and resources for quick reference.
- Define Project Structure (3 hours):
- Plan a directory structure for your project (e.g., src, include, test, docs).
- Decide on file naming conventions and coding standards.
- Identify Main Components (3 hours):
- List the main components/modules required for the Black-Scholes model, option Greeks, and Heston model integration.
- Define interfaces between components.
- Setup Version Control (4 hours):
- Initialize a Git repository for version control.
- Create a .gitignore file to exclude unnecessary files.
- Commit the initial project structure.
- Implement Black-Scholes Basics (15 hours):
- Implement the Black-Scholes formula for European options in the "src" directory.
- Develop necessary formulas and calculations for option pricing.
- User Input Handling (8 hours):
- Implement user input functionality for option parameters.
- Validate and sanitize user inputs to ensure correctness.
- File Input Handling (7 hours):
- Develop functions to read option parameters from external files (e.g., CSV).
- Handle errors gracefully and provide meaningful error messages.
- Option Greeks Calculation (15 hours):
- Extend the implementation to calculate option Greeks: delta, gamma, vega, theta, and rho.
- Ensure accurate and efficient calculations.
- Enhanced Black-Scholes Pricing Models (15 hours):
- Implement implied volatility calculation in the Black-Scholes model.
- Incorporate Heston model equations for pricing.
- Calibration Procedure (10 hours):
- Develop a calibration procedure to estimate Heston model parameters based on market data.
- Implement optimization algorithms (e.g., gradient descent) for parameter fine-tuning.
- Volatility Surface Calculation (15 hours):
- Implement functions to calculate the implied volatility surface using the Heston model.
- Visualize the surface using plotting libraries (e.g., Matplotlib).
- Monte Carlo Simulation (10 hours):
- Develop Monte Carlo simulation for generating random paths based on the Heston model.
- Ensure realistic simulations for both asset price and volatility.
- Historical Volatility Analysis (10 hours):
- Integrate functionality to calculate historical volatility based on historical price data.
- Implement data analysis tools for insights.
- Unit Testing (10 hours):
- Implement comprehensive unit tests for each component.
- Use a testing framework (e.g., Google Test) to automate tests.
- Validation (10 hours):
- Validate the entire program against established pricing models.
- Compare results with known Black-Scholes and Heston model outcomes.
- Create README and Documentation (10 hours):
- Document the project overview, features, and usage in the README.
- Write detailed documentation for each feature, including examples.
- Code Comments (5 hours):
- Add comments to your code for clarity and context.
- Ensure that the codebase is well-documented for future reference.
- Optimization (5 hours):
- Optimize the performance of the option pricing calculations.
- Document performance improvements achieved.
- Visualizations (10 hours):
- Enhance the project with visualizations using plotting libraries.
- Plot option prices, implied volatility surfaces, Greeks, or other relevant metrics.
- Finalize Documentation (5 hours):
- Review and finalize all project documentation.
- Ensure consistency and completeness.
NEVER
FILL THIS SECTION OUT LATERRRR
LATER
IDFK
PROBABLY NONE LEFT
black-scholes-cpp
mandates:
- A functional C++ compiler compatible with C++20,
- required libraries installed (e.g., CURL for API access, SQLite for database interactions),
GoogleTest
mocking and unit-testing library installed,
- Use
brew install googletest
to install to your device via Homebrew.
- the
Threads
package to handle threading-related functionality,
- Use
brew install --cask threads
to install to your device via Homebrew.
- the ability to build, run, and debug using
CMake
of version3.26
or higher, and - the
Ninja
build system.
- Via Homebrew, install with the following command:
brew install ninja
.
- Clone the repository:
git clone https://github.com/lyndskg/black-scholes-cpp.git
cd black-scholes-cpp
- Build the project:
cmake -Bbuild-cmake -H. -GNinja
cd build-cmake
- Run the program:
cmake --build .
- Explore the different features and input modes provided by the program.
- Try out the model interactively via CLI, or stream in real data feeds from live API streams.
- To clean the project, access the current build directory:
pwd
(Make sure you're inbuild-cmake
; if not,cd build-cmake
)ninja -t clean
- Repeat step 3 as needed.
- Algorithmic trading strategy formulation, backtesting, and refinement.
- Real-time market data monitoring and informed decision-making.
- Portfolio analysis and optimization for traders and investors.
WRITE HERE
- Operating System: macOS Ventura (version 14.3.1)
- Architecture: Apple arm64
We welcome contributions from the community to help improve black-scholes-cpp
and make it even better.
- Contribute: Don't.
- Donate: DON'T!
WRITE HERE
Lyndsey Gu - @lyndskg - lyndsey.gu@gmail.com
Project Link: https://github.com/lyndskg/black-scholes-cpp
Put Stuff Here
Resources:
- Online tutorials:
- Online resources:
- GitHub Repos:
- CMake & Google Test framework: Jamagas, TimothyHelton, DavidAg, Pyarmak, PhDP, SRombauts, pandreidoru
- Official CMake Git
- Reading input from database:
SQLite
- Reading input from file: Get
.CSV
samples fromKaggle
to test. - Reading input from external market feeds / APIs. Retrieve Alpha Vantage Rapid API Private Key and finish configuration.
- Testing and debugging.
- Finishing
optionGreeksModel
class implementations. - Implementing more advanced functionalities: implied volatility (IV), Heston model, Monte Carlo, etc.
- Check all
#includes
and using directives. - In function
double blackScholesModel::calculateOptionPrice()
, can use if-elif-else statement, switch statement, or ternary operator foroptionType
. - In class
blackScholesModel
,optionType
(i.e. Call vs. Put) can be represented asenum
type orchar
. If latter, does it need to be initialized in ctor? - In function
double blackScholesModel::normalCDF()
, should the result be returned via ternary operator or if-else statement? - In the main driver function in
main.cpp
, should an instance of blackScholesModel using the custom ctor initializing all pricing input variables be used instead of having to use the same getter methods in the driver itself? - In function
double blackScholesModel::normalCDF()
, a more efficient approximation can be used. - In function
inputReader::readInputFromUser()
, should validation be accomplished using its two current helper functions or viavalidateAndSetInputValues()
?
- In function
Program::get_options()
, in the default case (i.e. no options are flagged), should figure out how to print invalid command-line argument (int option
) tostderr
(cerr
) for debugging purposes.
dr-liangma/BlackScholes_MonteCarlo
- Monte Carlo Methods applied to the Black-Scholes financial market model yogesh-vishwakarma/Stock-market-prediction-using-Monte-Carlo-simulation-Black-Scholes
- Stock Market Forecasting using Parallel Monte-Carlo Simulations and Machine Learning AiglonDore/black-scholes OskarMai/BSOptionPricer nburma01/QuantLibTest LittleQuant/DerivativePricing
- Black Scholes derivatives pricer implemented following and referencing the C++ Design Patterns and Derivatives Pricing 2nd Edition by Mark Joshi.
- Personal project to write a dynamic library for pricing financial derivatives using Monte Carlo methods under the Black Scholes model. redbzi/MC
- Monte-Carlo simulations around the Black-Scholes and Heston models. oguzaras/-FFTBlackScholes
- Fast Fourier Transform Black-Scholes