### Install py_vollib Python Library via Pip Source: https://github.com/vollib/py_vollib/blob/master/README.rst This command installs the py_vollib library and its core dependencies using pip. Ensure Python and pip are already installed on your system before running this command. ```Shell pip install py_vollib ``` -------------------------------- ### Install py_vollib Python Library via pip Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/index.html This command installs the py_vollib library and its necessary dependencies, such as py_lets_be_rational, using the Python package installer, pip. Ensure that Python and pip are already installed on your system before running this command. ```Python pip install py_vollib ``` -------------------------------- ### Python Examples: Calculate Implied Volatility with `py_vollib` Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/apidoc/py_vollib.ref_python.black.html Provides practical Python examples demonstrating the usage of the `implied_volatility` function. These examples illustrate how to input various option parameters and verify the computed implied volatility against expected values. They also show integration with the `black` function for deriving option prices. ```python F = 101.0 K = 102.0 t = .5 r = .01 flag = 'p' sigma_in = 0.2 price = black(flag, F, K, t, r, sigma_in) expected_price = 6.20451158097 abs(expected_price - price) < 0.00001 # True sigma_out = implied_volatility(price, F, K, r, t, flag) sigma_in == sigma_out or abs(sigma_in - sigma_out) < 0.00001 # True F = 100 K = 100 sigma = .2 flag = 'c' t = .5 r = .02 discounted_call_price = black(flag, F, K, t, r, sigma) iv = implied_volatility(discounted_call_price, F, K, r, t, flag) expected_discounted_call_price = 5.5811067246 expected_iv = 0.2 abs(expected_discounted_call_price - discounted_call_price) < 0.00001 # True abs(expected_iv - iv) < 0.00001 # True ``` -------------------------------- ### Generate Sphinx Documentation for py_vollib Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/index.html This snippet provides shell commands to generate Sphinx documentation for the `py_vollib` project. It uses `sphinx-apidoc` to create API documentation from the source code and `make html` to build the HTML output. This process requires Sphinx to be installed and configured in your environment. ```Shell cd docs sphinx-apidoc -f -o apidoc ../py_vollib make html ``` -------------------------------- ### Python Example: Calculate Black Call Option Price Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/_modules/py_vollib/ref_python/black.html Illustrates how to use the `black` function to calculate a call option price. The example provides input parameters and verifies the calculated value against an expected result, demonstrating the function's usage. ```Python F = 100 K = 100 sigma = .2 flag = 'c' r = .02 t = .5 expected = 5.5811067246048118 actual = black(flag, F, K, t, r, sigma) abs(expected - actual) < 1e-12 ``` -------------------------------- ### Install Numba Dependencies for py_vollib on macOS Source: https://github.com/vollib/py_vollib/blob/master/README.rst This snippet provides commands to install Numba's dependencies, specifically llvm-lite and numba itself, on macOS using Homebrew and pip. Numba is an optional dependency for py_vollib that improves execution speed. ```Shell brew install llvm@3.9 LLVM_CONFIG=/usr/local/opt/llvm@3.9/bin/llvm-config pip install llvmlite==0.16.0 pip install numba==0.31.0 ``` -------------------------------- ### Python Example: Calculate Black Put Option Price Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/_modules/py_vollib/ref_python/black.html Demonstrates how to use the `black_put` function with sample values. This example calculates the put option price and verifies it against a textbook value, showing the function's accuracy. ```Python F = 20 K = 20 r = .09 sigma = .25 t = 4/12.0 calculated_value = black_put(F, K, t, r, sigma) # 1.11664145656 text_book_value = 1.12 abs(calculated_value - text_book_value) < .01 ``` -------------------------------- ### py_vollib.ref_python.black Package Structure Overview Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/apidoc/py_vollib.ref_python.black.html This snippet outlines the hierarchical structure of the `py_vollib.ref_python.black` package, listing its direct subpackages and submodules. It serves as a navigational guide to the components responsible for Black model calculations within the reference implementation. ```APIDOC py_vollib.ref_python.black package ================================== Subpackages: - py_vollib.ref_python.black.greeks package - Submodules: - py_vollib.ref_python.black.greeks.analytical module - py_vollib.ref_python.black.greeks.numerical module - Module contents: py_vollib.ref_python.black.greeks Submodules: - py_vollib.ref_python.black.implied_volatility module ``` -------------------------------- ### API Structure for py_vollib.ref_python Package Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/apidoc/py_vollib.html This snippet outlines the hierarchical structure of the py_vollib.ref_python package, detailing its subpackages and modules for Black and Black-Scholes models, including their respective Greeks and implied volatility functionalities. It serves as a guide to navigate the reference implementation. ```APIDOC { "py_vollib.ref_python": { "description": "A pure Python reference implementation of py_vollib, without dependence on LetsBeRational. Intended for sanity checking, not industrial use.", "contents": { "packages": { "black": { "description": "Contains modules related to the Black model.", "modules": { "greeks": { "description": "Module for Black model Greeks calculations.", "submodules": { "numerical": { "description": "Numerical Greeks calculations for the Black model." } } }, "implied_volatility": { "description": "Module for Black model implied volatility calculations." } } }, "black_scholes": { "description": "Contains modules related to the Black-Scholes model.", "packages": { "greeks": { "description": "Package for Black-Scholes Greeks.", "modules": { "analytical": { "description": "Analytical Greeks calculations for the Black-Scholes model." }, "numerical": { "description": "Numerical Greeks calculations for the Black-Scholes model." } } } } } } } } } ``` -------------------------------- ### Python Example: Compare Numerical and Analytical Greeks Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/apidoc/py_vollib.ref_python.black_scholes.greeks.html This code snippet demonstrates a test suite that compares the numerical implementations of Black-Scholes Greeks (delta, gamma, rho, vega) against their analytical counterparts. It defines a set of option parameters and then asserts that the absolute difference between the numerical and analytical values for each Greek is less than a small epsilon, ensuring consistency and accuracy of the numerical methods. ```Python S = 49 K = 50 r = .05 t = 0.3846 sigma = 0.2 flag = 'c' epsilon = .0001 v1 = delta(flag, S, K, t, r, sigma) v2 = adelta(flag, S, K, t, r, sigma) abs(v1-v2)>> S = 49 >>> K = 50 >>> r = .05 >>> t = 0.3846 >>> sigma = 0.2 >>> flag = 'c' >>> delta_calc = delta(flag, S, K, t, r, sigma) >>> # 0.521601633972 >>> delta_text_book = 0.522 >>> abs(delta_calc - delta_text_book) < .01 True Example 17.2, page 359, Hull: >>> S = 49 >>> K = 50 >>> r = .05 >>> t = 0.3846 >>> sigma = 0.2 >>> flag = 'c' >>> annual_theta_calc = theta(flag, S, K, t, r, sigma) * 365 >>> # -4.30538996455 >>> annual_theta_text_book = -4.31 >>> abs(annual_theta_calc - annual_theta_text_book) < .01 True Example 17.4, page 364, Hull: >>> S = 49 >>> K = 50 >>> r = .05 >>> t = 0.3846 >>> sigma = 0.2 >>> flag = 'c' >>> gamma_calc = gamma(flag, S, K, t, r, sigma) >>> # 0.0655453772525 >>> gamma_text_book = 0.066 >>> abs(gamma_calc - gamma_text_book) < .001 True Example 17.6, page 367, Hull: >>> S = 49 >>> K = 50 >>> r = .05 >>> t = 0.3846 >>> sigma = 0.2 >>> flag = 'c' >>> vega_calc = vega(flag, S, K, t, r, sigma) >>> # 0.121052427542 >>> vega_text_book = 0.121 >>> abs(vega_calc - vega_text_book) < .01 True Example 17.7, page 368, Hull: >>> S = 49 >>> K = 50 >>> r = .05 ``` -------------------------------- ### Test Binary Flag Mapping for Options in Python Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/_modules/py_vollib/helpers.html This function demonstrates the mapping of 'c' for call and 'p' for put options to their respective numerical flags (+1 and -1). It serves as a test case to ensure the `binary_flag` dictionary correctly assigns values as per the 'Let's be Rational' convention, where +1 signifies a call and -1 a put. ```Python def test_binary_flag(): """ :: ======================================================== Note: In "Let's be Rational," Peter Jäckel uses θ as a flag to distinguish between puts and calls. +1 represents a call, -1 represents a put. See page 1, Introduction, first paragraph. Throughout py_vollib this is replaced with 'c' and 'p'. ======================================================== >>> binary_flag['c'] 1 >>> binary_flag['p'] -1 """ ``` ```APIDOC Function: test_binary_flag() Description: Verifies the mapping of 'c' (call) to +1 and 'p' (put) to -1 in the `binary_flag` dictionary. This function ensures consistency with the 'Let's be Rational' convention for option type representation. Parameters: None Returns: None (assertion-based test) ``` -------------------------------- ### APIDOC: py_vollib.helpers.doctest_helper Module Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/apidoc/py_vollib.html This module likely contains utilities to assist with doctests within the py_vollib project, ensuring code examples in docstrings are correct. ```APIDOC { "module": "py_vollib.helpers.doctest_helper", "description": "Helper functions for doctesting." } ``` -------------------------------- ### API Documentation for py_vollib.black_scholes_merton.greeks package Source: https://github.com/vollib/py_vollib/blob/master/docs/apidoc/py_vollib.black_scholes_merton.greeks.rst Documents the main `py_vollib.black_scholes_merton.greeks` package. This package serves as a central hub, aggregating both analytical and numerical implementations of Black-Scholes-Merton Greeks. It provides a unified interface to access various option sensitivity calculations, allowing users to choose their preferred method. ```APIDOC Package: py_vollib.black_scholes_merton.greeks Description: Provides a comprehensive set of functions for calculating Black-Scholes-Merton Greeks, including both analytical and numerical implementations. Submodules: - py_vollib.black_scholes_merton.greeks.analytical - py_vollib.black_scholes_merton.greeks.numerical Common Interface (Example): - Name: calculate_greeks Signature: calculate_greeks(S, K, t, r, sigma, flag, method='analytical') Description: Calculates all major Greeks for an option using a specified method. Parameters: - name: S type: float description: Stock price - name: K type: float description: Strike price - name: t type: float description: Time to expiration (in years) - name: r type: float description: Risk-free interest rate (annualized) - name: sigma type: float description: Volatility of the underlying asset (annualized) - name: flag type: str description: Option type ('c' for call, 'p' for put) - name: method type: str description: Calculation method ('analytical' or 'numerical'). Defaults to 'analytical'. Returns: type: dict description: A dictionary containing calculated Greeks (e.g., {'delta': ..., 'gamma': ..., 'vega': ..., 'theta': ..., 'rho': ...}). ``` -------------------------------- ### Python: Get Probability Density Function Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/apidoc/py_vollib.helpers.html This function calculates the probability density function (PDF) for a continuous random variable. It takes a single input `x` representing the random variable. This function is part of the `py_vollib.helpers` module. ```APIDOC py_vollib.helpers.pdf(x) Parameters: x: a continuous random variable ``` -------------------------------- ### Python: py_vollib.black Package API Overview Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/_sources/apidoc/py_vollib.black.rst.txt This section provides an overview of the `py_vollib.black` package, detailing its structure and main components. It serves as the entry point for Black-Scholes related functionalities within the `py_vollib` library, including access to submodules and subpackages. ```APIDOC Package: py_vollib.black Description: The py_vollib.black package implements Black-Scholes model functionalities. Subpackages: - py_vollib.black.greeks: Contains functions for calculating option Greeks. Submodules: - py_vollib.black.implied_volatility: Provides functions for implied volatility calculations. Members: (Any direct members of the py_vollib.black package would be listed here if available) ``` -------------------------------- ### Black-Scholes Option Pricing Function API Reference Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/_modules/py_vollib/black_scholes.html Detailed API documentation for the `black_scholes` function, outlining its parameters, their types, descriptions, and the expected return value. This reference is crucial for understanding how to correctly invoke the function for option pricing. ```APIDOC Function: black_scholes(flag, S, K, t, r, sigma) Parameters: - S (float): Underlying asset price - K (float): Strike price - sigma (float): Annualized standard deviation, or volatility - t (float): Time to expiration in years - r (float): Risk-free interest rate - flag (str): 'c' for call or 'p' for put Returns: - float: The Black-Scholes option price Example Usage: >>> c = black_scholes('c',100,90,.5,.01,.2) >>> abs(c - 12.111581435) < .000001 True >>> p = black_scholes('p',100,90,.5,.01,.2) >>> abs(p - 1.66270456231) < .000001 True ``` -------------------------------- ### Calculate Black-Scholes-Merton Theta in Python Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/_modules/py_vollib/black_scholes_merton/greeks/analytical.html Provides Python code and API documentation for calculating the Black-Scholes-Merton theta, which measures the sensitivity of an option's price to the passage of time. The example demonstrates how to use the function and verify its output against a known value. ```Python S = 49 K = 50 r = .05 t = 0.3846 q = 0 sigma = 0.2 flag = 'c' theta_calc = theta(flag, S, K, t, r, sigma, q) # -1.8530056722 theta_text_book = -1.853 abs(theta_calc - theta_text_book) < .001 ``` ```Python D1 = d1(S, K, t, r, sigma, q) D2 = d2(S, K, t, r, sigma, q) first_term = (S * numpy.exp(-q*t) * pdf(D1) * sigma) / (2 * numpy.sqrt(t)) if flag == 'c': second_term = -q * S * numpy.exp(-q*t) * N(D1) third_term = r * K * numpy.exp(-r*t) * N(D2) return - (first_term + second_term + third_term) / 365.0 else: second_term = -q * S * numpy.exp(-q*t) * N(-D1) third_term = r * K * numpy.exp(-r*t) * N(-D2) return (-first_term + second_term + third_term) / 365.0 ``` ```APIDOC Function: theta(flag, S, K, t, r, sigma, q) Description: Returns the Black-Scholes-Merton theta of an option. Parameters: - flag (str): 'c' or 'p' for call or put. - S (float): underlying asset price - K (float): strike price - t (float): time to expiration in years - r (float): annual risk-free interest rate - sigma (float): volatility - q (float): annualized continuous dividend yield Returns: - float ``` -------------------------------- ### API Reference: py_vollib.black_scholes_merton.greeks package Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/_sources/apidoc/py_vollib.black_scholes_merton.greeks.rst.txt Documents the main `greeks` package within `py_vollib.black_scholes_merton`. This package serves as a container for both analytical and numerical implementations of Black-Scholes-Merton Greeks. It provides a unified interface to access various option sensitivity calculations. ```APIDOC Package: py_vollib.black_scholes_merton.greeks Description: This package serves as the primary container for Black-Scholes-Merton Greeks calculations. It encompasses both analytical and numerical approaches. Submodules: - py_vollib.black_scholes_merton.greeks.analytical - py_vollib.black_scholes_merton.greeks.numerical Members: - All public members (functions, classes, variables) within the package are documented. - Provides a unified interface to access various option sensitivity calculations. ``` -------------------------------- ### API Documentation for py_vollib.ref_python.black_scholes Package Source: https://github.com/vollib/py_vollib/blob/master/docs/apidoc/py_vollib.ref_python.black_scholes.rst This snippet details the top-level API structure of the `py_vollib.ref_python.black_scholes` package. It lists its subpackages and modules, and indicates that its core members (functions, classes) are intended for documentation as per the `automodule` directive. ```APIDOC Package: py_vollib.ref_python.black_scholes Description: Contains core Black-Scholes model implementations and related utilities. Subpackages: - py_vollib.ref_python.black_scholes.greeks Modules: - py_vollib.ref_python.black_scholes.implied_volatility Members: - (Functions, classes, or variables documented by :members: directive) ``` -------------------------------- ### Calculate Black-Scholes-Merton Rho in Python Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/_modules/py_vollib/black_scholes_merton/greeks/analytical.html Provides Python code and API documentation for calculating the Black-Scholes-Merton rho, which measures the sensitivity of an option's price to changes in the risk-free interest rate. The example demonstrates how to use the function and verify its output against a known value. ```Python S = 49 K = 50 r = .05 t = 0.3846 q = 0 sigma = 0.2 flag = 'c' rho_calc = rho(flag, S, K, t, r, sigma, q) # 0.089065740988 rho_text_book = 0.0891 abs(rho_calc - rho_text_book) < .0001 ``` ```Python D2 = d2(S, K, t, r, sigma, q) if flag == 'c': return t * K * numpy.exp(-r*t) * N(D2) * .01 else: return -t * K * numpy.exp(-r*t) * N(-D2) * .01 ``` ```APIDOC Function: rho(flag, S, K, t, r, sigma, q) Description: Returns the Black-Scholes-Merton rho of an option. Parameters: - flag (str): 'c' or 'p' for call or put. - S (float): underlying asset price - ``` -------------------------------- ### Calculate Black-Scholes-Merton Gamma in Python Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/_modules/py_vollib/black_scholes_merton/greeks/analytical.html Provides Python code and API documentation for calculating the Black-Scholes-Merton gamma, which measures the sensitivity of an option's delta to changes in the underlying asset price. The example demonstrates how to use the function and verify its output against a known value. ```Python S = 49 K = 50 r = .05 t = 0.3846 q = 0 sigma = 0.2 flag = 'c' gamma_calc = gamma(flag, S, K, t, r, sigma, q) # 0.0655453772525 gamma_text_book = 0.066 abs(gamma_calc - gamma_text_book) < .001 ``` ```Python D1 = d1(S, K, t, r, sigma, q) numerator = numpy.exp(-q*t) * pdf(D1) denominator = S * sigma * numpy.sqrt(t) return numerator / denominator ``` ```APIDOC Function: gamma(flag, S, K, t, r, sigma, q) Description: Returns the Black-Scholes-Merton gamma of an option. Parameters: - flag (str): 'c' or 'p' for call or put. - S (float): underlying asset price - K (float): strike price - t (float): time to expiration in years - r (float): annual risk-free interest rate - sigma (float): volatility - q (float): annualized continuous dividend yield Returns: - float ``` -------------------------------- ### Configure Sphinx Documentation Options and Theme Navigation Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/apidoc/py_vollib.ref_python.black.greeks.html This JavaScript code initializes global options for a Sphinx-generated documentation site, including paths and file types. Additionally, it activates the sticky navigation bar provided by the Sphinx ReadTheDocs theme, ensuring the navigation remains visible while scrolling. ```JavaScript var DOCUMENTATION_OPTIONS = { URL_ROOT:'../', VERSION:'1.0.2', COLLAPSE_INDEX:false, FILE_SUFFIX:'.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' }; jQuery(function () { SphinxRtdTheme.StickyNav.enable(); }); ``` -------------------------------- ### Calculate Black-Scholes-Merton Vega in Python Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/_modules/py_vollib/black_scholes_merton/greeks/analytical.html Provides Python code and API documentation for calculating the Black-Scholes-Merton vega, which measures the sensitivity of an option's price to changes in the underlying asset's volatility. The example demonstrates how to use the function and verify its output against a known value. ```Python S = 49 K = 50 r = .05 t = 0.3846 q = 0 sigma = 0.2 flag = 'c' vega_calc = vega(flag, S, K, t, r, sigma, q) # 0.121052427542 vega_text_book = 0.121 abs(vega_calc - vega_text_book) < .01 ``` ```Python D1 = d1(S, K, t, r, sigma, q) return S * numpy.exp(-q*t) * pdf(D1) * numpy.sqrt(t) * 0.01 ``` ```APIDOC Function: vega(flag, S, K, t, r, sigma, q) Description: Returns the Black-Scholes-Merton vega of an option. Parameters: - flag (str): 'c' or 'p' for call or put. - S (float): underlying asset price - K (float): strike price - t (float): time to expiration in years - r (float): annual risk-free interest rate - sigma (float): volatility - q (float): annualized continuous dividend yield Returns: - float ``` -------------------------------- ### Python py_vollib.black_scholes_merton.greeks Package Overview Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/apidoc/py_vollib.black_scholes_merton.greeks.html This snippet provides an overview of the `py_vollib.black_scholes_merton.greeks` package, detailing its purpose within the `py_vollib` library and listing its submodules. It serves as an entry point for understanding the analytical functionalities related to option greeks. ```APIDOC Package: py_vollib.black_scholes_merton.greeks Description: This package is part of the py_vollib library, focusing on functionalities related to option greeks within the Black-Scholes-Merton model. Submodules: - py_vollib.black_scholes_merton.greeks.analytical Description: A library for option pricing, implied volatility, and greek calculation. py_vollib is based on lets_be_rational, a Python wrapper for LetsBeRational by Peter Jaeckel. Copyright: © 2017 Gammon Capital LLC License: MIT ``` -------------------------------- ### Generate HTML Documentation for py_vollib using Sphinx Source: https://github.com/vollib/py_vollib/blob/master/README.rst These commands navigate to the documentation directory, use Sphinx's apidoc tool to generate reStructuredText source files from the py_vollib Python modules, and then build the HTML documentation. This process creates a comprehensive set of web pages for the project's API and modules. ```Shell cd docs sphinx-apidoc -f -o apidoc ../py_vollib make html ``` -------------------------------- ### Calculate Black-Scholes-Merton Vega for Call Option in Python Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/apidoc/py_vollib.ref_python.black_scholes_merton.greeks.html This example demonstrates how to calculate the Black-Scholes-Merton vega for a call option using the `vega` function from `py_vollib`. It sets up the necessary input parameters and compares the calculated vega against a reference value from Hull's textbook, verifying the accuracy within a specified tolerance. ```Python S = 49 K = 50 r = .05 t = 0.3846 q = 0 sigma = 0.2 flag = 'c' vega_calc = vega(flag, S, K, t, r, sigma, q) # 0.121052427542 vega_text_book = 0.121 abs(vega_calc - vega_text_book) < .01 True ``` -------------------------------- ### Configure Sphinx Documentation Options in JavaScript Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/_modules/py_vollib/black_scholes/greeks/numerical.html This JavaScript snippet defines global options for Sphinx documentation, such as the base URL, version number, and file suffixes. It also initializes the sticky navigation feature from the Sphinx Read the Docs theme using jQuery, ensuring the navigation bar remains visible as the user scrolls. ```JavaScript var DOCUMENTATION_OPTIONS = { URL_ROOT:'../../../../', VERSION:'1.0.2', COLLAPSE_INDEX:false, FILE_SUFFIX:'.html', HAS_SOURCE: true, SOURCELINK_SUFFIX: '.txt' }; jQuery(function () { SphinxRtdTheme.StickyNav.enable(); }); ``` -------------------------------- ### Python py_vollib.helpers.doctest_helper.run_doctest Function Source: https://github.com/vollib/py_vollib/blob/master/docs/_build/html/apidoc/py_vollib.helpers.html This function, part of the py_vollib.helpers.doctest_helper module, is designed to execute doctests. It helps in verifying the correctness of code examples embedded within docstrings, ensuring the library's functionality behaves as expected. This function takes no explicit parameters and is primarily used for internal testing or demonstration purposes. ```Python py_vollib.helpers.doctest_helper.run_doctest() ```