Skip to content

A UI-friendly program calculating Black-Scholes options pricing with advanced algorithms incorporating option Greeks, IV, Heston model, etc. Reads input from users, files, databases, and real-time, external market feeds (e.g. APIs).

Notifications You must be signed in to change notification settings

lyndskg/black-scholes-cpp

Repository files navigation

black-scholes-cpp

* a C++ program that calculates the price of European options using the Black-Scholes formula *

SIDE-NOTE: IS BACKTESTING THAT BIG OF A DEAL IN THE FUTURE?

Figure out fast_io

LinkedIn | Website | GitHub | Contact Info

Table of Contents

File Hierarchy
Current Tech Stack   [view more details]

Progress   [view our progress, logs, and other documentation]

Note: Last updated: 8/9/23

  1. 8/9/23

Project Overview

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.

 


Key Features:

  1. 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.
  1. 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.
  1. Implied Volatility Calculation:

A function to calculate implied volatility, an important parameter in option pricing.

  1. Heston Model Integration:

black-scholes-cpp is enhanced to incorporate equations from the Heston model, allowing for a more nuanced understanding of volatility dynamics.

  1. 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.
  1. 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.

  1. 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.
  1. 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.
  1. 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.
  1. 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.

 

(back to top)


Current Notes and/or Issues:

  • 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

(back to top)


Technologies and Programming Languages

Programming Language: C++

  • C++ remains the primary language for its efficiency and performance in numerical computations.

Build System: CMake and Ninja

  • CMake facilitates the building and compilation of this C++project.
  • It's widely used and supports various platforms.
  • Ninja is a small build system automation tool for C++ and Python, used as an alternative for Make.
  • In conjunction with CMake, Ninja runs builds as fast as possible.

Backend: RESTful API (Optional):

  • Design a RESTful API to expose your option pricing functionalities.
  • This allows for easy integration with different platforms and technologies.

Libraries and Frameworks:

  • Boost C++ Libraries:
  • Boost libraries for C++ offer utilities and functionalities that can enhance your project.
  • QuantLib (Optional):
  • QuantLib provides tools for quantitative finance, including derivative pricing and risk management.

Testing, Mocking, and Quality Assurance:

  • Google Test (for Unit Testing):
  • Google Test is a widely used testing framework for C++.
  • 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.

Database: SQLite

  • SQLite is a lightweight, embedded database that can be used for local storage of option parameters.

Web APIs and HTTP Communication: cpp-httplib (for HTTP server)

  • A C++ library for creating HTTP servers, enabling communication with your application via HTTP.

Error Handling and Logging: spdlog

  • spdlog is a fast C++ logging library that can be used for error handling and logging.
  • It provides various logging sinks and is easy to configure.

API Documentation:

  • Swagger/OpenAPI (Optional):
  • Swagger or OpenAPI 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.

Frontend (Optional):

  • 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.

Continuous Integration: Travis CI or GitHub Actions

  • Setting up continuous integration ensures that your project is automatically built and tested whenever changes are pushed to the repository.

Dependency Management: Conan or vcpkg

  • Use a dependency manager like Conan or vcpkg to manage external libraries and ensure consistent builds across different environments.

Containerization (Optional): Docker

  • Docker can be used to containerize your application, making it easy to deploy and run in different environments.

Roadmap

Phase 1: Research and Understanding (Estimated Time: 15 hours)

  1. 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.
  1. 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.
  1. 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.

Phase 2: Project Setup and Planning (Estimated Time: 10 hours)

  1. 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.
  1. 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.
  1. 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.

Phase 3: Basic Implementation (Estimated Time: 30 hours)

  1. 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.
  1. User Input Handling (8 hours):
  • Implement user input functionality for option parameters.
  • Validate and sanitize user inputs to ensure correctness.
  1. 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.

Phase 4: Advanced Feature (Estimated Time: 40 hours)

  1. Option Greeks Calculation (15 hours):
  • Extend the implementation to calculate option Greeks: delta, gamma, vega, theta, and rho.
  • Ensure accurate and efficient calculations.
  1. Enhanced Black-Scholes Pricing Models (15 hours):
  • Implement implied volatility calculation in the Black-Scholes model.
  • Incorporate Heston model equations for pricing.
  1. 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.

Phase 5: Additional Features (Estimated Time: 35 hours)

  1. 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).
  1. 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.
  1. Historical Volatility Analysis (10 hours):
  • Integrate functionality to calculate historical volatility based on historical price data.
  • Implement data analysis tools for insights.

Phase 6: Testing and Validation (Estimated Time: 20 hours)

  1. Unit Testing (10 hours):
  • Implement comprehensive unit tests for each component.
  • Use a testing framework (e.g., Google Test) to automate tests.
  1. Validation (10 hours):
  • Validate the entire program against established pricing models.
  • Compare results with known Black-Scholes and Heston model outcomes.

Phase 7: Documentation and Optimization (Estimated Time: 20 hours)

  1. Create README and Documentation (10 hours):
  • Document the project overview, features, and usage in the README.
  • Write detailed documentation for each feature, including examples.
  1. Code Comments (5 hours):
  • Add comments to your code for clarity and context.
  • Ensure that the codebase is well-documented for future reference.
  1. Optimization (5 hours):
  • Optimize the performance of the option pricing calculations.
  • Document performance improvements achieved.

Phase 8: Visualization and Finalization (Estimated Time: 15 hours)

  1. Visualizations (10 hours):
  • Enhance the project with visualizations using plotting libraries.
  • Plot option prices, implied volatility surfaces, Greeks, or other relevant metrics.
  1. Finalize Documentation (5 hours):
  • Review and finalize all project documentation.
  • Ensure consistency and completeness.

 

(back to top)


Project Implementation Guide

NEVER

 

(back to top)


Potential I/O Specifications

Input:

FILL THIS SECTION OUT LATERRRR

 

Output:

LATER

 

Error Handling:

 


Basic Workflow Guide

IDFK

 

(back to top)


Future Enhancements:

PROBABLY NONE LEFT

(back to top)


User Installation

System Prerequisites:

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 version 3.26 or higher, and
  • the Ninja build system.
  • Via Homebrew, install with the following command: brew install ninja.

 

Build and Run:

  1. Clone the repository:
  • git clone https://github.com/lyndskg/black-scholes-cpp.git
  • cd black-scholes-cpp
  1. Build the project:
  • cmake -Bbuild-cmake -H. -GNinja
  • cd build-cmake
  1. Run the program:
  • cmake --build .
  1. 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.
  1. To clean the project, access the current build directory:
  • pwd (Make sure you're in build-cmake; if not, cd build-cmake)
  • ninja -t clean
  • Repeat step 3 as needed.

(back to top)


Usage

Potential Use Cases:

  • Algorithmic trading strategy formulation, backtesting, and refinement.
  • Real-time market data monitoring and informed decision-making.
  • Portfolio analysis and optimization for traders and investors.

 

(back to top)

Practical Applications:

WRITE HERE

 

(back to top)


Development Environment:

  • Operating System: macOS Ventura (version 14.3.1)
  • Architecture: Apple arm64

(back to top)


How to Support Us

We welcome contributions from the community to help improve black-scholes-cpp and make it even better.

  • Contribute: Don't.
  • Donate: DON'T!

(back to top)


Conclusion

WRITE HERE

 

(back to top)


Contact

Lyndsey Gu - @lyndskg - lyndsey.gu@gmail.com

Project Link: https://github.com/lyndskg/black-scholes-cpp

(back to top)


Acknowledgments

Put Stuff Here

Resources:

  1. Online tutorials:
  1. Online resources:
  1. GitHub Repos:

(back to top)

Things to work on:

  1. Reading input from database: SQLite
  2. Reading input from file: Get .CSV samples from Kaggle to test.
  3. Reading input from external market feeds / APIs. Retrieve Alpha Vantage Rapid API Private Key and finish configuration.
  4. Testing and debugging.
  5. Finishing optionGreeksModel class implementations.
  6. Implementing more advanced functionalities: implied volatility (IV), Heston model, Monte Carlo, etc.

Optimizations:

  1. Check all #includes and using directives.
  2. In function double blackScholesModel::calculateOptionPrice(), can use if-elif-else statement, switch statement, or ternary operator for optionType.
  3. In class blackScholesModel, optionType (i.e. Call vs. Put) can be represented as enum type or char. If latter, does it need to be initialized in ctor?
  4. In function double blackScholesModel::normalCDF(), should the result be returned via ternary operator or if-else statement?
  5. 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?
  6. In function double blackScholesModel::normalCDF(), a more efficient approximation can be used.
  7. In function inputReader::readInputFromUser(), should validation be accomplished using its two current helper functions or via validateAndSetInputValues()?

Bug fixes:

  1. 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) to stderr (cerr) for debugging purposes.

dr-liangma/BlackScholes_MonteCarlo

CHAT MF GPT

About

A UI-friendly program calculating Black-Scholes options pricing with advanced algorithms incorporating option Greeks, IV, Heston model, etc. Reads input from users, files, databases, and real-time, external market feeds (e.g. APIs).

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published