├── .github ├── actions │ └── cached-venv │ │ └── action.yml └── workflows │ └── cicd.yml ├── .gitignore ├── .pre-commit-config.yaml ├── CHANGELOG.md ├── LICENSE ├── README.md ├── docs ├── index.html ├── optionlab.html ├── optionlab.png ├── optionlab │ ├── black_scholes.html │ ├── engine.html │ ├── models.html │ ├── optionlab.png │ ├── plot.html │ ├── price_array.html │ ├── support.html │ └── utils.html └── search.js ├── examples ├── .gitignore ├── black_scholes_calculator.ipynb ├── calendar_spread.ipynb ├── call_spread.ipynb ├── covered_call.ipynb ├── msft_22-November-2021.csv └── naked_call.ipynb ├── optionlab.png ├── optionlab ├── .gitignore ├── __init__.py ├── black_scholes.py ├── engine.py ├── models.py ├── plot.py ├── price_array.py ├── support.py └── utils.py ├── poetry.lock ├── pyproject.toml └── tests ├── .gitignore ├── __init__.py ├── conftest.py ├── test_core.py ├── test_misc.py └── test_models.py /.github/actions/cached-venv/action.yml: -------------------------------------------------------------------------------- 1 | name: "Install dependencies in venv" 2 | description: "Install dependencies in venv" 3 | 4 | runs: 5 | using: composite 6 | steps: 7 | - name: Cache virtual environment 8 | uses: actions/cache@v4 9 | env: 10 | cache-name: cache-venv-1 11 | with: 12 | path: '**/venv' 13 | key: ${{ runner.os }}-${{ env.cache-name }}-${{ hashFiles('poetry.lock') }} 14 | 15 | - name: Set up Python ${{ matrix.python-version }} 16 | uses: actions/setup-python@v2 17 | with: 18 | python-version: "3.10.8" 19 | 20 | - name: Install Poetry 21 | run: | 22 | pip install poetry==1.4.0 23 | shell: bash 24 | 25 | - name: Install dependencies 26 | run: | 27 | python3.10 -m venv venv 28 | source venv/bin/activate 29 | poetry install 30 | shell: bash 31 | -------------------------------------------------------------------------------- /.github/workflows/cicd.yml: -------------------------------------------------------------------------------- 1 | # Run unit and integration tests for CI 2 | # Build any branch that passes CI as a docker image 3 | # Push a docker image tagged with the git hash and branch name 4 | # For PR's, display the option to deploy to the test env 5 | # For merges to main, display the option to deploy to the dev env 6 | # The environments are configured in the GitHub repo settings 7 | 8 | name: CI/CD 9 | 10 | on: 11 | push: 12 | branches: 13 | - '**' 14 | 15 | jobs: 16 | tests: 17 | runs-on: ubuntu-latest 18 | steps: 19 | - uses: actions/checkout@v4 20 | - uses: ./.github/actions/cached-venv 21 | - name: Run mypy & service tests 22 | run: | 23 | source venv/bin/activate 24 | mypy optionlab/ --ignore-missing-imports 25 | black . --check --diff --color 26 | pytest -m "not benchmark" 27 | 28 | publish: 29 | name: Publish to pypi.org 30 | if: github.event.ref == 'refs/heads/main' 31 | needs: [ tests ] 32 | runs-on: ubuntu-latest 33 | steps: 34 | - uses: actions/checkout@v4 35 | - uses: ./.github/actions/cached-venv 36 | - name: Build and publish 37 | env: 38 | PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }} 39 | run: | 40 | poetry config pypi-token.pypi "$PYPI_TOKEN" 41 | poetry publish --build 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .benchmarks 2 | .mypy_cache 3 | .pytest_cache 4 | __pycache__ 5 | dist 6 | run_check 7 | *.old 8 | runpdoc.bat 9 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # See https://pre-commit.com for more information 2 | # See https://pre-commit.com/hooks.html for more hooks 3 | repos: 4 | - repo: https://github.com/psf/black 5 | rev: 24.2.0 6 | hooks: 7 | - id: black 8 | - repo: https://github.com/astral-sh/ruff-pre-commit 9 | rev: v0.3.2 10 | hooks: 11 | - id: ruff 12 | args: [--ignore,E501,--fix] 13 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # CHANGELOG 2 | 3 | ## 1.4.3 (2025-04-14) 4 | 5 | - Updated docstrings. 6 | - Added documentation with `pdoc`. 7 | - Changed __init__.py for compatibility with `pdoc` autodocumentation. 8 | - Removed `BaseLeg` from models.py. 9 | - Changed `StrategyType` to `StrategyLegType` in models.py for clarity. 10 | - Removed "normal" as an alias for "black-scholes" to avoid confusion with Bachelier model. 11 | - Updated Readme.md. 12 | 13 | ## 1.4.2 (2025-01-25) 14 | 15 | - Removed `expected_profit` and `expected_loss` calculation from `_get_pop_bs` in support.py; implementation was not correct, giving wrong results when compared with Monte Carlo simulations 16 | 17 | ## 1.4.1 (2025-01-04) 18 | 19 | - Removed a small bug in `create_price_seq` in support.py 20 | - Improved the algorithm in `get_profit_range` in support.py, then renamed to `_get_profit_range` 21 | - Created a helper function `_get_sign_changes` in support.py, called by `get_profit_range` 22 | - Removed the fields `probability_of_profit_from_mc`, `average_profit_from_mc` and `average_loss_from_mc` from `Outputs` in models.py 23 | - Created the fields `expected_profit` and `expected_loss` in `Outputs` in models.py 24 | - Created a class `PoPOutputs` in models.py containing fields returned by `get_pop` in support.py 25 | - Removed Laplace form `get_pop` in support.py 26 | - Improved `get_pop` in support.py to return a `PoPOutputs` object with more information 27 | - Added naked calls as an example of strategy 28 | - Created a custom type `FloatOrNdarray` that can contain a float or a numpy.ndarray in models.py 29 | - Created the helper functions `_get_pop_bs` and `get_pop_array` in support.py 30 | 31 | ## 1.4.0 (2025-01-01) 32 | 33 | - Changed the class name `DistributionInputs` to `TheoreticalModelInputs` in models.py, to be more descriptive 34 | - Changed the class name `DistributionBlackScholesInputs` to `BlackScholesModelInputs` in models.py 35 | - Changed the class name `DistributionLaplaceInputs` to `LaplaceInputs` in models.py 36 | - Changed the class name `DistributionArrayInputs` to `ArrayInputs` in models.py 37 | - Changed literal `Distribution` to `TheoreticalModel` 38 | - Moved `create_price_samples` from support.py to a new module price_array.py and renamed it to `create_price_array` 39 | - Commented a code snippet in engine.py where terminal stock prices are created using `create_price_samples`, to be removed in a next version 40 | - Allowed a dictionary as input for `create_price_array` in price_array.py 41 | - Allowed a dictionary as input for `get_pop` in support.py 42 | 43 | ## 1.3.5 (2024-12-28) 44 | 45 | - Created a base class `DistributionInputs` 46 | - Changed the name of `ProbabilityOfProfitInputs` in models.py (and everywhere in the code) to `DistributionBlackScholesInputs`, which inherits from `DistributionInputs` 47 | - Removed the `source` field from `DistributionBlackScholesInputs` 48 | - Modified interest_rate: float = Field(0.0, ge=0.0) in `DistributionBlackScholesInputs` in models.py 49 | - Modified volatility: float = Field(gt=0.0) in `DistributionInputs` in models.py 50 | - Modified years_to_maturity: float = Field(ge=0.0) in `DistributionInputs` in models.py 51 | - Created a class `DistributionLaplaceInputs` in models.py, which inherits from `DistributionInputs` 52 | - Changed `years_to_maturity` field in `DistributionInputs` to `years_to_target_date` 53 | - Refactored `create_price_samples` in support.py 54 | - Added __hash__ = object.__hash__ in `DistributionBlackScholesInputs` and `DistributionLaplaceInputs` in models.py to allow their use in `create_price_samples` in support.py with caching 55 | - Updated tests to reflect those changes 56 | - Removed a deprecated class, `StrategyEngine`, commented in a previous version 57 | - Added a test for Laplace distribution 58 | - Added a test for Calendar Spread 59 | 60 | ## 1.3.4 (2024-12-20) 61 | 62 | - Deleted `OptionInfo` class in models.py, because it is not necessary 63 | - Deleted `return_in_the_domain_ratio` in `Outputs` in models.py 64 | - Deleted `Country` in models.py, because it is not necessary 65 | - Deleted source: Literal["array"] = "array" in `ProbabilityOfProfitArrayInputs` class in models.py, because it is not necessary 66 | - Strike prices in black_scholes.py functions now can be provided also as numpy arrays and those functions return numpy arrays 67 | - `BlackScholesInfo` fields in models.py now can be both float and numpy arrays 68 | - Split `get_d1_d2` function in black_scholes.py into two functions, `get_d1` and `get_d2` 69 | - Added the field `business_days_in_year` in `Inputs` class in models.py to allow market-dependent customization; also changed in engine.py 70 | - Added Greek Rho calculation to black-scholes.py 71 | - Added `call_rho` and `put_rho` fields to `BlackScholesInfo` in models.py 72 | - Added `rho` field to `EngineData` in models.py 73 | - Added `rho` field to `Outputs` in models.py 74 | - Added `rho` data field in engine.py 75 | - Added a `seed` argument to `create_price_samples` in support.py to make the generation of price samples deterministic 76 | - Changed `array_prices` field to simply `array` in `Inputs` in models.py 77 | - Changed and commented some tests in test_core.py 78 | 79 | ## 1.3.3 (2024-12-18) 80 | 81 | - Updated docstrings to comply with reStructuredText (RST) standards 82 | - Changed the `country` argument in `get_nonbusiness_days` in utils.py to accept a string 83 | - Changed the `data` argument in `get_pl` and `pl_to_csv` in utils.py to accept an `Outputs` object instead of `EngineData` 84 | - Commented 'source: Literal["array"] = "array"' in `ProbabilityOfProfitArrayInputs` class in models.py, because `source` is not necessary 85 | - Commented `OptionInfo` class in models.py, because it is not used anywhere 86 | - Commented `return_in_the_domain_ratio` in `Outputs` in models.py, because it is not necessary 87 | - Commented `Country` in models.py, because it is not necessary 88 | - Changed country: Country = "US" to country: str = "US" in models.py 89 | 90 | ## 1.3.2 (2024-11-30) 91 | 92 | - Changed Laplace distribution implementation in `create_price_samples` and `get_pop` functions in support.py 93 | 94 | ## 1.3.1 (2024-09-27) 95 | 96 | - discriminator="type" removed from strategy: list[StrategyLeg] = Field(..., min_length=1) in models.py, since 97 | it was causing errors in new Pydantic versions. 98 | - Changed `StotckStrategy` and `OptionStrategy` to `Stock` and `Option` in models.py, respectively. 99 | - Changed `BaseStrategy` to `BaseLeg` in models.py 100 | - Changed `Strategy` to `StrategyLeg` in models.py 101 | - Removed `premium` field from `Stock` in models.py 102 | - Moved `n` field to `BaseLeg` in models.py 103 | 104 | ## 1.3.0 (2024-09-13) 105 | 106 | - Remove the deprecated `StrategyEngine` class (it remains commented in the code). 107 | - Update the README.md file to reflect the current state of the library 108 | 109 | ## 1.2.1 (2024-06-03) 110 | 111 | - Add 1 to `time_to_target` and `time_to_maturity` in `engine.py` to consider the target and expiration dates as trading days in the calculations 112 | - Change Jupyter notebooks in the `examples` directory to utilize the `run_strategy()` function for performing options strategy calculations, instead of using the `StrategyEngine` class (deprecated) 113 | - Correct the PoP Calculator notebook 114 | - Change the name of variable `project_target_ranges` in `models.py` and `engine.py` to `profit_target_ranges` 115 | 116 | ## 1.2.0 (2024-03-31) 117 | 118 | - Add functions to run engine 119 | 120 | ## 1.1.0 (2024-03-24) 121 | 122 | - Refactor the engine's `run` method for readability 123 | - Accept dictionary of inputs to `StratgyEngine` init 124 | 125 | ## 1.0.1 (2024-03-18) 126 | 127 | - Refactor __holidays__.py to a utils function using the `holiday` library 128 | 129 | ## 1.0.0 (2024-03-11) 130 | 131 | **BREAKING CHANGES**: 132 | - Renamed strategy.py to engine.py and `Strategy` to `StrategyEngine` 133 | - Using pydantic for input validation into `StrategyEngine` 134 | - Outputs are now also a Pydantic model 135 | - Delete `use_dates`, as Pydantic will handle either using dates or `days_to_target` 136 | - Renamed functions to be PEP8 compliant, i.e. instead of `getPoP`, now is `get_pop` 137 | - Deleted options_chain.py module 138 | 139 | ## 0.1.7 (2023-07-04) 140 | 141 | - Initial commit with strategy engine and examples 142 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![OptionLab](optionlab.png) 2 | 3 | # OptionLab 4 | 5 | This package is a lightweight library written entirely in Python, designed to provide 6 | quick evaluation of option strategy ideas. 7 | 8 | The code produces various outputs, including the profit/loss profile of the strategy on 9 | a user-defined target date, the range of stock prices for which the strategy is 10 | profitable (i.e., generating a return greater than \$0.01), the Greeks associated with 11 | each leg of the strategy using the Black-Sholes model, the resulting debit or credit on the 12 | trading account, the maximum and minimum returns within a specified lower and higher price 13 | range of the underlying asset, and an estimate of the strategy's probability of profit. 14 | 15 | If you have any questions, corrections, comments or suggestions, just 16 | [drop a message](mailto:roberto.veiga@ufabc.edu.br). 17 | 18 | You can also reach me on [Linkedin](https://www.linkedin.com/in/roberto-gomes-phd-8a718317b/) or 19 | follow me on [X](https://x.com/rgaveiga). When I have some free time, which is rare, I publish articles 20 | on [Medium](https://medium.com/@rgaveiga). 21 | 22 | If you want to support this and other open source projects that I maintain, become a 23 | [sponsor on Github](https://github.com/sponsors/rgaveiga). 24 | 25 | ## Installation 26 | 27 | The easiest way to install **OptionLab** is using **pip**: 28 | 29 | ``` 30 | pip install optionlab 31 | ``` 32 | 33 | ## Documentation 34 | 35 | You can access the API documentation for **OptionLab** on the [project's GitHub Pages site](https://rgaveiga.github.io/optionlab). 36 | 37 | ## Contributions 38 | 39 | Contributions are definitely welcome. However, it should be mentioned that this 40 | repository uses [poetry](https://python-poetry.org/) as a package manager and 41 | [git hooks](https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks) with 42 | [pre-commit](https://pre-commit.com/) to customize actions on the repository. Source 43 | code must be formatted using [black](https://github.com/psf/black). 44 | 45 | ## Disclaimer 46 | 47 | This is free software and is provided as is. The author makes no guarantee that its 48 | results are accurate and is not responsible for any losses caused by the use of the 49 | code. 50 | 51 | Options are very risky derivatives and, like any other type of financial vehicle, 52 | trading options requires due diligence. This code is provided for educational and 53 | research purposes only. 54 | 55 | Bugs can be reported as issues. 56 | -------------------------------------------------------------------------------- /docs/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /docs/optionlab.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rgaveiga/optionlab/b4af9805ea7658b9e0d6d96cc11af83e17c3903d/docs/optionlab.png -------------------------------------------------------------------------------- /docs/optionlab/optionlab.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rgaveiga/optionlab/b4af9805ea7658b9e0d6d96cc11af83e17c3903d/docs/optionlab/optionlab.png -------------------------------------------------------------------------------- /examples/.gitignore: -------------------------------------------------------------------------------- 1 | .ipynb_checkpoints -------------------------------------------------------------------------------- /examples/black_scholes_calculator.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Black-Scholes calculator\n", 8 | "\n", 9 | "This notebook can be used to calculate the prices of call and put options, as well as the corresponding Greeks, using the famous [Black-Scholes model](https://www.investopedia.com/terms/b/blackscholes.asp).\n", 10 | "\n", 11 | "**Caveat: Options are very risky derivatives and, like any other type of financial vehicle, trading options requires due diligence.**" 12 | ] 13 | }, 14 | { 15 | "cell_type": "code", 16 | "execution_count": 1, 17 | "metadata": { 18 | "ExecuteTime": { 19 | "end_time": "2024-03-15T21:15:37.010803Z", 20 | "start_time": "2024-03-15T21:15:36.450216Z" 21 | } 22 | }, 23 | "outputs": [], 24 | "source": [ 25 | "from __future__ import print_function\n", 26 | "from __future__ import division\n", 27 | "from optionlab import VERSION, get_bs_info\n", 28 | "import sys" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": 2, 34 | "metadata": { 35 | "ExecuteTime": { 36 | "end_time": "2024-03-11T13:51:18.074225Z", 37 | "start_time": "2024-03-11T13:51:18.059531Z" 38 | } 39 | }, 40 | "outputs": [ 41 | { 42 | "name": "stdout", 43 | "output_type": "stream", 44 | "text": [ 45 | "Python version: 3.11.9 | packaged by Anaconda, Inc. | (main, Apr 19 2024, 16:40:41) [MSC v.1916 64 bit (AMD64)]\n", 46 | "OptionLab version: 1.4.3\n" 47 | ] 48 | } 49 | ], 50 | "source": [ 51 | "print(f\"Python version: {sys.version}\")\n", 52 | "print(f\"OptionLab version: {VERSION}\")" 53 | ] 54 | }, 55 | { 56 | "cell_type": "markdown", 57 | "metadata": {}, 58 | "source": [ 59 | "## Input\n", 60 | "\n", 61 | "You must provide the spot price of the underlying asset, the option strike, the annualized risk-free interest rate (as a percentage), the annualized volatility (also as a percentage), and the number of days remaining until the option expires. The annualized dividend yield on the stock, also as a percentage, is optional." 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": 3, 67 | "metadata": { 68 | "ExecuteTime": { 69 | "end_time": "2024-03-11T13:51:19.921321Z", 70 | "start_time": "2024-03-11T13:51:19.914234Z" 71 | } 72 | }, 73 | "outputs": [], 74 | "source": [ 75 | "stock_price = 100.0\n", 76 | "strike = 105.0\n", 77 | "interest_rate = 1.0\n", 78 | "dividend_yield = 0.0\n", 79 | "volatility = 20.0\n", 80 | "days_to_maturity = 60" 81 | ] 82 | }, 83 | { 84 | "cell_type": "markdown", 85 | "metadata": {}, 86 | "source": [ 87 | "## Calculations\n", 88 | "\n", 89 | "Before performing the calculations, the risk-free interest rate, dividend yield and volatility are converted from percentage to fractional and time remaining to option expiration is converted from days to years.\n", 90 | "\n", 91 | "The calculations are then performed using the Black-Scholes model." 92 | ] 93 | }, 94 | { 95 | "cell_type": "code", 96 | "execution_count": 4, 97 | "metadata": { 98 | "ExecuteTime": { 99 | "end_time": "2024-03-11T13:51:23.066600Z", 100 | "start_time": "2024-03-11T13:51:23.061122Z" 101 | } 102 | }, 103 | "outputs": [ 104 | { 105 | "name": "stdout", 106 | "output_type": "stream", 107 | "text": [ 108 | "CPU times: total: 0 ns\n", 109 | "Wall time: 4 ms\n" 110 | ] 111 | } 112 | ], 113 | "source": [ 114 | "%%time\n", 115 | "interest_rate = interest_rate / 100\n", 116 | "dividend_yield = dividend_yield / 100\n", 117 | "volatility = volatility / 100\n", 118 | "time_to_maturity = days_to_maturity / 365\n", 119 | "bs = get_bs_info(\n", 120 | " stock_price, strike, interest_rate, volatility, time_to_maturity, dividend_yield\n", 121 | ")" 122 | ] 123 | }, 124 | { 125 | "cell_type": "markdown", 126 | "metadata": {}, 127 | "source": [ 128 | "## Output\n", 129 | "\n", 130 | "You can find below the output of Black-Scholes calculations." 131 | ] 132 | }, 133 | { 134 | "cell_type": "code", 135 | "execution_count": 5, 136 | "metadata": { 137 | "ExecuteTime": { 138 | "end_time": "2024-03-11T13:51:26.685306Z", 139 | "start_time": "2024-03-11T13:51:26.678507Z" 140 | } 141 | }, 142 | "outputs": [ 143 | { 144 | "name": "stdout", 145 | "output_type": "stream", 146 | "text": [ 147 | "CALL\n", 148 | "====\n", 149 | " Price: 1.44\n", 150 | " Delta: 0.29\n", 151 | " Theta: -8.78\n", 152 | " Rho: 0.05\n", 153 | " ITM probability: 26.70\n", 154 | "\n", 155 | "\n", 156 | "PUT\n", 157 | "===\n", 158 | " Price: 6.27\n", 159 | " Delta: -0.71\n", 160 | " Theta: -7.73\n", 161 | " Rho: -0.13\n", 162 | " ITM probability: 73.30\n", 163 | "\n", 164 | "\n", 165 | "Gamma and Vega: 0.0425 \n", 166 | " 0.14\n" 167 | ] 168 | } 169 | ], 170 | "source": [ 171 | "print(\"CALL\")\n", 172 | "print(\"====\")\n", 173 | "print(f\" Price: {bs.call_price:.2f}\")\n", 174 | "print(f\" Delta: {bs.call_delta:.2f}\")\n", 175 | "print(f\" Theta: {bs.call_theta:.2f}\")\n", 176 | "print(f\" Rho: {bs.call_rho: .2f}\")\n", 177 | "print(f\" ITM probability: {bs.call_itm_prob * 100.0:.2f}\")\n", 178 | "print(\"\\n\")\n", 179 | "print(\"PUT\")\n", 180 | "print(\"===\")\n", 181 | "print(f\" Price: {bs.put_price:.2f}\")\n", 182 | "print(f\" Delta: {bs.put_delta:.2f}\")\n", 183 | "print(f\" Theta: {bs.put_theta:.2f}\")\n", 184 | "print(f\" Rho: {bs.put_rho: .2f}\")\n", 185 | "print(f\" ITM probability: {bs.put_itm_prob * 100.0:.2f}\")\n", 186 | "print(\"\\n\")\n", 187 | "print(f\"Gamma and Vega: {bs.gamma:.4f} \\n {bs.vega:.2f}\")" 188 | ] 189 | }, 190 | { 191 | "cell_type": "code", 192 | "execution_count": null, 193 | "metadata": {}, 194 | "outputs": [], 195 | "source": [] 196 | } 197 | ], 198 | "metadata": { 199 | "kernelspec": { 200 | "display_name": "Python 3 (ipykernel)", 201 | "language": "python", 202 | "name": "python3" 203 | }, 204 | "language_info": { 205 | "codemirror_mode": { 206 | "name": "ipython", 207 | "version": 3 208 | }, 209 | "file_extension": ".py", 210 | "mimetype": "text/x-python", 211 | "name": "python", 212 | "nbconvert_exporter": "python", 213 | "pygments_lexer": "ipython3", 214 | "version": "3.11.9" 215 | } 216 | }, 217 | "nbformat": 4, 218 | "nbformat_minor": 4 219 | } 220 | -------------------------------------------------------------------------------- /examples/calendar_spread.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Calendar Spread\n", 8 | "\n", 9 | "To implement this [strategy](https://www.investopedia.com/terms/c/calendarspread.asp), the trader sells a short-term option (either a call or a put) and buys a long-term option of same type, both options with the same strike. As such, it is a debit spread, the maximum loss being the amount paid for the strategy.\n", 10 | "\n", 11 | "**Caveat: Options are very risky derivatives and, like any other type of financial vehicle, trading options requires due diligence. Transactions shown as examples of trading strategies with options in this notebook are not recommendations.**" 12 | ] 13 | }, 14 | { 15 | "cell_type": "code", 16 | "execution_count": 1, 17 | "metadata": { 18 | "ExecuteTime": { 19 | "end_time": "2024-03-15T17:48:30.709566Z", 20 | "start_time": "2024-03-15T17:48:29.956122Z" 21 | } 22 | }, 23 | "outputs": [], 24 | "source": [ 25 | "from __future__ import print_function\n", 26 | "\n", 27 | "import datetime as dt\n", 28 | "import sys\n", 29 | "\n", 30 | "from optionlab import VERSION, run_strategy, plot_pl\n", 31 | "\n", 32 | "%matplotlib inline" 33 | ] 34 | }, 35 | { 36 | "cell_type": "code", 37 | "execution_count": 2, 38 | "metadata": { 39 | "ExecuteTime": { 40 | "end_time": "2024-03-11T13:51:39.643053Z", 41 | "start_time": "2024-03-11T13:51:39.640177Z" 42 | } 43 | }, 44 | "outputs": [ 45 | { 46 | "name": "stdout", 47 | "output_type": "stream", 48 | "text": [ 49 | "Python version: 3.11.9 | packaged by Anaconda, Inc. | (main, Apr 19 2024, 16:40:41) [MSC v.1916 64 bit (AMD64)]\n", 50 | "OptionLab version: 1.4.3\n" 51 | ] 52 | } 53 | ], 54 | "source": [ 55 | "print(f\"Python version: {sys.version}\")\n", 56 | "print(f\"OptionLab version: {VERSION}\")" 57 | ] 58 | }, 59 | { 60 | "cell_type": "markdown", 61 | "metadata": {}, 62 | "source": [ 63 | "The underlying asset is Apple stock (ticker: APPL). We consider the stock price on January 18, 2021. The strategy involves selling 1000 calls with a strike of 127, expiring on January 29, 2021, and buying 1000 calls with a strike of 127, expiring on February 12, 2021. The first leg of the strategy earns us a premium of 4.60 per option, while the second leg costs us 5.90 per option." 64 | ] 65 | }, 66 | { 67 | "cell_type": "code", 68 | "execution_count": 3, 69 | "metadata": { 70 | "ExecuteTime": { 71 | "end_time": "2024-03-15T17:48:35.828897Z", 72 | "start_time": "2024-03-15T17:48:35.823904Z" 73 | } 74 | }, 75 | "outputs": [], 76 | "source": [ 77 | "stock_price = 127.14\n", 78 | "volatility = 0.427\n", 79 | "start_date = dt.date(2021, 1, 18)\n", 80 | "target_date = dt.date(2021, 1, 29)\n", 81 | "interest_rate = 0.0009\n", 82 | "min_stock = stock_price - round(stock_price * 0.5, 2)\n", 83 | "max_stock = stock_price + round(stock_price * 0.5, 2)\n", 84 | "strategy = [\n", 85 | " {\"type\": \"call\", \"strike\": 127.00, \"premium\": 4.60, \"n\": 1000, \"action\": \"sell\"},\n", 86 | " {\n", 87 | " \"type\": \"call\",\n", 88 | " \"strike\": 127.00,\n", 89 | " \"premium\": 5.90,\n", 90 | " \"n\": 1000,\n", 91 | " \"action\": \"buy\",\n", 92 | " \"expiration\": dt.date(2021, 2, 12),\n", 93 | " },\n", 94 | "]\n", 95 | "\n", 96 | "inputs = {\n", 97 | " \"stock_price\": stock_price,\n", 98 | " \"start_date\": start_date,\n", 99 | " \"target_date\": target_date,\n", 100 | " \"volatility\": volatility,\n", 101 | " \"interest_rate\": interest_rate,\n", 102 | " \"min_stock\": min_stock,\n", 103 | " \"max_stock\": max_stock,\n", 104 | " \"strategy\": strategy,\n", 105 | "}" 106 | ] 107 | }, 108 | { 109 | "cell_type": "code", 110 | "execution_count": 4, 111 | "metadata": { 112 | "ExecuteTime": { 113 | "end_time": "2024-03-12T13:22:23.858251Z", 114 | "start_time": "2024-03-12T13:22:23.848088Z" 115 | } 116 | }, 117 | "outputs": [ 118 | { 119 | "name": "stdout", 120 | "output_type": "stream", 121 | "text": [ 122 | "CPU times: total: 375 ms\n", 123 | "Wall time: 485 ms\n" 124 | ] 125 | } 126 | ], 127 | "source": [ 128 | "%%time\n", 129 | "out = run_strategy(inputs)" 130 | ] 131 | }, 132 | { 133 | "cell_type": "code", 134 | "execution_count": 5, 135 | "metadata": { 136 | "ExecuteTime": { 137 | "end_time": "2024-03-12T13:22:31.185260Z", 138 | "start_time": "2024-03-12T13:22:30.357975Z" 139 | } 140 | }, 141 | "outputs": [ 142 | { 143 | "name": "stdout", 144 | "output_type": "stream", 145 | "text": [ 146 | "Profit/Loss diagram:\n", 147 | "--------------------\n", 148 | "The vertical green dashed line corresponds to the position of the stock's spot price. The right and left arrow markers indicate the strike prices of calls and puts, respectively, with blue representing long and red representing short positions.\n" 149 | ] 150 | }, 151 | { 152 | "data": { 153 | "image/png": "iVBORw0KGgoAAAANSUhEUgAAAnYAAAHWCAYAAAD6oMSKAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjAsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvlHJYcgAAAAlwSFlzAAAPYQAAD2EBqD+naQAAV89JREFUeJzt3QeUFFXWwPHLRCYwgGTJSM5ZUQFRFFCCoKiYwLisropZTKCui4oJ17Tqt6KrGEARQVGQJFEBJWclZ5A0gWGY6e/ch1V2w8wwoburu/r/O6d8r7truh8l1Nx+4b4SHo/HIwAAAAh7UU43AAAAAP5BYAcAAOASBHYAAAAuQWAHAADgEgR2AAAALkFgBwAA4BIEdgAAAC5B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zZsp7ExERP3759PTt37vREotNdz507d3oGDRrkOfPMM831bNCggeell14y91W3Xc8S+h+ng0sAAAAUH3PsAAAAXILADgAAwCUI7AAAAFyCwA4AAMAlCOwAAABcgsAOAADAJQjsAAAAXILADgAAwCUI7AAggEaPHi1lypQJymfpdlO6dd/JG5kDiBwEdgAiwt69e+Xvf/+72TcyPj7e7GParVs3mTt3rn2OBkVfffWVhKtzzz1Xdu7cafa9BBCZYpxuAAAEwxVXXCHHjh2TDz74QOrUqSO7d++WadOmyf79+8UNsrKyJC4uzgSsACIXPXYAXE+HJmfPni3PP/+8dOnSRWrWrCnt27eXoUOHSu/evc05tWrVMmXfvn1Nz531WL311lty1llnmcCpQYMG8r///e+U9//b3/4mlSpVkpIlS0rTpk1l0qRJefYctm3b1nxOZmZmrufoZz/zzDMyYMAASUpKkqpVq8obb7zhc462Udul7ddznn322VyHYrVH8oILLpDExEQpW7as6aU8cOCAeS0nJ0dGjBghtWvXloSEBGnRooWMGzeuyNcZgPMI7AC4XnJysjl0mDWvYGrhwoWmfP/9981wpvV4/Pjxcs8998j9998vK1asMAHcTTfdJDNmzLCDox49epgA6qOPPpJVq1bJc889J9HR0ad8xtatW6Vjx44m8NMASoeE8zJy5EgTaP3666/yyCOPmDZMnTrV55zhw4ebAHH58uVy8803n/IeS5YskYsuukgaN24s8+fPlzlz5kivXr0kOzvbvK5B3Ycffihvv/22rFy5Uu699165/vrrZdasWYW6vgBCiAcAIsC4ceM8ZcuW9ZQsWdJz7rnneoYOHepZunSpzzl6Sxw/frzPc3rubbfd5vNc//79PZdeeqmpf//9956oqCjP2rVrc/3c999/31O6dGnPmjVrPNWrV/fcfffdnpycnHzbWrNmTU/37t19nrv66qs9PXr08GnrkCFDfM6ZMWOGef7AgQPm8YABAzznnXderp9x9OhRT2JiomfevHk+z99yyy3m5wCEJ3rsAETMHLsdO3bI119/Ld27dzfDlq1btzarVvOzevVqOe+883ye08f6vNUrVq1aNalfv36e75GRkWF66vr16yejRo0yw6Wn06FDh1MeW59p0SHd/Fg9drnZsGGDpKeny8UXX2z3aOqhPXi//fbbadsHIDSxeAJAxND5bxrI6PHEE0/IrbfeKsOGDZNBgwYV+T11btrp6JBr165dzby7Bx980MyZ8wedW1fUtqWmpprym2++OaU9+Q0RAwht9NgBiFg69ywtLc1+HBsba88/szRq1MgnJYrSx/qzqnnz5rJt2zZZt25dnp8TFRVlFly0adPGLN7QnsPTWbBgwSmPtS2FoW3Tlb+50fZrALdlyxapW7euz1G9evVCfQ6A0EGPHQDX05Qm/fv3NwsMNNgpVaqULFq0SF544QXp06ePz2pUDYR0qFWDHl1Fqj1sV111lbRq1cr0uk2cOFG+/PJL+eGHH8zPdO7cWTp16mSGel9++WUTGK1Zs8YMt+qQr0UXU3z88cdmpeuFF15ohoLzS02iwaO27/LLLzeLJsaOHWt61wpDV/02a9ZM7rjjDhk8eLBZ1auLPvRalC9fXh544AGzYEIXgJx//vly6NAh87kpKSkycODAIl1rAA5zepIfAASaLhR45JFHPK1btzYLGXTRQIMGDTyPP/64Jz093T7v66+/9tStW9cTExNjFjBY3nzzTU+dOnU8sbGxnvr163s+/PBDn/ffv3+/56abbvKUK1fOLM5o2rSpZ9KkST6LJyxZWVmefv36eRo1auTZvXt3ru3Vz37qqafMIg1ta+XKlT2jRo067UKPkxdPqJkzZ5oFIPHx8Z4yZcp4unXrZr+uizheffVVcy30z1ahQgXz+qxZs4p4pQE4rYT+x+ngEgAgPj2HQ4YMMQcAFAZz7AAAAFyCwA4AAMAlGIoFAABwCXrsAAAAXILADgAAwCUI7AAAAFyCwA4AAMAlCOwAAABcgsAOAADAJQjsAAAAXILADgAAwCUI7AAAAMQd/h/+UltV8FPnDgAAAABJRU5ErkJggg==", 154 | "text/plain": [ 155 | "
" 156 | ] 157 | }, 158 | "metadata": {}, 159 | "output_type": "display_data" 160 | } 161 | ], 162 | "source": [ 163 | "plot_pl(out)" 164 | ] 165 | }, 166 | { 167 | "cell_type": "code", 168 | "execution_count": 6, 169 | "metadata": { 170 | "ExecuteTime": { 171 | "end_time": "2024-03-12T13:22:34.374344Z", 172 | "start_time": "2024-03-12T13:22:34.372552Z" 173 | } 174 | }, 175 | "outputs": [ 176 | { 177 | "name": "stdout", 178 | "output_type": "stream", 179 | "text": [ 180 | "Probability of profit: 0.599111819020198\n", 181 | "Profit ranges: [(118.87, 136.15)]\n", 182 | "Per leg cost: [4600.0, -5900.0]\n", 183 | "Strategy cost: -1300.0\n", 184 | "Minimum return in the domain: -1300.0000000000146\n", 185 | "Maximum return in the domain: 3009.999999999999\n", 186 | "Implied volatility: [0.47300000000000003, 0.419]\n", 187 | "In the money probability: [0.4895105709759477, 0.4805997906939539]\n", 188 | "Delta: [-0.5216914758915705, 0.5273457614638198]\n", 189 | "Gamma: [0.03882722919950356, 0.02669940508461828]\n", 190 | "Theta: [0.22727438444823292, -0.15634971608107964]\n", 191 | "Vega: [0.09571294014902997, 0.1389462831961853]\n", 192 | "Rho: [-0.022202087247849632, 0.046016214466188525]\n", 193 | "\n" 194 | ] 195 | } 196 | ], 197 | "source": [ 198 | "print(out)" 199 | ] 200 | }, 201 | { 202 | "cell_type": "code", 203 | "execution_count": null, 204 | "metadata": {}, 205 | "outputs": [], 206 | "source": [] 207 | } 208 | ], 209 | "metadata": { 210 | "kernelspec": { 211 | "display_name": "Python 3 (ipykernel)", 212 | "language": "python", 213 | "name": "python3" 214 | }, 215 | "language_info": { 216 | "codemirror_mode": { 217 | "name": "ipython", 218 | "version": 3 219 | }, 220 | "file_extension": ".py", 221 | "mimetype": "text/x-python", 222 | "name": "python", 223 | "nbconvert_exporter": "python", 224 | "pygments_lexer": "ipython3", 225 | "version": "3.11.9" 226 | } 227 | }, 228 | "nbformat": 4, 229 | "nbformat_minor": 4 230 | } 231 | -------------------------------------------------------------------------------- /optionlab.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/rgaveiga/optionlab/b4af9805ea7658b9e0d6d96cc11af83e17c3903d/optionlab.png -------------------------------------------------------------------------------- /optionlab/.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ 2 | old -------------------------------------------------------------------------------- /optionlab/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | ## OptionLab is... 3 | 4 | ... a Python library designed as a research tool for quickly evaluating options 5 | strategy ideas. It is intended for a wide range of users, from individuals learning 6 | about options trading to developers of quantitative strategies. 7 | 8 | **OptionLab** calculations can produce a number of useful outputs: 9 | 10 | - the profit/loss profile of the strategy on a user-defined target date, 11 | 12 | - the range of stock prices for which the strategy is profitable, 13 | 14 | - the Greeks associated with each leg of the strategy, 15 | 16 | - the resulting debit or credit on the trading account, 17 | 18 | - the maximum and minimum returns within a specified lower and higher price range 19 | of the underlying asset, 20 | 21 | - the expected profit and expected loss, and 22 | 23 | - an estimate of the strategy's probability of profit. 24 | 25 | The probability of profit (PoP) of the strategy on the user-defined target date 26 | is calculated analytically by default using the Black-Scholes model. Alternatively, 27 | the user can provide an array of terminal underlying asset prices obtained from 28 | other sources (e.g., the Heston model, a Laplace distribution, or a Machine Learning/Deep Learning model) 29 | to be used in the calculations instead of the Black-Scholes model. This allows 30 | **OptionLab** to function as a calculator that supports a variety of pricing 31 | models. 32 | 33 | An advanced feature of **OptionLab** that provides great flexibility in building 34 | complex dynamic strategies is the ability to include previously created positions 35 | as legs in a new strategy. Popular strategies that can benefit from this feature 36 | include the Wheel and Covered Call strategies. 37 | 38 | ## OptionLab is not... 39 | 40 | ... a platform for direct order execution. This capability has not been and 41 | probably will not be implemented. 42 | 43 | Backtesting and trade simulation using Monte Carlo have also not (yet) been 44 | implemented in the API. 45 | 46 | That being said, nothing prevents **OptionLab** from being integrated into an 47 | options quant trader's workflow alongside other tools. 48 | 49 | ## Installation 50 | 51 | The easiest way to install **OptionLab** is using **pip**: 52 | 53 | ``` 54 | pip install optionlab 55 | ``` 56 | 57 | ## Quickstart 58 | 59 | **OptionLab** is designed with ease of use in mind. An options strategy can be 60 | defined and evaluated with just a few lines of Python code. The API is streamlined, 61 | and the learning curve is minimal. 62 | 63 | The evaluation of a strategy is done by calling the `optionlab.engine.run_strategy` 64 | function provided by the library. This function receives the input data either 65 | as a dictionary or an `optionlab.models.Inputs` object. 66 | 67 | For example, let's say we wanted to calculate the probability of profit for naked 68 | calls on Apple stocks expiring on December 17, 2021. The strategy setup consisted 69 | of selling 100 175.00 strike calls for 1.15 each on November 22, 2021. 70 | 71 | The input data for this strategy can be provided in a dictionary as follows: 72 | 73 | ```python 74 | input_data = { 75 | "stock_price": 164.04, 76 | "start_date": "2021-11-22", 77 | "target_date": "2021-12-17", 78 | "volatility": 0.272, 79 | "interest_rate": 0.0002, 80 | "min_stock": 120, 81 | "max_stock": 200, 82 | "strategy": [ 83 | { 84 | "type": "call", 85 | "strike": 175.0, 86 | "premium": 1.15, 87 | "n": 100, 88 | "action":"sell" 89 | } 90 | ], 91 | } 92 | ``` 93 | 94 | Alternatively, the input data could be defined as the `optionlab.models.Inputs` 95 | object below: 96 | 97 | ```python 98 | from optionlab import Inputs 99 | 100 | input_data = Inputs( 101 | stock_price = 164.04, 102 | start_date = "2021-11-22", 103 | target_date = "2021-12-17", 104 | volatility = 0.272, 105 | interest_rate = 0.0002, 106 | min_stock = 120, 107 | max_stock = 200, 108 | strategy = [ 109 | { 110 | "type": "call", 111 | "strike": 175.0, 112 | "premium": 1.15, 113 | "n": 100, 114 | "action":"sell" 115 | } 116 | ], 117 | ) 118 | ``` 119 | 120 | In both cases, the strategy itself is a list of dictionaries, where each dictionary 121 | defines a leg in the strategy. The fields in a leg, depending on the type of the 122 | leg, are described in `optionlab.models.Stock`, `optionlab.models.Option`, and 123 | `optionlab.models.ClosedPosition`. 124 | 125 | After defining the input data, we pass it to the `run_strategy` function as shown 126 | below: 127 | 128 | ```python 129 | from optionlab import run_strategy, plot_pl 130 | 131 | out = run_strategy(input_data) 132 | 133 | print(out) 134 | 135 | plot_pl(out) 136 | ``` 137 | 138 | The variable `out` is an `optionlab.models.Outputs` object that contains the 139 | results from the calculations. By calling `print` with `out` as an argument, 140 | these results are displayed on screen. 141 | 142 | The `optionlab.plot.plot_pl` function, in turn, takes an `optionlab.models.Outputs` 143 | object as its argument and plots the profit/loss diagram for the strategy. 144 | 145 | ## Examples 146 | 147 | Examples for a number of popular options trading strategies can be found as 148 | Jupyter notebooks in the [examples](https://github.com/rgaveiga/optionlab/tree/main/examples) 149 | directory. 150 | """ 151 | 152 | from .models import ( 153 | Inputs, 154 | OptionType, 155 | Option, 156 | Outputs, 157 | ClosedPosition, 158 | ArrayInputs, 159 | TheoreticalModelInputs, 160 | BlackScholesModelInputs, 161 | LaplaceInputs, 162 | BlackScholesInfo, 163 | TheoreticalModel, 164 | FloatOrNdarray, 165 | StrategyLeg, 166 | StrategyLegType, 167 | Stock, 168 | Action, 169 | ) 170 | from .black_scholes import ( 171 | get_itm_probability, 172 | get_implied_vol, 173 | get_option_price, 174 | get_d1, 175 | get_d2, 176 | get_bs_info, 177 | get_vega, 178 | get_delta, 179 | get_gamma, 180 | get_theta, 181 | get_rho, 182 | ) 183 | from .engine import run_strategy 184 | from .plot import plot_pl 185 | from .price_array import create_price_array 186 | from .support import ( 187 | get_pl_profile, 188 | get_pl_profile_stock, 189 | get_pl_profile_bs, 190 | create_price_seq, 191 | get_pop, 192 | ) 193 | from .utils import ( 194 | get_nonbusiness_days, 195 | get_pl, 196 | pl_to_csv, 197 | ) 198 | 199 | 200 | VERSION = "1.4.3" 201 | 202 | __docformat__ = "markdown" 203 | __version__ = VERSION 204 | 205 | 206 | ALL = ( 207 | # models 208 | "Inputs", 209 | "OptionType", 210 | "Option", 211 | "Outputs", 212 | "ClosedPosition", 213 | "ArrayInputs", 214 | "TheoreticalModelInputs", 215 | "BlackScholesModelInputs", 216 | "LaplaceInputs", 217 | "BlackScholesInfo", 218 | "TheoreticalModel", 219 | "FloatOrNdarray", 220 | "StrategyLeg", 221 | "StrategyLegType", 222 | "Stock", 223 | "Action", 224 | # engine 225 | "run_strategy", 226 | # support 227 | "get_pl_profile", 228 | "get_pl_profile_stock", 229 | "get_pl_profile_bs", 230 | "create_price_seq", 231 | "get_pop", 232 | # black_scholes 233 | "get_d1", 234 | "get_d2", 235 | "get_option_price", 236 | "get_itm_probability", 237 | "get_implied_vol", 238 | "get_bs_info", 239 | "get_vega", 240 | "get_delta", 241 | "get_gamma", 242 | "get_theta", 243 | "get_rho", 244 | # plot 245 | "plot_pl", 246 | # price_array 247 | "create_price_array", 248 | # utils 249 | "get_nonbusiness_days", 250 | "get_pl", 251 | "pl_to_csv", 252 | ) 253 | """@private""" 254 | 255 | 256 | def __dir__() -> "list[str]": 257 | return list(ALL) 258 | -------------------------------------------------------------------------------- /optionlab/black_scholes.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module defines functions that calculate quantities, such as option prices 3 | and the Greeks, related to the Black-Scholes model. 4 | """ 5 | 6 | from __future__ import division 7 | 8 | from scipy import stats 9 | from numpy import exp, round, arange, abs, argmin, pi 10 | from numpy.lib.scimath import log, sqrt 11 | 12 | from optionlab.models import BlackScholesInfo, OptionType, FloatOrNdarray 13 | 14 | 15 | def get_bs_info( 16 | s: float, 17 | x: FloatOrNdarray, 18 | r: float, 19 | vol: float, 20 | years_to_maturity: float, 21 | y: float = 0.0, 22 | ) -> BlackScholesInfo: 23 | """ 24 | Provides information about call and put options calculated using the Black-Scholes 25 | formula. 26 | 27 | Parameters 28 | ---------- 29 | `s`: stock price. 30 | 31 | `x`: strike price(s). 32 | 33 | `r`: annualized risk-free interest rate. 34 | 35 | `vol`: annualized volatility. 36 | 37 | `years_to_maturity`: time remaining to maturity, in years. 38 | 39 | `y`: annualized dividend yield. 40 | 41 | Returns 42 | ------- 43 | Information calculated using the Black-Scholes formula. 44 | """ 45 | 46 | d1 = get_d1(s, x, r, vol, years_to_maturity, y) 47 | d2 = get_d2(s, x, r, vol, years_to_maturity, y) 48 | call_price = get_option_price("call", s, x, r, years_to_maturity, d1, d2, y) 49 | put_price = get_option_price("put", s, x, r, years_to_maturity, d1, d2, y) 50 | call_delta = get_delta("call", d1, years_to_maturity, y) 51 | put_delta = get_delta("put", d1, years_to_maturity, y) 52 | call_theta = get_theta("call", s, x, r, vol, years_to_maturity, d1, d2, y) 53 | put_theta = get_theta("put", s, x, r, vol, years_to_maturity, d1, d2, y) 54 | gamma = get_gamma(s, vol, years_to_maturity, d1, y) 55 | vega = get_vega(s, years_to_maturity, d1, y) 56 | call_rho = get_rho("call", x, r, years_to_maturity, d2) 57 | put_rho = get_rho("put", x, r, years_to_maturity, d2) 58 | call_itm_prob = get_itm_probability("call", d2, years_to_maturity, y) 59 | put_itm_prob = get_itm_probability("put", d2, years_to_maturity, y) 60 | 61 | return BlackScholesInfo( 62 | call_price=call_price, 63 | put_price=put_price, 64 | call_delta=call_delta, 65 | put_delta=put_delta, 66 | call_theta=call_theta, 67 | put_theta=put_theta, 68 | gamma=gamma, 69 | vega=vega, 70 | call_rho=call_rho, 71 | put_rho=put_rho, 72 | call_itm_prob=call_itm_prob, 73 | put_itm_prob=put_itm_prob, 74 | ) 75 | 76 | 77 | def get_option_price( 78 | option_type: OptionType, 79 | s0: FloatOrNdarray, 80 | x: FloatOrNdarray, 81 | r: float, 82 | years_to_maturity: float, 83 | d1: FloatOrNdarray, 84 | d2: FloatOrNdarray, 85 | y: float = 0.0, 86 | ) -> FloatOrNdarray: 87 | """ 88 | Returns the price of an option. 89 | 90 | Parameters 91 | ---------- 92 | `option_type`: either *'call'* or *'put'*. 93 | 94 | `s0`: spot price(s) of the underlying asset. 95 | 96 | `x`: strike price(s). 97 | 98 | `r`: annualize risk-free interest rate. 99 | 100 | `years_to_maturity`: time remaining to maturity, in years. 101 | 102 | `d1`: `d1` in Black-Scholes formula. 103 | 104 | `d2`: `d2` in Black-Scholes formula. 105 | 106 | `y`: annualized dividend yield. 107 | 108 | Returns 109 | ------- 110 | Option price(s). 111 | """ 112 | 113 | s = s0 * exp(-y * years_to_maturity) 114 | 115 | if option_type == "call": 116 | return round( 117 | s * stats.norm.cdf(d1) 118 | - x * exp(-r * years_to_maturity) * stats.norm.cdf(d2), 119 | 2, 120 | ) 121 | elif option_type == "put": 122 | return round( 123 | x * exp(-r * years_to_maturity) * stats.norm.cdf(-d2) 124 | - s * stats.norm.cdf(-d1), 125 | 2, 126 | ) 127 | else: 128 | raise ValueError("Option type must be either 'call' or 'put'!") 129 | 130 | 131 | def get_delta( 132 | option_type: OptionType, 133 | d1: FloatOrNdarray, 134 | years_to_maturity: float, 135 | y: float = 0.0, 136 | ) -> FloatOrNdarray: 137 | """ 138 | Returns the option's Greek Delta. 139 | 140 | Parameters 141 | ---------- 142 | `option_type`: either *'call'* or *'put'*. 143 | 144 | `d1`: `d1` in Black-Scholes formula. 145 | 146 | `years_to_maturity`: time remaining to maturity, in years. 147 | 148 | `y`: annualized dividend yield. 149 | 150 | Returns 151 | ------- 152 | Option's Greek Delta. 153 | """ 154 | 155 | yfac = exp(-y * years_to_maturity) 156 | 157 | if option_type == "call": 158 | return yfac * stats.norm.cdf(d1) 159 | elif option_type == "put": 160 | return yfac * (stats.norm.cdf(d1) - 1.0) 161 | else: 162 | raise ValueError("Option must be either 'call' or 'put'!") 163 | 164 | 165 | def get_gamma( 166 | s0: float, 167 | vol: float, 168 | years_to_maturity: float, 169 | d1: FloatOrNdarray, 170 | y: float = 0.0, 171 | ) -> FloatOrNdarray: 172 | """ 173 | Returns the option's Greek Gamma. 174 | 175 | Parameters 176 | ---------- 177 | `s0`: spot price of the underlying asset. 178 | 179 | `vol`: annualized volatitily. 180 | 181 | `years_to_maturity`: time remaining to maturity, in years. 182 | 183 | `d1`: `d1` in Black-Scholes formula. 184 | 185 | `y`: annualized divident yield. 186 | 187 | Returns 188 | ------- 189 | Option's Greek Gamma. 190 | """ 191 | 192 | yfac = exp(-y * years_to_maturity) 193 | 194 | cdf_d1_prime = exp(-0.5 * d1 * d1) / sqrt(2.0 * pi) 195 | 196 | return yfac * cdf_d1_prime / (s0 * vol * sqrt(years_to_maturity)) 197 | 198 | 199 | def get_theta( 200 | option_type: OptionType, 201 | s0: float, 202 | x: FloatOrNdarray, 203 | r: float, 204 | vol: float, 205 | years_to_maturity: float, 206 | d1: FloatOrNdarray, 207 | d2: FloatOrNdarray, 208 | y: float = 0.0, 209 | ) -> FloatOrNdarray: 210 | """ 211 | Returns the option's Greek Theta. 212 | 213 | Parameters 214 | ---------- 215 | `option_type`: either *'call'* or *'put'*. 216 | 217 | `s0`: spot price of the underlying asset. 218 | 219 | `x`: strike price(s). 220 | 221 | `r`: annualized risk-free interest rate. 222 | 223 | `vol`: annualized volatility. 224 | 225 | `years_to_maturity`: time remaining to maturity, in years. 226 | 227 | `d1`: `d1` in Black-Scholes formula. 228 | 229 | `d2`: `d2` in Black-Scholes formula. 230 | 231 | `y`: annualized dividend yield. 232 | 233 | Returns 234 | ------- 235 | Option's Greek Theta. 236 | """ 237 | 238 | s = s0 * exp(-y * years_to_maturity) 239 | 240 | cdf_d1_prime = exp(-0.5 * d1 * d1) / sqrt(2.0 * pi) 241 | 242 | if option_type == "call": 243 | return -( 244 | s * vol * cdf_d1_prime / (2.0 * sqrt(years_to_maturity)) 245 | + r * x * exp(-r * years_to_maturity) * stats.norm.cdf(d2) 246 | - y * s * stats.norm.cdf(d1) 247 | ) 248 | elif option_type == "put": 249 | return -( 250 | s * vol * cdf_d1_prime / (2.0 * sqrt(years_to_maturity)) 251 | - r * x * exp(-r * years_to_maturity) * stats.norm.cdf(-d2) 252 | + y * s * stats.norm.cdf(-d1) 253 | ) 254 | else: 255 | raise ValueError("Option type must be either 'call' or 'put'!") 256 | 257 | 258 | def get_vega( 259 | s0: float, 260 | years_to_maturity: float, 261 | d1: FloatOrNdarray, 262 | y: float = 0.0, 263 | ) -> FloatOrNdarray: 264 | """ 265 | Returns the option's Greek Vega. 266 | 267 | Parameters 268 | ---------- 269 | `s0`: spot price of the underlying asset. 270 | 271 | `years_to_maturity`: time remaining to maturity, in years. 272 | 273 | `d1`: `d1` in Black-Scholes formula. 274 | 275 | `y`: annualized dividend yield. 276 | 277 | Returns 278 | ------- 279 | Option's Greek Vega. 280 | """ 281 | 282 | s = s0 * exp(-y * years_to_maturity) 283 | 284 | cdf_d1_prime = exp(-0.5 * d1 * d1) / sqrt(2.0 * pi) 285 | 286 | return s * cdf_d1_prime * sqrt(years_to_maturity) / 100 287 | 288 | 289 | def get_rho( 290 | option_type: OptionType, 291 | x: FloatOrNdarray, 292 | r: float, 293 | years_to_maturity: float, 294 | d2: FloatOrNdarray, 295 | ) -> FloatOrNdarray: 296 | """ 297 | Returns the option's Greek Rho. 298 | 299 | Parameters 300 | ---------- 301 | `option_type`: either *'call'* or *'put'*. 302 | 303 | `x`: strike price(s). 304 | 305 | `r`: annualized risk-free interest rate. 306 | 307 | `years_to_maturity`: time remaining to maturity, in years. 308 | 309 | `d2`: `d2` in Black-Scholes formula. 310 | 311 | Returns 312 | ------- 313 | Option's Greek Rho. 314 | """ 315 | 316 | if option_type == "call": 317 | return ( 318 | x 319 | * years_to_maturity 320 | * exp(-r * years_to_maturity) 321 | * stats.norm.cdf(d2) 322 | / 100 323 | ) 324 | elif option_type == "put": 325 | return ( 326 | -x 327 | * years_to_maturity 328 | * exp(-r * years_to_maturity) 329 | * stats.norm.cdf(-d2) 330 | / 100 331 | ) 332 | else: 333 | raise ValueError("Option must be either 'call' or 'put'!") 334 | 335 | 336 | def get_d1( 337 | s0: FloatOrNdarray, 338 | x: FloatOrNdarray, 339 | r: float, 340 | vol: FloatOrNdarray, 341 | years_to_maturity: float, 342 | y: float = 0.0, 343 | ) -> FloatOrNdarray: 344 | """ 345 | Returns `d1` used in Black-Scholes formula. 346 | 347 | Parameters 348 | ---------- 349 | `s0`: spot price(s) of the underlying asset. 350 | 351 | `x`: strike price(s). 352 | 353 | `r`: annualized risk-free interest rate. 354 | 355 | `vol`: annualized volatility(ies). 356 | 357 | `years_to_maturity`: time remaining to maturity, in years. 358 | 359 | `y`: annualized divident yield. 360 | 361 | Returns 362 | ------- 363 | `d1` in Black-Scholes formula. 364 | """ 365 | 366 | return (log(s0 / x) + (r - y + vol * vol / 2.0) * years_to_maturity) / ( 367 | vol * sqrt(years_to_maturity) 368 | ) 369 | 370 | 371 | def get_d2( 372 | s0: FloatOrNdarray, 373 | x: FloatOrNdarray, 374 | r: float, 375 | vol: FloatOrNdarray, 376 | years_to_maturity: float, 377 | y: float = 0.0, 378 | ) -> FloatOrNdarray: 379 | """ 380 | Returns `d2` used in Black-Scholes formula. 381 | 382 | Parameters 383 | ---------- 384 | `s0`: spot price(s) of the underlying asset. 385 | 386 | `x`: strike price(s). 387 | 388 | `r`: annualized risk-free interest rate. 389 | 390 | `vol`: annualized volatility(ies). 391 | 392 | `years_to_maturity`: time remaining to maturity, in years. 393 | 394 | `y`: annualized divident yield. 395 | 396 | Returns 397 | ------- 398 | `d2` in Black-Scholes formula. 399 | """ 400 | 401 | return (log(s0 / x) + (r - y - vol * vol / 2.0) * years_to_maturity) / ( 402 | vol * sqrt(years_to_maturity) 403 | ) 404 | 405 | 406 | def get_implied_vol( 407 | option_type: OptionType, 408 | oprice: float, 409 | s0: float, 410 | x: float, 411 | r: float, 412 | years_to_maturity: float, 413 | y: float = 0.0, 414 | ) -> float: 415 | """ 416 | Returns the implied volatility of an option. 417 | 418 | Parameters 419 | ---------- 420 | `option_type`: either *'call'* or *'put'*. 421 | 422 | `oprice`: market price of an option. 423 | 424 | `s0`: spot price of the underlying asset. 425 | 426 | `x`: strike price. 427 | 428 | `r`: annualized risk-free interest rate. 429 | 430 | `years_to_maturity`: time remaining to maturity, in years. 431 | 432 | `y`: annualized dividend yield. 433 | 434 | Returns 435 | ------- 436 | Option's implied volatility. 437 | """ 438 | 439 | vol = 0.001 * arange(1, 1001) 440 | d1 = get_d1(s0, x, r, vol, years_to_maturity, y) 441 | d2 = get_d2(s0, x, r, vol, years_to_maturity, y) 442 | dopt = abs( 443 | get_option_price(option_type, s0, x, r, years_to_maturity, d1, d2, y) - oprice 444 | ) 445 | 446 | return vol[argmin(dopt)] 447 | 448 | 449 | def get_itm_probability( 450 | option_type: OptionType, 451 | d2: FloatOrNdarray, 452 | years_to_maturity: float, 453 | y: float = 0.0, 454 | ) -> FloatOrNdarray: 455 | """ 456 | Returns the probability(ies) that the option(s) will expire in-the-money (ITM). 457 | 458 | Parameters 459 | ---------- 460 | `option_type`: either *'call'* or *'put'*. 461 | 462 | `d2`: `d2` in Black-Scholes formula. 463 | 464 | `years_to_maturity`: time remaining to maturity, in years. 465 | 466 | `y`: annualized dividend yield. 467 | 468 | Returns 469 | ------- 470 | Probability(ies) that the option(s) will expire in-the-money (ITM). 471 | """ 472 | 473 | yfac = exp(-y * years_to_maturity) 474 | 475 | if option_type == "call": 476 | return yfac * stats.norm.cdf(d2) 477 | elif option_type == "put": 478 | return yfac * stats.norm.cdf(-d2) 479 | else: 480 | raise ValueError("Option type must be either 'call' or 'put'!") 481 | -------------------------------------------------------------------------------- /optionlab/engine.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module defines the `run_strategy` function. 3 | 4 | Given input data provided as either an `optionlab.models.Inputs` object or a dictionary, 5 | `run_strategy` returns the results of an options strategy calculation (e.g., the 6 | probability of profit on the target date) as an `optionlab.models.Outputs` object. 7 | """ 8 | 9 | from __future__ import division 10 | from __future__ import print_function 11 | 12 | import datetime as dt 13 | 14 | from numpy import zeros, array 15 | 16 | 17 | from optionlab.black_scholes import get_bs_info, get_implied_vol 18 | from optionlab.models import ( 19 | Inputs, 20 | Action, 21 | Option, 22 | Stock, 23 | ClosedPosition, 24 | Outputs, 25 | BlackScholesModelInputs, 26 | ArrayInputs, 27 | OptionType, 28 | EngineData, 29 | PoPOutputs, 30 | ) 31 | from optionlab.support import ( 32 | get_pl_profile, 33 | get_pl_profile_stock, 34 | get_pl_profile_bs, 35 | create_price_seq, 36 | get_pop, 37 | ) 38 | from optionlab.utils import get_nonbusiness_days 39 | 40 | 41 | def run_strategy(inputs_data: Inputs | dict) -> Outputs: 42 | """ 43 | Runs the calculation for a strategy. 44 | 45 | Parameters 46 | ---------- 47 | `inputs_data`: input data used in the strategy calculation. 48 | 49 | Returns 50 | ------- 51 | Output data from the strategy calculation. 52 | """ 53 | 54 | inputs = ( 55 | inputs_data 56 | if isinstance(inputs_data, Inputs) 57 | else Inputs.model_validate(inputs_data) 58 | ) 59 | 60 | data = _init_inputs(inputs) 61 | 62 | data = _run(data) 63 | 64 | return _generate_outputs(data) 65 | 66 | 67 | def _init_inputs(inputs: Inputs) -> EngineData: 68 | data = EngineData( 69 | stock_price_array=create_price_seq(inputs.min_stock, inputs.max_stock), 70 | terminal_stock_prices=inputs.array if inputs.model == "array" else array([]), 71 | inputs=inputs, 72 | ) 73 | 74 | data.days_in_year = ( 75 | inputs.business_days_in_year if inputs.discard_nonbusiness_days else 365 76 | ) 77 | 78 | if inputs.start_date and inputs.target_date: 79 | if inputs.discard_nonbusiness_days: 80 | n_discarded_days = get_nonbusiness_days( 81 | inputs.start_date, inputs.target_date, inputs.country 82 | ) 83 | else: 84 | n_discarded_days = 0 85 | 86 | data.days_to_target = ( 87 | (inputs.target_date - inputs.start_date).days + 1 - n_discarded_days 88 | ) 89 | else: 90 | data.days_to_target = inputs.days_to_target_date 91 | 92 | for i, strategy in enumerate(inputs.strategy): 93 | data.type.append(strategy.type) 94 | 95 | if isinstance(strategy, Option): 96 | data.strike.append(strategy.strike) 97 | data.premium.append(strategy.premium) 98 | data.n.append(strategy.n) 99 | data.action.append(strategy.action) 100 | data.previous_position.append(strategy.prev_pos or 0.0) 101 | 102 | if not strategy.expiration: 103 | data.days_to_maturity.append(data.days_to_target) 104 | data.use_bs.append(False) 105 | elif isinstance(strategy.expiration, dt.date) and inputs.start_date: 106 | if inputs.discard_nonbusiness_days: 107 | n_discarded_days = get_nonbusiness_days( 108 | inputs.start_date, strategy.expiration, inputs.country 109 | ) 110 | else: 111 | n_discarded_days = 0 112 | 113 | data.days_to_maturity.append( 114 | (strategy.expiration - inputs.start_date).days 115 | + 1 116 | - n_discarded_days 117 | ) 118 | 119 | data.use_bs.append(strategy.expiration != inputs.target_date) 120 | elif isinstance(strategy.expiration, int): 121 | if strategy.expiration >= data.days_to_target: 122 | data.days_to_maturity.append(strategy.expiration) 123 | 124 | data.use_bs.append(strategy.expiration != data.days_to_target) 125 | else: 126 | raise ValueError( 127 | "Days remaining to maturity must be greater than or equal to the number of days remaining to the target date!" 128 | ) 129 | else: 130 | raise ValueError("Expiration must be a date, an int or None.") 131 | 132 | elif isinstance(strategy, Stock): 133 | data.n.append(strategy.n) 134 | data.action.append(strategy.action) 135 | data.previous_position.append(strategy.prev_pos or 0.0) 136 | data.strike.append(0.0) 137 | data.premium.append(0.0) 138 | data.use_bs.append(False) 139 | data.days_to_maturity.append(-1) 140 | 141 | elif isinstance(strategy, ClosedPosition): 142 | data.previous_position.append(strategy.prev_pos) 143 | data.strike.append(0.0) 144 | data.n.append(0) 145 | data.premium.append(0.0) 146 | data.action.append("n/a") 147 | data.use_bs.append(False) 148 | data.days_to_maturity.append(-1) 149 | else: 150 | raise ValueError("Type must be 'call', 'put', 'stock' or 'closed'!") 151 | 152 | return data 153 | 154 | 155 | def _run(data: EngineData) -> EngineData: 156 | inputs = data.inputs 157 | 158 | time_to_target = data.days_to_target / data.days_in_year 159 | data.cost = [0.0] * len(data.type) 160 | 161 | data.profit = zeros((len(data.type), data.stock_price_array.shape[0])) 162 | data.strategy_profit = zeros(data.stock_price_array.shape[0]) 163 | 164 | if inputs.model == "array": 165 | data.profit_mc = zeros((len(data.type), data.terminal_stock_prices.shape[0])) 166 | data.strategy_profit_mc = zeros(data.terminal_stock_prices.shape[0]) 167 | 168 | pop_inputs: BlackScholesModelInputs | ArrayInputs 169 | pop_out: PoPOutputs 170 | 171 | for i, type in enumerate(data.type): 172 | if type in ("call", "put"): 173 | _run_option_calcs(data, i) 174 | elif type == "stock": 175 | _run_stock_calcs(data, i) 176 | elif type == "closed": 177 | _run_closed_position_calcs(data, i) 178 | 179 | data.strategy_profit += data.profit[i] 180 | 181 | if inputs.model == "array": 182 | data.strategy_profit_mc += data.profit_mc[i] 183 | 184 | if inputs.model == "black-scholes": 185 | pop_inputs = BlackScholesModelInputs( 186 | stock_price=inputs.stock_price, 187 | volatility=inputs.volatility, 188 | years_to_target_date=time_to_target, 189 | interest_rate=inputs.interest_rate, 190 | dividend_yield=inputs.dividend_yield, 191 | ) 192 | elif inputs.model == "array": 193 | pop_inputs = ArrayInputs(array=data.strategy_profit_mc) 194 | else: 195 | raise ValueError("Model is not valid!") 196 | 197 | pop_out = get_pop(data.stock_price_array, data.strategy_profit, pop_inputs) 198 | 199 | data.profit_probability = pop_out.probability_of_reaching_target 200 | data.expected_profit = pop_out.expected_return_above_target 201 | data.expected_loss = pop_out.expected_return_below_target 202 | data.profit_ranges = pop_out.reaching_target_range 203 | 204 | if inputs.profit_target is not None and inputs.profit_target > 0.01: 205 | pop_out_prof_targ = get_pop( 206 | data.stock_price_array, 207 | data.strategy_profit, 208 | pop_inputs, 209 | inputs.profit_target, 210 | ) 211 | data.profit_target_probability = ( 212 | pop_out_prof_targ.probability_of_reaching_target 213 | ) 214 | data.profit_target_ranges = pop_out_prof_targ.reaching_target_range 215 | 216 | if inputs.loss_limit is not None and inputs.loss_limit < 0.0: 217 | pop_out_loss_lim = get_pop( 218 | data.stock_price_array, 219 | data.strategy_profit, 220 | pop_inputs, 221 | inputs.loss_limit + 0.01, 222 | ) 223 | data.loss_limit_probability = pop_out_loss_lim.probability_of_missing_target 224 | data.loss_limit_ranges = pop_out_loss_lim.missing_target_range 225 | 226 | return data 227 | 228 | 229 | def _run_option_calcs(data: EngineData, i: int) -> EngineData: 230 | inputs = data.inputs 231 | action: Action = data.action[i] # type: ignore 232 | type: OptionType = data.type[i] # type: ignore 233 | 234 | if data.previous_position[i] < 0.0: 235 | # Previous position is closed 236 | data.implied_volatility.append(0.0) 237 | data.itm_probability.append(0.0) 238 | data.delta.append(0.0) 239 | data.gamma.append(0.0) 240 | data.vega.append(0.0) 241 | data.theta.append(0.0) 242 | data.rho.append(0.0) 243 | 244 | cost = (data.premium[i] + data.previous_position[i]) * data.n[i] 245 | 246 | if data.action[i] == "buy": 247 | cost *= -1.0 248 | 249 | data.cost[i] = cost 250 | data.profit[i] += cost 251 | 252 | if inputs.model == "array": 253 | data.profit_mc[i] += cost 254 | 255 | return data 256 | 257 | time_to_maturity = data.days_to_maturity[i] / data.days_in_year 258 | bs = get_bs_info( 259 | inputs.stock_price, 260 | data.strike[i], 261 | inputs.interest_rate, 262 | inputs.volatility, 263 | time_to_maturity, 264 | inputs.dividend_yield, 265 | ) 266 | 267 | data.gamma.append( 268 | float(bs.gamma) 269 | ) # TODO: This is required because of mypy. Check later for workarounds, maybe using zero-dimensional numpy arrays 270 | data.vega.append(float(bs.vega)) 271 | 272 | data.implied_volatility.append( 273 | float( 274 | get_implied_vol( 275 | type, 276 | data.premium[i], 277 | inputs.stock_price, 278 | data.strike[i], 279 | inputs.interest_rate, 280 | time_to_maturity, 281 | inputs.dividend_yield, 282 | ) 283 | ) 284 | ) 285 | 286 | negative_multiplier = 1 if data.action[i] == "buy" else -1 287 | 288 | if type == "call": 289 | data.itm_probability.append(float(bs.call_itm_prob)) 290 | data.delta.append(float(bs.call_delta * negative_multiplier)) 291 | data.theta.append( 292 | float(bs.call_theta / data.days_in_year * negative_multiplier) 293 | ) 294 | data.rho.append(float(bs.call_rho * negative_multiplier)) 295 | else: 296 | data.itm_probability.append(float(bs.put_itm_prob)) 297 | data.delta.append(float(bs.put_delta * negative_multiplier)) 298 | data.theta.append(float(bs.put_theta / data.days_in_year * negative_multiplier)) 299 | data.rho.append(float(bs.put_rho * negative_multiplier)) 300 | 301 | if data.previous_position[i] > 0.0: # Premium of the open position 302 | opt_value = data.previous_position[i] 303 | else: # Current premium 304 | opt_value = data.premium[i] 305 | 306 | if data.use_bs[i]: 307 | target_to_maturity = ( 308 | data.days_to_maturity[i] - data.days_to_target 309 | ) / data.days_in_year # To consider the expiration date as a trading day 310 | 311 | data.profit[i], data.cost[i] = get_pl_profile_bs( 312 | type, 313 | action, 314 | data.strike[i], 315 | opt_value, 316 | inputs.interest_rate, 317 | target_to_maturity, 318 | inputs.volatility, 319 | data.n[i], 320 | data.stock_price_array, 321 | inputs.dividend_yield, 322 | inputs.opt_commission, 323 | ) 324 | 325 | if inputs.model == "array": 326 | data.profit_mc[i] = get_pl_profile_bs( 327 | type, 328 | action, 329 | data.strike[i], 330 | opt_value, 331 | inputs.interest_rate, 332 | target_to_maturity, 333 | inputs.interest_rate, 334 | data.n[i], 335 | data.terminal_stock_prices, 336 | inputs.dividend_yield, 337 | inputs.opt_commission, 338 | )[0] 339 | else: 340 | data.profit[i], data.cost[i] = get_pl_profile( 341 | type, 342 | action, 343 | data.strike[i], 344 | opt_value, 345 | data.n[i], 346 | data.stock_price_array, 347 | inputs.opt_commission, 348 | ) 349 | 350 | if inputs.model == "array": 351 | data.profit_mc[i] = get_pl_profile( 352 | type, 353 | action, 354 | data.strike[i], 355 | opt_value, 356 | data.n[i], 357 | data.terminal_stock_prices, 358 | inputs.opt_commission, 359 | )[0] 360 | 361 | return data 362 | 363 | 364 | def _run_stock_calcs(data: EngineData, i: int) -> EngineData: 365 | inputs = data.inputs 366 | action: Action = data.action[i] # type: ignore 367 | 368 | if action == "buy": 369 | data.delta.append(1.0) 370 | else: 371 | data.delta.append(-1.0) 372 | 373 | data.itm_probability.append(1.0) 374 | data.implied_volatility.append(0.0) 375 | data.gamma.append(0.0) 376 | data.vega.append(0.0) 377 | data.rho.append(0.0) 378 | data.theta.append(0.0) 379 | 380 | if data.previous_position[i] < 0.0: # Previous position is closed 381 | costtmp = (inputs.stock_price + data.previous_position[i]) * data.n[i] 382 | 383 | if data.action[i] == "buy": 384 | costtmp *= -1.0 385 | 386 | data.cost[i] = costtmp 387 | data.profit[i] += costtmp 388 | 389 | if inputs.model == "array": 390 | data.profit_mc[i] += costtmp 391 | 392 | return data 393 | 394 | if data.previous_position[i] > 0.0: # Stock price at previous position 395 | stockpos = data.previous_position[i] 396 | else: # Spot price of the stock at start date 397 | stockpos = inputs.stock_price 398 | 399 | data.profit[i], data.cost[i] = get_pl_profile_stock( 400 | stockpos, 401 | action, 402 | data.n[i], 403 | data.stock_price_array, 404 | inputs.stock_commission, 405 | ) 406 | 407 | if inputs.model == "array": 408 | data.profit_mc[i] = get_pl_profile_stock( 409 | stockpos, 410 | action, 411 | data.n[i], 412 | data.terminal_stock_prices, 413 | inputs.stock_commission, 414 | )[0] 415 | 416 | return data 417 | 418 | 419 | def _run_closed_position_calcs(data: EngineData, i: int) -> EngineData: 420 | inputs = data.inputs 421 | 422 | data.implied_volatility.append(0.0) 423 | data.itm_probability.append(0.0) 424 | data.delta.append(0.0) 425 | data.gamma.append(0.0) 426 | data.vega.append(0.0) 427 | data.rho.append(0.0) 428 | data.theta.append(0.0) 429 | 430 | data.cost[i] = data.previous_position[i] 431 | data.profit[i] += data.previous_position[i] 432 | 433 | if inputs.model == "array": 434 | data.profit_mc[i] += data.previous_position[i] 435 | 436 | return data 437 | 438 | 439 | def _generate_outputs(data: EngineData) -> Outputs: 440 | return Outputs( 441 | inputs=data.inputs, 442 | data=data, 443 | probability_of_profit=data.profit_probability, 444 | expected_profit=data.expected_profit, 445 | expected_loss=data.expected_loss, 446 | strategy_cost=sum(data.cost), 447 | per_leg_cost=data.cost, 448 | profit_ranges=data.profit_ranges, 449 | minimum_return_in_the_domain=data.strategy_profit.min(), 450 | maximum_return_in_the_domain=data.strategy_profit.max(), 451 | implied_volatility=data.implied_volatility, 452 | in_the_money_probability=data.itm_probability, 453 | delta=data.delta, 454 | gamma=data.gamma, 455 | theta=data.theta, 456 | vega=data.vega, 457 | rho=data.rho, 458 | probability_of_profit_target=data.profit_target_probability, 459 | probability_of_loss_limit=data.loss_limit_probability, 460 | profit_target_ranges=data.profit_target_ranges, 461 | loss_limit_ranges=data.loss_limit_ranges, 462 | ) 463 | -------------------------------------------------------------------------------- /optionlab/models.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module primarily implements Pydantic models that represent inputs and outputs 3 | of strategy calculations. It also implements constants and custom types. 4 | 5 | From the user's point of view, the two most important classes that they will use 6 | to provide input and subsequently process calculation results are `Inputs` and 7 | `Outputs`, respectively. 8 | """ 9 | 10 | import datetime as dt 11 | from typing import Literal, Optional 12 | 13 | import numpy as np 14 | from pydantic import BaseModel, Field, field_validator, model_validator, ConfigDict 15 | 16 | OptionType = Literal["call", "put"] 17 | """Option type in a strategy leg.""" 18 | 19 | Action = Literal["buy", "sell"] 20 | """Action taken in in a strategy leg.""" 21 | 22 | StrategyLegType = Literal["stock"] | OptionType | Literal["closed"] 23 | """Type of strategy leg.""" 24 | 25 | TheoreticalModel = Literal["black-scholes", "array"] 26 | """ 27 | Theoretical model used in probability of profit (PoP) calculations. 28 | """ 29 | 30 | Range = tuple[float, float] 31 | """Range boundaries.""" 32 | 33 | FloatOrNdarray = float | np.ndarray 34 | """Float or numpy array custom type.""" 35 | 36 | 37 | def init_empty_array() -> np.ndarray: 38 | """@private""" 39 | 40 | return np.array([]) 41 | 42 | 43 | class Stock(BaseModel): 44 | """Defines the attributes of a stock leg in a strategy.""" 45 | 46 | type: Literal["stock"] = "stock" 47 | """It must be *'stock'*.""" 48 | 49 | n: int = Field(gt=0) 50 | """Number of shares.""" 51 | 52 | action: Action 53 | """Either *'buy'* or *'sell'*.""" 54 | 55 | prev_pos: Optional[float] = None 56 | """ 57 | Stock price effectively paid or received in a previously opened position. 58 | 59 | - If positive, the position remains open and the payoff calculation considers 60 | this price instead of the current stock price. 61 | 62 | - If negative, the position is closed and the difference between this price 63 | and the current price is included in the payoff calculation. 64 | 65 | The default is `None`, which means this stock position is not a previously 66 | opened position. 67 | """ 68 | 69 | 70 | class Option(BaseModel): 71 | """Defines the attributes of an option leg in a strategy.""" 72 | 73 | type: OptionType 74 | """Either *'call'* or *'put'*.""" 75 | 76 | strike: float = Field(gt=0) 77 | """Strike price.""" 78 | 79 | premium: float = Field(gt=0) 80 | """Option premium.""" 81 | 82 | action: Action 83 | """Either *'buy'* or *'sell'*.""" 84 | 85 | n: int = Field(gt=0) 86 | """Number of options.""" 87 | 88 | prev_pos: Optional[float] = None 89 | """ 90 | Premium effectively paid or received in a previously opened position. 91 | 92 | - If positive, the position remains open and the payoff calculation considers 93 | this price instead of the current price of the option. 94 | 95 | - If negative, the position is closed and the difference between this price 96 | and the current price is included in the payoff calculation. 97 | 98 | The default is `None`, which means this option position is not a previously 99 | opened position. 100 | """ 101 | 102 | expiration: dt.date | int | None = None 103 | """ 104 | Expiration date or number of days remaining to expiration. 105 | 106 | The default is `None`, which means the expiration is the same as `Inputs.target_date` 107 | or `Inputs.days_to_target_date`. 108 | """ 109 | 110 | @field_validator("expiration") 111 | def validate_expiration(cls, v: dt.date | int | None) -> dt.date | int | None: 112 | """@private""" 113 | 114 | if isinstance(v, int) and v <= 0: 115 | raise ValueError("If expiration is an integer, it must be greater than 0.") 116 | return v 117 | 118 | 119 | class ClosedPosition(BaseModel): 120 | """Defines the attributes of a previously closed position in a strategy.""" 121 | 122 | type: Literal["closed"] = "closed" 123 | """It must be *'closed'*.""" 124 | 125 | prev_pos: float 126 | """ 127 | The total amount of the closed position. 128 | 129 | - If positive, it resulted in a profit. 130 | 131 | - If negative, it incurred a loss. 132 | 133 | This amount will be added to the payoff and taken into account in the strategy 134 | calculations. 135 | """ 136 | 137 | 138 | StrategyLeg = Stock | Option | ClosedPosition 139 | """Leg in a strategy.""" 140 | 141 | 142 | class TheoreticalModelInputs(BaseModel): 143 | """Inputs for calculations, such as the probability of profit (PoP).""" 144 | 145 | stock_price: float = Field(gt=0.0) 146 | """Stock price.""" 147 | 148 | volatility: float = Field(gt=0.0) 149 | """Annualized volatility of the underlying asset.""" 150 | 151 | years_to_target_date: float = Field(ge=0.0) 152 | """Time remaining until target date, in years.""" 153 | 154 | 155 | class BlackScholesModelInputs(TheoreticalModelInputs): 156 | """Defines the input data for the calculations using the Black-Scholes model.""" 157 | 158 | model: Literal["black-scholes"] = "black-scholes" 159 | """It must be *'black-scholes'*.""" 160 | 161 | interest_rate: float = Field(0.0, ge=0.0) 162 | """ 163 | Annualized risk-free interest rate. 164 | 165 | The default is 0.0. 166 | """ 167 | 168 | dividend_yield: float = Field(0.0, ge=0.0, le=1.0) 169 | """ 170 | Annualized dividend yield. 171 | 172 | The default is 0.0. 173 | """ 174 | 175 | __hash__ = object.__hash__ 176 | 177 | 178 | class LaplaceInputs(TheoreticalModelInputs): 179 | """ 180 | Defines the input data for the calculations using a log-Laplace distribution of 181 | stock prices. 182 | """ 183 | 184 | model: Literal["laplace"] = "laplace" 185 | """It must be '*laplace*'.""" 186 | 187 | mu: float 188 | """Annualized return of the underlying asset.""" 189 | 190 | __hash__ = object.__hash__ 191 | 192 | 193 | class ArrayInputs(BaseModel): 194 | """ 195 | Defines the input data for the calculations when using an array of strategy 196 | returns. 197 | """ 198 | 199 | model: Literal["array"] = "array" 200 | """It must be *'array*'.""" 201 | 202 | array: np.ndarray 203 | """Array of strategy returns.""" 204 | 205 | model_config = ConfigDict(arbitrary_types_allowed=True) 206 | 207 | @field_validator("array", mode="before") 208 | @classmethod 209 | def validate_arrays(cls, v: np.ndarray | list[float]) -> np.ndarray: 210 | """@private""" 211 | 212 | arr = np.asarray(v) 213 | if arr.shape[0] == 0: 214 | raise ValueError("The array is empty!") 215 | return arr 216 | 217 | 218 | class Inputs(BaseModel): 219 | """Defines the input data for a strategy calculation.""" 220 | 221 | stock_price: float = Field(gt=0.0) 222 | """Spot price of the underlying.""" 223 | 224 | volatility: float = Field(ge=0.0) 225 | """Annualized volatility.""" 226 | 227 | interest_rate: float = Field(ge=0.0) 228 | """Annualized risk-free interest rate.""" 229 | 230 | min_stock: float = Field(ge=0.0) 231 | """Minimum value of the stock in the stock price domain.""" 232 | 233 | max_stock: float = Field(ge=0.0) 234 | """Maximum value of the stock in the stock price domain.""" 235 | 236 | strategy: list[StrategyLeg] = Field(..., min_length=1) 237 | """A list of strategy legs.""" 238 | 239 | dividend_yield: float = Field(0.0, ge=0.0) 240 | """ 241 | Annualized dividend yield. 242 | 243 | The default is 0.0. 244 | """ 245 | 246 | profit_target: Optional[float] = None 247 | """ 248 | Target profit level. 249 | 250 | The default is `None`, which means it is not calculated. 251 | """ 252 | 253 | loss_limit: Optional[float] = None 254 | """ 255 | Limit loss level. 256 | 257 | The default is `None`, which means it is not calculated. 258 | """ 259 | 260 | opt_commission: float = 0.0 261 | """ 262 | Brokerage commission for options transactions. 263 | 264 | The default is 0.0. 265 | """ 266 | 267 | stock_commission: float = 0.0 268 | """ 269 | Brokerage commission for stocks transactions. 270 | 271 | The default is 0.0. 272 | """ 273 | 274 | discard_nonbusiness_days: bool = True 275 | """ 276 | Discards weekends and holidays when counting the number of days between 277 | two dates. 278 | 279 | The default is `True`. 280 | """ 281 | 282 | business_days_in_year: int = 252 283 | """ 284 | Number of business days in a year. 285 | 286 | The default is 252. 287 | """ 288 | 289 | country: str = "US" 290 | """ 291 | Country whose holidays will be counted if `discard_nonbusinessdays` is 292 | set to `True`. 293 | 294 | The default is '*US*'. 295 | """ 296 | 297 | start_date: dt.date | None = None 298 | """ 299 | Start date in the calculations. 300 | 301 | If not provided, `days_to_target_date` must be provided. 302 | """ 303 | 304 | target_date: dt.date | None = None 305 | """ 306 | Target date in the calculations. 307 | 308 | If not provided, `days_to_target_date` must be provided. 309 | """ 310 | 311 | days_to_target_date: int = Field(0, ge=0) 312 | """ 313 | Days remaining to the target date. 314 | 315 | If not provided, `start_date` and `target_date` must be provided. 316 | """ 317 | 318 | model: TheoreticalModel = "black-scholes" 319 | """ 320 | Theoretical model used in the calculations of probability of profit. 321 | 322 | It can be *'black-scholes'* or *'array*'. 323 | """ 324 | 325 | array: np.ndarray = Field(default_factory=init_empty_array) 326 | """ 327 | Array of terminal stock prices. 328 | 329 | The default is an empty array. 330 | """ 331 | 332 | model_config = ConfigDict(arbitrary_types_allowed=True) 333 | 334 | @field_validator("strategy") 335 | @classmethod 336 | def validate_strategy(cls, v: list[StrategyLeg]) -> list[StrategyLeg]: 337 | """@private""" 338 | 339 | types = [strategy.type for strategy in v] 340 | if types.count("closed") > 1: 341 | raise ValueError("Only one position of type 'closed' is allowed!") 342 | return v 343 | 344 | @model_validator(mode="after") 345 | def validate_dates(self) -> "Inputs": 346 | """@private""" 347 | 348 | expiration_dates = [ 349 | strategy.expiration 350 | for strategy in self.strategy 351 | if isinstance(strategy, Option) and isinstance(strategy.expiration, dt.date) 352 | ] 353 | if self.start_date and self.target_date: 354 | if any( 355 | expiration_date < self.target_date 356 | for expiration_date in expiration_dates 357 | ): 358 | raise ValueError("Expiration dates must be after or on target date!") 359 | if self.start_date >= self.target_date: 360 | raise ValueError("Start date must be before target date!") 361 | return self 362 | if self.days_to_target_date: 363 | if len(expiration_dates) > 0: 364 | raise ValueError( 365 | "You can't mix a strategy expiration with a days_to_target_date." 366 | ) 367 | return self 368 | raise ValueError( 369 | "Either start_date and target_date or days_to_maturity must be provided" 370 | ) 371 | 372 | @model_validator(mode="after") 373 | def validate_model_array(self) -> "Inputs": 374 | """@private""" 375 | 376 | if self.model != "array": 377 | return self 378 | elif self.array is None: 379 | raise ValueError( 380 | "Array of terminal stock prices must be provided if model is 'array'." 381 | ) 382 | elif self.array.shape[0] == 0: 383 | raise ValueError( 384 | "Array of terminal stock prices must be provided if model is 'array'." 385 | ) 386 | return self 387 | 388 | 389 | class BlackScholesInfo(BaseModel): 390 | """Defines the data returned by a calculation using the Black-Scholes model.""" 391 | 392 | call_price: FloatOrNdarray 393 | """Price of a call option.""" 394 | 395 | put_price: FloatOrNdarray 396 | """Price of a put option.""" 397 | 398 | call_delta: FloatOrNdarray 399 | """Delta of a call option.""" 400 | 401 | put_delta: FloatOrNdarray 402 | """Delta of a put option.""" 403 | 404 | call_theta: FloatOrNdarray 405 | """Theta of a call option.""" 406 | 407 | put_theta: FloatOrNdarray 408 | """Theta of a put option.""" 409 | 410 | gamma: FloatOrNdarray 411 | """Gamma of an option.""" 412 | 413 | vega: FloatOrNdarray 414 | """Vega of an option.""" 415 | 416 | call_rho: FloatOrNdarray 417 | """Rho of a call option.""" 418 | 419 | put_rho: FloatOrNdarray 420 | """Rho of a put option.""" 421 | 422 | call_itm_prob: FloatOrNdarray 423 | """Probability of expiring in-the-money probability of a call option.""" 424 | 425 | put_itm_prob: FloatOrNdarray 426 | """Probability of expiring in-the-money of a put option.""" 427 | 428 | model_config = ConfigDict(arbitrary_types_allowed=True) 429 | 430 | 431 | class EngineDataResults(BaseModel): 432 | """@private""" 433 | 434 | stock_price_array: np.ndarray 435 | terminal_stock_prices: np.ndarray = Field(default_factory=init_empty_array) 436 | profit: np.ndarray = Field(default_factory=init_empty_array) 437 | profit_mc: np.ndarray = Field(default_factory=init_empty_array) 438 | strategy_profit: np.ndarray = Field(default_factory=init_empty_array) 439 | strategy_profit_mc: np.ndarray = Field(default_factory=init_empty_array) 440 | strike: list[float] = [] 441 | premium: list[float] = [] 442 | n: list[int] = [] 443 | action: list[Action | Literal["n/a"]] = [] 444 | type: list[StrategyLegType] = [] 445 | 446 | model_config = ConfigDict(arbitrary_types_allowed=True) 447 | 448 | 449 | class EngineData(EngineDataResults): 450 | """@private""" 451 | 452 | inputs: Inputs 453 | previous_position: list[float] = [] 454 | use_bs: list[bool] = [] 455 | profit_ranges: list[Range] = [] 456 | profit_target_ranges: list[Range] = [] 457 | loss_limit_ranges: list[Range] = [] 458 | days_to_maturity: list[int] = [] 459 | days_in_year: int = 365 460 | days_to_target: int = 30 461 | implied_volatility: list[float] = [] 462 | itm_probability: list[float] = [] 463 | delta: list[float] = [] 464 | gamma: list[float] = [] 465 | vega: list[float] = [] 466 | rho: list[float] = [] 467 | theta: list[float] = [] 468 | cost: list[float] = [] 469 | profit_probability: float = 0.0 470 | profit_target_probability: float = 0.0 471 | loss_limit_probability: float = 0.0 472 | expected_profit: Optional[float] = None 473 | expected_loss: Optional[float] = None 474 | 475 | 476 | class Outputs(BaseModel): 477 | """ 478 | Defines the output data from a strategy calculation. 479 | """ 480 | 481 | probability_of_profit: float 482 | """ 483 | Probability of the strategy yielding at least $0.01. 484 | """ 485 | 486 | profit_ranges: list[Range] 487 | """ 488 | A list of minimum and maximum stock prices defining ranges in which the 489 | strategy makes at least $0.01. 490 | """ 491 | 492 | expected_profit: Optional[float] = None 493 | """ 494 | Expected profit when the strategy is profitable. 495 | 496 | The default is `None`. 497 | """ 498 | 499 | expected_loss: Optional[float] = None 500 | """ 501 | Expected loss when the strategy is not profitable. 502 | 503 | The default is `None`. 504 | """ 505 | 506 | per_leg_cost: list[float] 507 | """ 508 | List of leg costs. 509 | """ 510 | 511 | strategy_cost: float 512 | """ 513 | Total strategy cost. 514 | """ 515 | 516 | minimum_return_in_the_domain: float 517 | """ 518 | Minimum return of the strategy within the stock price domain. 519 | """ 520 | 521 | maximum_return_in_the_domain: float 522 | """ 523 | Maximum return of the strategy within the stock price domain. 524 | """ 525 | 526 | implied_volatility: list[float] 527 | """ 528 | List of implied volatilities, one per strategy leg. 529 | """ 530 | 531 | in_the_money_probability: list[float] 532 | """ 533 | List of probabilities of legs expiring in-the-money (ITM). 534 | """ 535 | 536 | delta: list[float] 537 | """ 538 | List of Delta values, one per strategy leg. 539 | """ 540 | 541 | gamma: list[float] 542 | """ 543 | List of Gamma values, one per strategy leg. 544 | """ 545 | 546 | theta: list[float] 547 | """ 548 | List of Theta values, one per strategy leg. 549 | """ 550 | 551 | vega: list[float] 552 | """ 553 | List of Vega values, one per strategy leg. 554 | """ 555 | 556 | rho: list[float] 557 | """ 558 | List of Rho values, one per strategy leg. 559 | """ 560 | 561 | probability_of_profit_target: float = 0.0 562 | """ 563 | Probability of the strategy yielding at least the profit target. 564 | 565 | The default is 0.0. 566 | """ 567 | 568 | profit_target_ranges: list[Range] = [] 569 | """ 570 | List of minimum and maximum stock prices defining ranges in which the 571 | strategy makes at least the profit target. 572 | 573 | The default is []. 574 | """ 575 | 576 | probability_of_loss_limit: float = 0.0 577 | """ 578 | Probability of the strategy losing at least the loss limit. 579 | 580 | The default is 0.0. 581 | """ 582 | 583 | loss_limit_ranges: list[Range] = [] 584 | """ 585 | List of minimum and maximum stock prices defining ranges where the 586 | strategy loses at least the loss limit. 587 | 588 | The default is []. 589 | """ 590 | 591 | inputs: Inputs 592 | """@private""" 593 | 594 | data: EngineDataResults 595 | """@private""" 596 | 597 | def __str__(self): 598 | s = "" 599 | 600 | for key, value in self.model_dump( 601 | exclude={"data", "inputs"}, 602 | exclude_none=True, 603 | exclude_defaults=True, 604 | ).items(): 605 | s += f"{key.capitalize().replace('_',' ')}: {value}\n" 606 | 607 | return s 608 | 609 | 610 | class PoPOutputs(BaseModel): 611 | """ 612 | Defines the output data from a probability of profit (PoP) calculation. 613 | """ 614 | 615 | probability_of_reaching_target: float = 0.0 616 | """ 617 | Probability that the strategy return will be equal or greater than the 618 | target. 619 | 620 | The default is 0.0. 621 | """ 622 | 623 | probability_of_missing_target: float = 0.0 624 | """ 625 | Probability that the strategy return will be less than the target. 626 | 627 | The default is 0.0. 628 | """ 629 | 630 | reaching_target_range: list[Range] = [] 631 | """ 632 | Range of stock prices where the strategy return is equal or greater than 633 | the target. 634 | 635 | The default is []. 636 | """ 637 | 638 | missing_target_range: list[Range] = [] 639 | """ 640 | Range of stock prices where the strategy return is less than the target. 641 | 642 | The default is []. 643 | """ 644 | 645 | expected_return_above_target: Optional[float] = None 646 | """ 647 | Expected value of the strategy return when the return is equal or greater 648 | than the target. 649 | 650 | The default is `None`. 651 | """ 652 | 653 | expected_return_below_target: Optional[float] = None 654 | """ 655 | Expected value of the strategy return when the return is less than the 656 | target. 657 | 658 | The default is `None`. 659 | """ 660 | -------------------------------------------------------------------------------- /optionlab/plot.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module implements the `plot_pl` function, which displays the profit/loss diagram 3 | of an options trading strategy. 4 | """ 5 | 6 | from __future__ import division 7 | from __future__ import print_function 8 | 9 | import matplotlib.pyplot as plt 10 | from matplotlib import rcParams 11 | from numpy import zeros, full 12 | 13 | from optionlab.models import Outputs 14 | 15 | 16 | def plot_pl(outputs: Outputs) -> None: 17 | """ 18 | Displays the strategy's profit/loss diagram. 19 | 20 | Parameters 21 | ---------- 22 | `outputs`: output data from a strategy calculation with `optionlab.engine.run_strategy`. 23 | 24 | Returns 25 | ------- 26 | `None`. 27 | """ 28 | 29 | st = outputs.data 30 | inputs = outputs.inputs 31 | 32 | if len(st.strategy_profit) == 0: 33 | raise RuntimeError( 34 | "Before plotting the profit/loss profile diagram, you must run a calculation!" 35 | ) 36 | 37 | rcParams.update({"figure.autolayout": True}) 38 | 39 | zero_line = zeros(st.stock_price_array.shape[0]) 40 | strike_call_buy = [] 41 | strike_put_buy = [] 42 | zero_call_buy = [] 43 | zero_put_buy = [] 44 | strike_call_sell = [] 45 | strike_put_sell = [] 46 | zero_call_sell = [] 47 | zero_put_sell = [] 48 | comment = "Profit/Loss diagram:\n--------------------\n" 49 | comment += "The vertical green dashed line corresponds to the position " 50 | comment += "of the stock's spot price. The right and left arrow " 51 | comment += "markers indicate the strike prices of calls and puts, " 52 | comment += "respectively, with blue representing long and red representing " 53 | comment += "short positions." 54 | 55 | plt.axvline(inputs.stock_price, ls="--", color="green") 56 | plt.xlabel("Stock price") 57 | plt.ylabel("Profit/Loss") 58 | plt.xlim(st.stock_price_array.min(), st.stock_price_array.max()) 59 | 60 | for i, strike in enumerate(st.strike): 61 | if strike == 0.0: 62 | continue 63 | 64 | if st.type[i] == "call": 65 | if st.action[i] == "buy": 66 | strike_call_buy.append(strike) 67 | zero_call_buy.append(0.0) 68 | elif st.action[i] == "sell": 69 | strike_call_sell.append(strike) 70 | zero_call_sell.append(0.0) 71 | elif st.type[i] == "put": 72 | if st.action[i] == "buy": 73 | strike_put_buy.append(strike) 74 | zero_put_buy.append(0.0) 75 | elif st.action[i] == "sell": 76 | strike_put_sell.append(strike) 77 | zero_put_sell.append(0.0) 78 | 79 | target_line = None 80 | if inputs.profit_target is not None: 81 | comment += " The blue dashed line represents the profit target level." 82 | target_line = full(st.stock_price_array.shape[0], inputs.profit_target) 83 | 84 | loss_line = None 85 | if inputs.loss_limit is not None: 86 | comment += " The red dashed line represents the loss limit level." 87 | loss_line = full(st.stock_price_array.shape[0], inputs.loss_limit) 88 | 89 | print(comment) 90 | 91 | if loss_line is not None and target_line is not None: 92 | plt.plot( 93 | st.stock_price_array, 94 | zero_line, 95 | "m--", 96 | st.stock_price_array, 97 | loss_line, 98 | "r--", 99 | st.stock_price_array, 100 | target_line, 101 | "b--", 102 | st.stock_price_array, 103 | st.strategy_profit, 104 | "k-", 105 | strike_call_buy, 106 | zero_call_buy, 107 | "b>", 108 | strike_put_buy, 109 | zero_put_buy, 110 | "b<", 111 | strike_call_sell, 112 | zero_call_sell, 113 | "r>", 114 | strike_put_sell, 115 | zero_put_sell, 116 | "r<", 117 | markersize=10, 118 | ) 119 | elif loss_line is not None: 120 | plt.plot( 121 | st.stock_price_array, 122 | zero_line, 123 | "m--", 124 | st.stock_price_array, 125 | loss_line, 126 | "r--", 127 | st.stock_price_array, 128 | st.strategy_profit, 129 | "k-", 130 | strike_call_buy, 131 | zero_call_buy, 132 | "b>", 133 | strike_put_buy, 134 | zero_put_buy, 135 | "b<", 136 | strike_call_sell, 137 | zero_call_sell, 138 | "r>", 139 | strike_put_sell, 140 | zero_put_sell, 141 | "r<", 142 | markersize=10, 143 | ) 144 | elif target_line is not None: 145 | plt.plot( 146 | st.stock_price_array, 147 | zero_line, 148 | "m--", 149 | st.stock_price_array, 150 | target_line, 151 | "b--", 152 | st.stock_price_array, 153 | st.strategy_profit, 154 | "k-", 155 | strike_call_buy, 156 | zero_call_buy, 157 | "b>", 158 | strike_put_buy, 159 | zero_put_buy, 160 | "b<", 161 | strike_call_sell, 162 | zero_call_sell, 163 | "r>", 164 | strike_put_sell, 165 | zero_put_sell, 166 | "r<", 167 | markersize=10, 168 | ) 169 | else: 170 | plt.plot( 171 | st.stock_price_array, 172 | zero_line, 173 | "m--", 174 | st.stock_price_array, 175 | st.strategy_profit, 176 | "k-", 177 | strike_call_buy, 178 | zero_call_buy, 179 | "b>", 180 | strike_put_buy, 181 | zero_put_buy, 182 | "b<", 183 | strike_call_sell, 184 | zero_call_sell, 185 | "r>", 186 | strike_put_sell, 187 | zero_put_sell, 188 | "r<", 189 | markersize=10, 190 | ) 191 | -------------------------------------------------------------------------------- /optionlab/price_array.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module defines the `create_price_array` function, which calculates terminal 3 | prices from numerical simulations of multiple stock paths. 4 | 5 | The terminal price array can later be used to calculate the probability of profit 6 | (PoP) of a strategy using the `optionlab.engine.run_strategy` function. 7 | """ 8 | 9 | from functools import lru_cache 10 | 11 | import numpy as np 12 | from numpy import exp 13 | from numpy.random import seed as np_seed_number, normal, laplace 14 | from numpy.lib.scimath import log, sqrt 15 | 16 | from optionlab.models import BlackScholesModelInputs, LaplaceInputs 17 | 18 | 19 | def create_price_array( 20 | inputs_data: BlackScholesModelInputs | LaplaceInputs | dict, 21 | n: int = 100_000, 22 | seed: int | None = None, 23 | ) -> np.ndarray: 24 | """ 25 | Generates terminal stock prices. 26 | 27 | Parameters 28 | ---------- 29 | `inputs_data`: input data used to generate the terminal stock prices. 30 | 31 | `n`: number of terminal stock prices. 32 | 33 | `seed`: seed for random number generation. 34 | 35 | Returns 36 | ------- 37 | Array of terminal prices. 38 | """ 39 | 40 | inputs: BlackScholesModelInputs | LaplaceInputs 41 | 42 | if isinstance(inputs_data, dict): 43 | input_type = inputs_data["model"] 44 | 45 | if input_type == "black-scholes": 46 | inputs = BlackScholesModelInputs.model_validate(inputs_data) 47 | elif input_type == "laplace": 48 | inputs = LaplaceInputs.model_validate(inputs_data) 49 | else: 50 | raise ValueError("Inputs are not valid!") 51 | else: 52 | inputs = inputs_data 53 | 54 | if isinstance(inputs, BlackScholesModelInputs): 55 | input_type = "black-scholes" 56 | elif isinstance(inputs, LaplaceInputs): 57 | input_type = "laplace" 58 | else: 59 | raise ValueError("Inputs are not valid!") 60 | 61 | np_seed_number(seed) 62 | 63 | if input_type == "black-scholes": 64 | arr = _get_array_price_from_BS(inputs, n) 65 | elif input_type == "laplace": 66 | arr = _get_array_price_from_laplace(inputs, n) 67 | 68 | np_seed_number(None) 69 | 70 | return arr 71 | 72 | 73 | @lru_cache 74 | def _get_array_price_from_BS(inputs: BlackScholesModelInputs, n: int) -> np.ndarray: 75 | return exp( 76 | normal( 77 | ( 78 | log(inputs.stock_price) 79 | + ( 80 | inputs.interest_rate 81 | - inputs.dividend_yield 82 | - 0.5 * inputs.volatility * inputs.volatility 83 | ) 84 | * inputs.years_to_target_date 85 | ), 86 | inputs.volatility * sqrt(inputs.years_to_target_date), 87 | n, 88 | ) 89 | ) 90 | 91 | 92 | @lru_cache 93 | def _get_array_price_from_laplace(inputs: LaplaceInputs, n: int) -> np.ndarray: 94 | return exp( 95 | laplace( 96 | (log(inputs.stock_price) + inputs.mu * inputs.years_to_target_date), 97 | (inputs.volatility * sqrt(inputs.years_to_target_date)) / sqrt(2.0), 98 | n, 99 | ) 100 | ) 101 | -------------------------------------------------------------------------------- /optionlab/support.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module implements a number of helper functions that are not intended to be 3 | called directly by users, but rather support functionalities within the 4 | `optionlab.engine.run_strategy` function. 5 | """ 6 | 7 | from __future__ import division 8 | 9 | from functools import lru_cache 10 | 11 | from typing import Optional 12 | 13 | import numpy as np 14 | from numpy import abs, round, arange 15 | from numpy.lib.scimath import log, sqrt 16 | from scipy import stats 17 | 18 | from optionlab.black_scholes import get_d1, get_d2, get_option_price 19 | from optionlab.models import ( 20 | OptionType, 21 | Action, 22 | BlackScholesModelInputs, 23 | ArrayInputs, 24 | Range, 25 | PoPOutputs, 26 | FloatOrNdarray, 27 | ) 28 | 29 | 30 | def get_pl_profile( 31 | option_type: OptionType, 32 | action: Action, 33 | x: float, 34 | val: float, 35 | n: int, 36 | s: np.ndarray, 37 | commission: float = 0.0, 38 | ) -> tuple[np.ndarray, float]: 39 | """ 40 | Returns the profit/loss profile and cost of an options trade at expiration. 41 | 42 | Parameters 43 | ---------- 44 | `option_type`: either *'call'* or *'put'*. 45 | 46 | `action`: either *'buy'* or *'sell'*. 47 | 48 | `x`: strike price. 49 | 50 | `val`: option price. 51 | 52 | `n`: number of options. 53 | 54 | `s`: array of stock prices. 55 | 56 | `commission`: brokerage commission. 57 | 58 | Returns 59 | ------- 60 | Profit/loss profile and cost of an option trade at expiration. 61 | """ 62 | 63 | if action == "buy": 64 | cost = -val 65 | elif action == "sell": 66 | cost = val 67 | else: 68 | raise ValueError("Action must be either 'buy' or 'sell'!") 69 | 70 | if option_type in ("call", "put"): 71 | return ( 72 | n * _get_pl_option(option_type, val, action, s, x) - commission, 73 | n * cost - commission, 74 | ) 75 | else: 76 | raise ValueError("Option type must be either 'call' or 'put'!") 77 | 78 | 79 | def get_pl_profile_stock( 80 | s0: float, action: Action, n: int, s: np.ndarray, commission: float = 0.0 81 | ) -> tuple[np.ndarray, float]: 82 | """ 83 | Returns the profit/loss profile and cost of a stock position. 84 | 85 | Parameters 86 | ---------- 87 | `s0`: initial stock price. 88 | 89 | `action`: either *'buy'* or *'sell'*. 90 | 91 | `n`: number of shares. 92 | 93 | `s`: array of stock prices. 94 | 95 | `commission`: brokerage commission. 96 | 97 | Returns 98 | ------- 99 | Profit/loss profile and cost of a stock position. 100 | """ 101 | 102 | if action == "buy": 103 | cost = -s0 104 | elif action == "sell": 105 | cost = s0 106 | else: 107 | raise ValueError("Action must be either 'buy' or 'sell'!") 108 | 109 | return n * _get_pl_stock(s0, action, s) - commission, n * cost - commission 110 | 111 | 112 | def get_pl_profile_bs( 113 | option_type: OptionType, 114 | action: Action, 115 | x: float, 116 | val: float, 117 | r: float, 118 | target_to_maturity_years: float, 119 | volatility: float, 120 | n: int, 121 | s: np.ndarray, 122 | y: float = 0.0, 123 | commission: float = 0.0, 124 | ) -> tuple[FloatOrNdarray, float]: 125 | """ 126 | Returns the profit/loss profile and cost of an options trade on a target date 127 | before expiration using the Black-Scholes model for option pricing. 128 | 129 | Parameters 130 | ---------- 131 | `option_type`: either *'call'* or *'put'*. 132 | 133 | `action`: either *'buy'* or *'sell'*. 134 | 135 | `x`: strike price. 136 | 137 | `val`: initial option price. 138 | 139 | `r`: annualized risk-free interest rate. 140 | 141 | `target_to_maturity_years`: time remaining to maturity from the target date, 142 | in years. 143 | 144 | `volatility`: annualized volatility of the underlying asset. 145 | 146 | `n`: number of options. 147 | 148 | `s`: array of stock prices. 149 | 150 | `y`: annualized dividend yield. 151 | 152 | `commission`: brokerage commission. 153 | 154 | Returns 155 | ------- 156 | Profit/loss profile and cost of an option trade before expiration. 157 | """ 158 | 159 | if action == "buy": 160 | cost = -val 161 | fac = 1 162 | elif action == "sell": 163 | cost = val 164 | fac = -1 165 | else: 166 | raise ValueError("Action must be either 'buy' or 'sell'!") 167 | 168 | d1: FloatOrNdarray = get_d1(s, x, r, volatility, target_to_maturity_years, y) 169 | d2: FloatOrNdarray = get_d2(s, x, r, volatility, target_to_maturity_years, y) 170 | calcprice: FloatOrNdarray = get_option_price( 171 | option_type, s, x, r, target_to_maturity_years, d1, d2, y 172 | ) 173 | profile: FloatOrNdarray = fac * n * (calcprice - val) - commission 174 | 175 | return profile, n * cost - commission 176 | 177 | 178 | @lru_cache 179 | def create_price_seq(min_price: float, max_price: float) -> np.ndarray: 180 | """ 181 | Generates a sequence of stock prices from a minimum to a maximum price with 182 | increment $0.01. 183 | 184 | Parameters 185 | ---------- 186 | `min_price`: minimum stock price in the range. 187 | 188 | `max_price`: maximum stock price in the range. 189 | 190 | Returns 191 | ------- 192 | Array of sequential stock prices. 193 | """ 194 | 195 | if max_price > min_price: 196 | return round((arange((max_price - min_price) * 100 + 1) * 0.01 + min_price), 2) 197 | else: 198 | raise ValueError("Maximum price cannot be less than minimum price!") 199 | 200 | 201 | def get_pop( 202 | s: np.ndarray, 203 | profit: np.ndarray, 204 | inputs_data: BlackScholesModelInputs | ArrayInputs, 205 | target: float = 0.01, 206 | ) -> PoPOutputs: 207 | """ 208 | Estimates the probability of profit (PoP) of an options trading strategy. 209 | 210 | Parameters 211 | ---------- 212 | `s`: array of stock prices. 213 | 214 | `profit`: array of profits and losses. 215 | 216 | `inputs_data`: input data used to estimate the probability of profit. 217 | 218 | `target`: target return. 219 | 220 | Returns 221 | ------- 222 | Outputs of a probability of profit (PoP) calculation. 223 | """ 224 | 225 | probability_of_reaching_target: float 226 | probability_of_missing_target: float 227 | 228 | expected_return_above_target: Optional[float] = None 229 | expected_return_below_target: Optional[float] = None 230 | 231 | t_ranges = _get_profit_range(s, profit, target) 232 | 233 | reaching_target_range = t_ranges[0] if t_ranges[0] != [(0.0, 0.0)] else [] 234 | missing_target_range = t_ranges[1] if t_ranges[1] != [(0.0, 0.0)] else [] 235 | 236 | if isinstance(inputs_data, BlackScholesModelInputs): 237 | ( 238 | probability_of_reaching_target, 239 | expected_return_above_target, 240 | probability_of_missing_target, 241 | expected_return_below_target, 242 | ) = _get_pop_bs(s, profit, inputs_data, t_ranges) 243 | elif isinstance(inputs_data, ArrayInputs): 244 | ( 245 | probability_of_reaching_target, 246 | expected_return_above_target, 247 | probability_of_missing_target, 248 | expected_return_below_target, 249 | ) = _get_pop_array(inputs_data, target) 250 | 251 | return PoPOutputs( 252 | probability_of_reaching_target=probability_of_reaching_target, 253 | probability_of_missing_target=probability_of_missing_target, 254 | reaching_target_range=reaching_target_range, 255 | missing_target_range=missing_target_range, 256 | expected_return_above_target=expected_return_above_target, 257 | expected_return_below_target=expected_return_below_target, 258 | ) 259 | 260 | 261 | def _get_pl_option( 262 | option_type: OptionType, opvalue: float, action: Action, s: np.ndarray, x: float 263 | ) -> np.ndarray: 264 | """ 265 | Returns the profit or loss profile of an option leg at expiration. 266 | 267 | Parameters 268 | ---------- 269 | `option_type`: either *'call'* or *'put'*. 270 | 271 | `opvalue`: option price. 272 | 273 | `action`: either *'buy'* or *'sell'*. 274 | 275 | `s`: array of stock prices. 276 | 277 | `x`: strike price. 278 | 279 | Returns 280 | ------- 281 | Profit or loss profile of an option leg at expiration. 282 | """ 283 | 284 | if action == "sell": 285 | return opvalue - _get_payoff(option_type, s, x) 286 | elif action == "buy": 287 | return _get_payoff(option_type, s, x) - opvalue 288 | else: 289 | raise ValueError("Action must be either 'sell' or 'buy'!") 290 | 291 | 292 | def _get_payoff(option_type: OptionType, s: np.ndarray, x: float) -> np.ndarray: 293 | """ 294 | Returns the payoff of an option leg at expiration. 295 | 296 | Parameters 297 | ---------- 298 | `option_type`: either *'call'* or *'put'*. 299 | 300 | `s`: array of stock prices. 301 | 302 | `x`: strike price. 303 | 304 | Returns 305 | ------- 306 | Payoff of an option leg at expiration. 307 | """ 308 | 309 | if option_type == "call": 310 | return (s - x + abs(s - x)) / 2.0 311 | elif option_type == "put": 312 | return (x - s + abs(x - s)) / 2.0 313 | else: 314 | raise ValueError("Option type must be either 'call' or 'put'!") 315 | 316 | 317 | def _get_pl_stock(s0: float, action: Action, s: np.ndarray) -> np.ndarray: 318 | """ 319 | Returns the profit or loss profile of a stock position. 320 | 321 | Parameters 322 | ---------- 323 | `s0`: spot price of the underlying asset. 324 | 325 | `action`: either *'buy'* or *'sell'*. 326 | 327 | `s`: array of stock prices. 328 | 329 | Returns 330 | ------- 331 | Profit or loss profile of a stock position. 332 | """ 333 | 334 | if action == "sell": 335 | return s0 - s 336 | elif action == "buy": 337 | return s - s0 338 | else: 339 | raise ValueError("Action must be either 'sell' or 'buy'!") 340 | 341 | 342 | def _get_pop_bs( 343 | s: np.ndarray, 344 | profit: np.ndarray, 345 | inputs: BlackScholesModelInputs, 346 | profit_range: tuple[list[Range], list[Range]], 347 | ) -> tuple[float, Optional[float], float, Optional[float]]: 348 | """ 349 | Estimates the probability of profit (PoP) of an options trading strategy using 350 | the Black-Scholes model. 351 | 352 | Parameters 353 | ---------- 354 | `s`: array of stock prices. 355 | 356 | `profit`: array of profits and losses. 357 | 358 | `inputs`: input data used to estimate the probability of profit. 359 | 360 | `profit_range`: lists of stock price pairs defining the profit and loss 361 | ranges. 362 | 363 | Returns 364 | ------- 365 | Probability of reaching the return target, expected value above the target, 366 | probability of missing the return target, and expected value below the 367 | target. 368 | """ 369 | 370 | expected_return_above_target = None 371 | expected_return_below_target = None 372 | 373 | sigma = ( 374 | inputs.volatility * sqrt(inputs.years_to_target_date) 375 | if inputs.volatility > 0.0 376 | else 1e-10 377 | ) 378 | 379 | for i, t in enumerate(profit_range): 380 | prob = 0.0 381 | 382 | if t != [(0.0, 0.0)]: 383 | for p_range in t: 384 | lval = log(p_range[0]) if p_range[0] > 0.0 else -float("inf") 385 | hval = log(p_range[1]) 386 | drift = ( 387 | inputs.interest_rate 388 | - inputs.dividend_yield 389 | - 0.5 * inputs.volatility * inputs.volatility 390 | ) * inputs.years_to_target_date 391 | m = log(inputs.stock_price) + drift 392 | prob += stats.norm.cdf((hval - m) / sigma) - stats.norm.cdf( 393 | (lval - m) / sigma 394 | ) 395 | 396 | if i == 0: 397 | probability_of_reaching_target = prob 398 | else: 399 | probability_of_missing_target = prob 400 | 401 | return ( 402 | probability_of_reaching_target, 403 | expected_return_above_target, 404 | probability_of_missing_target, 405 | expected_return_below_target, 406 | ) 407 | 408 | 409 | def _get_pop_array( 410 | inputs: ArrayInputs, target: float 411 | ) -> tuple[float, Optional[float], float, Optional[float]]: 412 | """ 413 | Estimates the probability of profit (PoP) of an options trading strategy using 414 | an array of terminal stock prices. 415 | 416 | Parameters 417 | ---------- 418 | `inputs`: input data used to estimate the probability of profit. 419 | 420 | `target`: target return. 421 | 422 | Returns 423 | ------- 424 | Probability of reaching the target return, expected value above the target, 425 | probability of missing the target return, and expected value below the 426 | target. 427 | """ 428 | 429 | if inputs.array.shape[0] == 0: 430 | raise ValueError("The array is empty!") 431 | 432 | tmp1 = inputs.array[inputs.array >= target] 433 | tmp2 = inputs.array[inputs.array < target] 434 | 435 | probability_of_reaching_target = tmp1.shape[0] / inputs.array.shape[0] 436 | probability_of_missing_target = 1.0 - probability_of_reaching_target 437 | 438 | expected_return_above_target = round(tmp1.mean(), 2) if tmp1.shape[0] > 0 else None 439 | expected_return_below_target = round(tmp2.mean(), 2) if tmp2.shape[0] > 0 else None 440 | 441 | return ( 442 | probability_of_reaching_target, 443 | expected_return_above_target, 444 | probability_of_missing_target, 445 | expected_return_below_target, 446 | ) 447 | 448 | 449 | def _get_profit_range( 450 | s: np.ndarray, profit: np.ndarray, target: float = 0.01 451 | ) -> tuple[list[Range], list[Range]]: 452 | """ 453 | Returns lists of stock price ranges: one representing the ranges where the 454 | options trade returns are equal to or greater than the target, and the other 455 | representing the ranges where they fall short. 456 | 457 | Parameters 458 | ---------- 459 | `s`: array of stock prices. 460 | 461 | `profit`: array of profits and losses. 462 | 463 | `target`: target profit. 464 | 465 | Returns 466 | ------- 467 | Lists of stock price pairs. 468 | """ 469 | 470 | profit_range = [] 471 | loss_range = [] 472 | 473 | crossings = _get_sign_changes(profit, target) 474 | n_crossings = len(crossings) 475 | 476 | if n_crossings == 0: 477 | if profit[0] >= target: 478 | return [(0.0, float("inf"))], [(0.0, 0.0)] 479 | else: 480 | return [(0.0, 0.0)], [(0.0, float("inf"))] 481 | 482 | lb_profit = hb_profit = None 483 | lb_loss = hb_loss = None 484 | 485 | for i, index in enumerate(crossings): 486 | if i == 0: 487 | if profit[index] < profit[index - 1]: 488 | lb_profit = 0.0 489 | hb_profit = s[index - 1] 490 | lb_loss = s[index] 491 | 492 | if n_crossings == 1: 493 | hb_loss = float("inf") 494 | else: 495 | lb_profit = s[index] 496 | lb_loss = 0.0 497 | hb_loss = s[index - 1] 498 | 499 | if n_crossings == 1: 500 | hb_profit = float("inf") 501 | elif i == n_crossings - 1: 502 | if profit[index] > profit[index - 1]: 503 | lb_profit = s[index] 504 | hb_profit = float("inf") 505 | hb_loss = s[index - 1] 506 | else: 507 | hb_profit = s[index - 1] 508 | lb_loss = s[index] 509 | hb_loss = float("inf") 510 | else: 511 | if profit[index] > profit[index - 1]: 512 | lb_profit = s[index] 513 | hb_loss = s[index - 1] 514 | else: 515 | hb_profit = s[index - 1] 516 | lb_loss = s[index] 517 | 518 | if lb_profit is not None and hb_profit is not None: 519 | profit_range.append((lb_profit, hb_profit)) 520 | 521 | lb_profit = hb_profit = None 522 | 523 | if lb_loss is not None and hb_loss is not None: 524 | loss_range.append((lb_loss, hb_loss)) 525 | 526 | lb_loss = hb_loss = None 527 | 528 | return profit_range, loss_range 529 | 530 | 531 | def _get_sign_changes(profit: np.ndarray, target: float) -> list[int]: 532 | """ 533 | Returns a list of the indices in the array of profits where the sign changes. 534 | 535 | Parameters 536 | ---------- 537 | `profit`: array of profits and losses. 538 | 539 | `target`: target profit. 540 | 541 | Returns 542 | ------- 543 | List of indices. 544 | """ 545 | 546 | p_temp = profit - target + 1e-10 547 | 548 | sign_changes = (np.sign(p_temp[:-1]) * np.sign(p_temp[1:])) < 0 549 | 550 | return list(np.where(sign_changes)[0] + 1) 551 | -------------------------------------------------------------------------------- /optionlab/utils.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module defines utility functions. 3 | """ 4 | 5 | from __future__ import division 6 | 7 | import datetime as dt 8 | from datetime import timedelta 9 | from functools import lru_cache 10 | 11 | import numpy as np 12 | from holidays import country_holidays 13 | 14 | from optionlab.models import Outputs 15 | 16 | 17 | @lru_cache 18 | def get_nonbusiness_days( 19 | start_date: dt.date, end_date: dt.date, country: str = "US" 20 | ) -> int: 21 | """ 22 | Returns the number of non-business days (i.e., weekends and holidays) between 23 | the start and end date. 24 | 25 | Parameters 26 | ---------- 27 | `start_date`: start date. 28 | 29 | `end_date`: end date. 30 | 31 | `country`: country of the stock exchange. 32 | 33 | Returns 34 | ------- 35 | Number of weekends and holidays between the start and end date. 36 | """ 37 | 38 | if end_date > start_date: 39 | n_days = (end_date - start_date).days 40 | else: 41 | raise ValueError("End date must be after start date!") 42 | 43 | nonbusiness_days: int = 0 44 | holidays = country_holidays(country) 45 | 46 | for i in range(n_days): 47 | current_date = start_date + timedelta(days=i) 48 | 49 | if current_date.weekday() >= 5 or current_date.strftime("%Y-%m-%d") in holidays: 50 | nonbusiness_days += 1 51 | 52 | return nonbusiness_days 53 | 54 | 55 | def get_pl(outputs: Outputs, leg: int | None = None) -> tuple[np.ndarray, np.ndarray]: 56 | """ 57 | Returns the stock prices and the corresponding profit/loss profile of either 58 | a leg or the whole strategy. 59 | 60 | Parameters 61 | ---------- 62 | `outputs`: output data from a strategy calculation. 63 | 64 | `leg`: index of a strategy leg. The default is `None`, which means the whole 65 | strategy. 66 | 67 | Returns 68 | ------- 69 | Array of stock prices and array or profits/losses. 70 | """ 71 | 72 | if outputs.data.profit.size > 0 and leg and leg < outputs.data.profit.shape[0]: 73 | return outputs.data.stock_price_array, outputs.data.profit[leg] 74 | 75 | return outputs.data.stock_price_array, outputs.data.strategy_profit 76 | 77 | 78 | def pl_to_csv( 79 | outputs: Outputs, filename: str = "pl.csv", leg: int | None = None 80 | ) -> None: 81 | """ 82 | Saves the stock prices and corresponding profit/loss profile of either a leg 83 | or the whole strategy to a CSV file. 84 | 85 | Parameters 86 | ---------- 87 | `outputs`: output data from a strategy calculation. 88 | 89 | `filename`: name of the CSV file. 90 | 91 | `leg`: index of a strategy leg. The default is `None`, which means the whole 92 | strategy. 93 | 94 | Returns 95 | ------- 96 | `None`. 97 | """ 98 | 99 | if outputs.data.profit.size > 0 and leg and leg < outputs.data.profit.shape[0]: 100 | arr = np.stack((outputs.data.stock_price_array, outputs.data.profit[leg])) 101 | else: 102 | arr = np.stack((outputs.data.stock_price_array, outputs.data.strategy_profit)) 103 | 104 | np.savetxt( 105 | filename, arr.transpose(), delimiter=",", header="StockPrice,Profit/Loss" 106 | ) 107 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "optionlab" 3 | version = "1.4.3" 4 | description = "Python library for evaluating options trading strategies" 5 | authors = ["Roberto Gomes, PhD "] 6 | readme = "README.md" 7 | 8 | [tool.poetry.dependencies] 9 | python = "^3.10" 10 | scipy = "^1.12.0" 11 | pandas = "^2.2.1" 12 | matplotlib = "^3.8.3" 13 | pydantic = "^2.9" 14 | holidays = "^0.44" 15 | jupyter = "^1.0.0" 16 | 17 | [tool.poetry.group.dev.dependencies] 18 | mypy = "^1.14.0" 19 | black = {extras = ["jupyter"], version = "^24.2.0"} 20 | pytest = "^8.0.2" 21 | pytest-benchmark = "^4.0.0" 22 | ruff = "^0.3.2" 23 | 24 | [build-system] 25 | requires = ["poetry-core"] 26 | build-backend = "poetry.core.masonry.api" 27 | -------------------------------------------------------------------------------- /tests/.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__ -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | from pathlib import Path 2 | 3 | TEST_DIR = Path(__file__).parent 4 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import datetime as dt 3 | 4 | 5 | @pytest.fixture 6 | def nvidia(): 7 | stockprice = 168.99 8 | return dict( 9 | stock_price=stockprice, 10 | volatility=0.483, 11 | start_date=dt.date(2023, 1, 16), 12 | target_date=dt.date(2023, 2, 17), 13 | interest_rate=0.045, 14 | min_stock=stockprice - 100.0, 15 | max_stock=stockprice + 100.0, 16 | ) 17 | -------------------------------------------------------------------------------- /tests/test_core.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from optionlab import Inputs, Outputs, BlackScholesModelInputs, LaplaceInputs 4 | from optionlab import run_strategy 5 | from optionlab import create_price_array 6 | from optionlab import get_bs_info 7 | 8 | 9 | COVERED_CALL_RESULT = { 10 | "probability_of_profit": 0.5472008423945267, 11 | "profit_ranges": [(164.9, float("inf"))], 12 | "per_leg_cost": [-16899.0, 409.99999999999994], 13 | "strategy_cost": -16489.0, 14 | "minimum_return_in_the_domain": -9590.000000000002, 15 | "maximum_return_in_the_domain": 2011.0, 16 | "implied_volatility": [0.0, 0.456], 17 | "in_the_money_probability": [1.0, 0.256866624586934], 18 | "delta": [1.0, -0.30713817729665704], 19 | "gamma": [0.0, 0.013948977387090415], 20 | "theta": [0.0, 0.19283555235589467], 21 | "vega": [0.0, 0.1832408146218486], 22 | "rho": [0.0, -0.04506390742751745], 23 | } 24 | 25 | PROB_100_ITM_RESULT = { 26 | "probability_of_profit": 1.0, 27 | "profit_ranges": [(0.0, float("inf"))], 28 | "per_leg_cost": [-750.0, 990.0], 29 | "strategy_cost": 240.0, 30 | "minimum_return_in_the_domain": 240.0, 31 | "maximum_return_in_the_domain": 740.0000000000018, 32 | "implied_volatility": [0.494, 0.482], 33 | "in_the_money_probability": [0.54558925139931, 0.465831136209786], 34 | "delta": [0.6039490632362865, -0.525237550169406], 35 | "gamma": [0.015297136732317718, 0.015806160944019643], 36 | "theta": [-0.21821351060901806, 0.22301627833773927], 37 | "vega": [0.20095091693287098, 0.20763771616023433], 38 | "rho": [0.08536880237502181, -0.07509774107468528], 39 | } 40 | 41 | PROB_NAKED_CALL = { 42 | "probability_of_profit": 0.8389215512144531, 43 | "profit_ranges": [(0.0, 176.14)], 44 | "per_leg_cost": [114.99999999999999], 45 | "strategy_cost": 114.99999999999999, 46 | "minimum_return_in_the_domain": -6991.999999999999, 47 | "maximum_return_in_the_domain": 114.99999999999999, 48 | "implied_volatility": [0.256], 49 | "in_the_money_probability": [0.1832371984432129], 50 | "delta": [-0.20371918274704337], 51 | "gamma": [0.023104402361599465], 52 | "theta": [0.091289876347897], 53 | "vega": [0.12750177318341913], 54 | "rho": [-0.02417676577711979], 55 | "probability_of_profit_target": 0.8197909190785164, 56 | "profit_target_ranges": [(0.0, 175.15)], 57 | "probability_of_loss_limit": 0.14307836806156238, 58 | "loss_limit_ranges": [(177.15, float("inf"))], 59 | } 60 | 61 | 62 | def test_black_scholes(): 63 | stock_price = 100.0 64 | strike = 105.0 65 | interest_rate = 1.0 66 | dividend_yield = 0.0 67 | volatility = 20.0 68 | days_to_maturity = 60 69 | 70 | interest_rate = interest_rate / 100 71 | dividend_yield = dividend_yield / 100 72 | volatility = volatility / 100 73 | time_to_maturity = days_to_maturity / 365 74 | 75 | bs = get_bs_info( 76 | stock_price, strike, interest_rate, volatility, time_to_maturity, dividend_yield 77 | ) 78 | 79 | assert bs.call_price == 1.44 80 | assert bs.call_delta == 0.2942972000055033 81 | assert bs.call_theta == -8.780589609657586 82 | assert bs.call_rho == 0.04600635174517672 83 | assert bs.call_itm_prob == 0.2669832523577367 84 | assert bs.put_price == 6.27 85 | assert bs.put_delta == -0.7057027999944967 86 | assert bs.put_theta == -7.732314219179215 87 | assert bs.put_rho == -0.12631289052524033 88 | assert bs.put_itm_prob == 0.7330167476422633 89 | assert bs.gamma == 0.042503588182705464 90 | assert bs.vega == 0.13973782416231934 91 | 92 | 93 | def test_covered_call(nvidia): 94 | # https://medium.com/@rgaveiga/python-for-options-trading-2-mixing-options-and-stocks-1e9f59f388f 95 | 96 | inputs = Inputs.model_validate( 97 | nvidia 98 | | { 99 | # The covered call strategy is defined 100 | "strategy": [ 101 | {"type": "stock", "n": 100, "action": "buy"}, 102 | { 103 | "type": "call", 104 | "strike": 185.0, 105 | "premium": 4.1, 106 | "n": 100, 107 | "action": "sell", 108 | "expiration": nvidia["target_date"], 109 | }, 110 | ], 111 | } 112 | ) 113 | 114 | outputs = run_strategy(inputs) 115 | 116 | assert isinstance(outputs, Outputs) 117 | assert outputs.model_dump( 118 | exclude={"data", "inputs"}, 119 | exclude_none=True, 120 | exclude_defaults=True, 121 | ) == pytest.approx(COVERED_CALL_RESULT) 122 | 123 | 124 | def test_covered_call_w_days_to_target(nvidia): 125 | inputs = Inputs.model_validate( 126 | nvidia 127 | | { 128 | "start_date": None, 129 | "target_date": None, 130 | "days_to_target_date": 24, # 32 days minus 9 non-business days plus 1 to consider the expiration date 131 | "strategy": [ 132 | {"type": "stock", "n": 100, "action": "buy"}, 133 | { 134 | "type": "call", 135 | "strike": 185.0, 136 | "premium": 4.1, 137 | "n": 100, 138 | "action": "sell", 139 | }, 140 | ], 141 | } 142 | ) 143 | 144 | outputs = run_strategy(inputs) 145 | 146 | # Print useful information on screen 147 | assert isinstance(outputs, Outputs) 148 | assert outputs.model_dump( 149 | exclude={"data", "inputs"}, 150 | exclude_none=True, 151 | exclude_defaults=True, 152 | ) == pytest.approx(COVERED_CALL_RESULT) 153 | 154 | 155 | def test_covered_call_w_prev_position(nvidia): 156 | # https://medium.com/@rgaveiga/python-for-options-trading-2-mixing-options-and-stocks-1e9f59f388f 157 | 158 | inputs = Inputs.model_validate( 159 | nvidia 160 | | { 161 | # The covered call strategy is defined 162 | "strategy": [ 163 | {"type": "stock", "n": 100, "action": "buy", "prev_pos": 158.99}, 164 | { 165 | "type": "call", 166 | "strike": 185.0, 167 | "premium": 4.1, 168 | "n": 100, 169 | "action": "sell", 170 | "expiration": nvidia["target_date"], 171 | }, 172 | ] 173 | } 174 | ) 175 | 176 | outputs = run_strategy(inputs) 177 | 178 | assert outputs.model_dump( 179 | exclude={"data", "inputs"}, 180 | exclude_none=True, 181 | exclude_defaults=True, 182 | ) == { 183 | "probability_of_profit": 0.7048129541301169, 184 | "profit_ranges": [(154.9, float("inf"))], 185 | "per_leg_cost": [-15899.0, 409.99999999999994], 186 | "strategy_cost": -15489.0, 187 | "minimum_return_in_the_domain": -8590.000000000002, 188 | "maximum_return_in_the_domain": 3011.0, 189 | "implied_volatility": [0.0, 0.456], 190 | "in_the_money_probability": [1.0, 0.256866624586934], 191 | "delta": [1.0, -0.30713817729665704], 192 | "gamma": [0.0, 0.013948977387090415], 193 | "theta": [0.0, 0.19283555235589467], 194 | "vega": [0.0, 0.1832408146218486], 195 | "rho": [0.0, -0.04506390742751745], 196 | } 197 | 198 | 199 | def test_100_perc_itm(nvidia): 200 | # https://medium.com/@rgaveiga/python-for-options-trading-3-a-trade-with-100-probability-of-profit-886e934addbf 201 | 202 | inputs = Inputs.model_validate( 203 | nvidia 204 | | { 205 | # The covered call strategy is defined 206 | "strategy": [ 207 | { 208 | "type": "call", 209 | "strike": 165.0, 210 | "premium": 12.65, 211 | "n": 100, 212 | "action": "buy", 213 | "prev_pos": 7.5, 214 | "expiration": nvidia["target_date"], 215 | }, 216 | { 217 | "type": "call", 218 | "strike": 170.0, 219 | "premium": 9.9, 220 | "n": 100, 221 | "action": "sell", 222 | "expiration": nvidia["target_date"], 223 | }, 224 | ] 225 | } 226 | ) 227 | 228 | outputs = run_strategy(inputs) 229 | 230 | assert outputs.model_dump( 231 | exclude={"data", "inputs"}, 232 | exclude_none=True, 233 | exclude_defaults=True, 234 | ) == pytest.approx(PROB_100_ITM_RESULT) 235 | 236 | 237 | def test_naked_call(): 238 | inputs = Inputs.model_validate( 239 | { 240 | "stock_price": 164.04, 241 | "volatility": 0.272, 242 | "start_date": "2021-11-22", 243 | "target_date": "2021-12-17", 244 | "interest_rate": 0.0002, 245 | "min_stock": 82.02, 246 | "max_stock": 246.06, 247 | "profit_target": 100.0, 248 | "loss_limit": -100.0, 249 | "model": "black-scholes", 250 | # The naked call strategy is defined 251 | "strategy": [ 252 | { 253 | "type": "call", 254 | "strike": 175.00, 255 | "premium": 1.15, 256 | "n": 100, 257 | "action": "sell", 258 | } 259 | ], 260 | } 261 | ) 262 | 263 | outputs = run_strategy(inputs) 264 | 265 | assert isinstance(outputs, Outputs) 266 | assert outputs.model_dump( 267 | exclude={"data", "inputs"}, exclude_none=True 268 | ) == pytest.approx(PROB_NAKED_CALL) 269 | 270 | 271 | def test_3_legs(nvidia): 272 | inputs = Inputs.model_validate( 273 | nvidia 274 | | { 275 | "strategy": [ 276 | {"type": "stock", "n": 100, "action": "buy", "prev_pos": 158.99}, 277 | { 278 | "type": "call", 279 | "strike": 165.0, 280 | "premium": 12.65, 281 | "n": 100, 282 | "action": "buy", 283 | "prev_pos": 7.5, 284 | "expiration": nvidia["target_date"], 285 | }, 286 | { 287 | "type": "call", 288 | "strike": 170.0, 289 | "premium": 9.9, 290 | "n": 100, 291 | "action": "sell", 292 | "expiration": nvidia["target_date"], 293 | }, 294 | ] 295 | } 296 | ) 297 | 298 | outputs = run_strategy(inputs) 299 | 300 | assert outputs.model_dump( 301 | exclude={"data", "inputs"}, 302 | exclude_none=True, 303 | exclude_defaults=True, 304 | ) == { 305 | "probability_of_profit": 0.6790581742719213, 306 | "profit_ranges": [(156.6, float("inf"))], 307 | "per_leg_cost": [-15899.0, -750.0, 990.0], 308 | "strategy_cost": -15659.0, 309 | "minimum_return_in_the_domain": -8760.000000000002, 310 | "maximum_return_in_the_domain": 11740.0, 311 | "implied_volatility": [0.0, 0.494, 0.482], 312 | "in_the_money_probability": [1.0, 0.54558925139931, 0.465831136209786], 313 | "delta": [1.0, 0.6039490632362865, -0.525237550169406], 314 | "gamma": [0.0, 0.015297136732317718, 0.015806160944019643], 315 | "theta": [0.0, -0.21821351060901806, 0.22301627833773927], 316 | "vega": [0.0, 0.20095091693287098, 0.20763771616023433], 317 | "rho": [0.0, 0.08536880237502181, -0.07509774107468528], 318 | } 319 | 320 | 321 | def test_run_with_mc_array(nvidia): 322 | arr = create_price_array( 323 | inputs_data=BlackScholesModelInputs( 324 | stock_price=168.99, 325 | volatility=0.483, 326 | interest_rate=0.045, 327 | years_to_target_date=24 / 365, 328 | ), 329 | seed=0, 330 | ) 331 | 332 | inputs = Inputs.model_validate( 333 | nvidia 334 | | { 335 | "model": "array", 336 | "array": arr, 337 | "strategy": [ 338 | {"type": "stock", "n": 100, "action": "buy"}, 339 | { 340 | "type": "call", 341 | "strike": 185.0, 342 | "premium": 4.1, 343 | "n": 100, 344 | "action": "sell", 345 | "expiration": nvidia["target_date"], 346 | }, 347 | ], 348 | } 349 | ) 350 | 351 | outputs = run_strategy(inputs) 352 | 353 | assert outputs.model_dump( 354 | exclude={"data", "inputs"}, 355 | exclude_none=True, 356 | exclude_defaults=True, 357 | ) == pytest.approx( 358 | { 359 | "probability_of_profit": 0.56564, 360 | "profit_ranges": [(164.9, float("inf"))], 361 | "expected_profit": 1356.3702804556585, 362 | "expected_loss": -1407.9604829624866, 363 | "per_leg_cost": [-16899.0, 409.99999999999994], 364 | "strategy_cost": -16489.0, 365 | "minimum_return_in_the_domain": -9590.000000000002, 366 | "maximum_return_in_the_domain": 2011.0, 367 | "implied_volatility": [0.0, 0.456], 368 | "in_the_money_probability": [1.0, 0.256866624586934], 369 | "delta": [1.0, -0.30713817729665704], 370 | "gamma": [0.0, 0.013948977387090415], 371 | "theta": [0.0, 0.19283555235589467], 372 | "vega": [0.0, 0.1832408146218486], 373 | "rho": [0.0, -0.04506390742751745], 374 | }, 375 | rel=0.05, 376 | ) 377 | 378 | 379 | def test_covered_call_w_laplace_distribution(nvidia): 380 | arr = create_price_array( 381 | inputs_data=LaplaceInputs( 382 | stock_price=168.99, 383 | volatility=0.483, 384 | years_to_target_date=24 / 365, 385 | mu=-0.07, 386 | ), 387 | seed=0, 388 | ) 389 | 390 | inputs = Inputs.model_validate( 391 | nvidia 392 | | { 393 | "model": "array", 394 | "array": arr, 395 | "strategy": [ 396 | {"type": "stock", "n": 100, "action": "buy"}, 397 | { 398 | "type": "call", 399 | "strike": 185.0, 400 | "premium": 4.1, 401 | "n": 100, 402 | "action": "sell", 403 | "expiration": nvidia["target_date"], 404 | }, 405 | ], 406 | } 407 | ) 408 | 409 | outputs = run_strategy(inputs) 410 | 411 | # Print useful information on screen 412 | assert isinstance(outputs, Outputs) 413 | assert outputs.model_dump( 414 | exclude={"data", "inputs"}, 415 | exclude_none=True, 416 | exclude_defaults=True, 417 | ) == pytest.approx( 418 | { 419 | "probability_of_profit": 0.60194, 420 | "profit_ranges": [(164.9, float("inf"))], 421 | "per_leg_cost": [-16899.0, 409.99999999999994], 422 | "strategy_cost": -16489.0, 423 | "minimum_return_in_the_domain": -9590.000000000002, 424 | "maximum_return_in_the_domain": 2011.0, 425 | "implied_volatility": [0.0, 0.456], 426 | "in_the_money_probability": [1.0, 0.256866624586934], 427 | "delta": [1.0, -0.30713817729665704], 428 | "gamma": [0.0, 0.013948977387090415], 429 | "theta": [0.0, 0.19283555235589467], 430 | "vega": [0.0, 0.1832408146218486], 431 | "rho": [0.0, -0.04506390742751745], 432 | "expected_profit": 1148.25, 433 | "expected_loss": -1333.85, 434 | } 435 | ) 436 | 437 | 438 | def test_calendar_spread(): 439 | stock_price = 127.14 # Apple stock 440 | volatility = 0.427 441 | start_date = "2021-01-18" 442 | target_date = "2021-01-29" 443 | interest_rate = 0.0009 444 | min_stock = stock_price - round(stock_price * 0.5, 2) 445 | max_stock = stock_price + round(stock_price * 0.5, 2) 446 | strategy = [ 447 | { 448 | "type": "call", 449 | "strike": 127.00, 450 | "premium": 4.60, 451 | "n": 1000, 452 | "action": "sell", 453 | }, 454 | { 455 | "type": "call", 456 | "strike": 127.00, 457 | "premium": 5.90, 458 | "n": 1000, 459 | "action": "buy", 460 | "expiration": "2021-02-12", 461 | }, 462 | ] 463 | 464 | inputs = { 465 | "stock_price": stock_price, 466 | "start_date": start_date, 467 | "target_date": target_date, 468 | "volatility": volatility, 469 | "interest_rate": interest_rate, 470 | "min_stock": min_stock, 471 | "max_stock": max_stock, 472 | "strategy": strategy, 473 | } 474 | 475 | outputs = run_strategy(inputs) 476 | 477 | assert outputs.model_dump( 478 | exclude={"data", "inputs"}, exclude_none=True, exclude_defaults=True 479 | ) == { 480 | "probability_of_profit": 0.599111819020198, 481 | "profit_ranges": [(118.87, 136.15)], 482 | "per_leg_cost": [4600.0, -5900.0], 483 | "strategy_cost": -1300.0, 484 | "minimum_return_in_the_domain": -1300.0000000000146, 485 | "maximum_return_in_the_domain": 3009.999999999999, 486 | "implied_volatility": [0.47300000000000003, 0.419], 487 | "in_the_money_probability": [0.4895105709759477, 0.4805997906939539], 488 | "delta": [-0.5216914758915705, 0.5273457614638198], 489 | "gamma": [0.03882722919950356, 0.02669940508461828], 490 | "theta": [0.22727438444823292, -0.15634971608107964], 491 | "vega": [0.09571294014902997, 0.1389462831961853], 492 | "rho": [-0.022202087247849632, 0.046016214466188525], 493 | } 494 | -------------------------------------------------------------------------------- /tests/test_misc.py: -------------------------------------------------------------------------------- 1 | import datetime as dt 2 | import time 3 | 4 | import pytest 5 | 6 | from optionlab.models import BlackScholesModelInputs 7 | from optionlab.price_array import create_price_array, _get_array_price_from_BS 8 | from optionlab.utils import get_nonbusiness_days 9 | 10 | 11 | def test_holidays(): 12 | start_date = dt.date(2024, 1, 1) 13 | end_date = dt.date(2024, 12, 31) 14 | 15 | us_nonbusiness_days = get_nonbusiness_days(start_date, end_date, country="US") 16 | 17 | assert us_nonbusiness_days == 115 18 | 19 | china_nonbusiness_days = get_nonbusiness_days(start_date, end_date, country="China") 20 | 21 | assert china_nonbusiness_days == 123 22 | 23 | brazil_nonbusiness_days = get_nonbusiness_days( 24 | start_date, end_date, country="Brazil" 25 | ) 26 | 27 | assert brazil_nonbusiness_days == 109 28 | 29 | germany_nonbusiness_days = get_nonbusiness_days( 30 | start_date, end_date, country="Germany" 31 | ) 32 | 33 | assert germany_nonbusiness_days == 113 34 | 35 | uk_nonbusiness_days = get_nonbusiness_days(start_date, end_date, country="UK") 36 | 37 | assert uk_nonbusiness_days == 110 38 | 39 | 40 | @pytest.mark.benchmark 41 | def test_holidays_benchmark(days: int = 366): 42 | start_date = dt.date(2024, 1, 1) 43 | 44 | for i in range(days): 45 | end_date = start_date + dt.timedelta(days=1) 46 | 47 | get_nonbusiness_days(start_date, end_date, country="US") 48 | 49 | 50 | def test_benchmark_holidays(benchmark): 51 | start_time = time.time() 52 | benchmark(test_holidays_benchmark) 53 | 54 | assert time.time() - start_time < 2 # takes avg. ~1.1ms on M1 55 | 56 | 57 | def test_cache_price_samples(): 58 | _get_array_price_from_BS.cache_clear() 59 | 60 | stock_price = 168.99 61 | volatility = 0.483 62 | interest_rate = 0.045 63 | years_to_target = 24 / 365 64 | 65 | sample1 = create_price_array( 66 | inputs_data=BlackScholesModelInputs( 67 | stock_price=stock_price, 68 | volatility=volatility, 69 | interest_rate=interest_rate, 70 | years_to_target_date=years_to_target, 71 | ), 72 | seed=0, 73 | ) 74 | 75 | # cache_info1 = create_price_samples.cache_info() 76 | # assert cache_info1.misses == 1 77 | # assert cache_info1.hits == 0 78 | # assert cache_info1.currsize == 1 79 | assert sample1.sum() == pytest.approx(16951655.848562226, rel=0.01) 80 | 81 | sample2 = create_price_array( 82 | inputs_data=BlackScholesModelInputs( 83 | stock_price=stock_price, 84 | volatility=volatility, 85 | interest_rate=interest_rate, 86 | years_to_target_date=years_to_target, 87 | ), 88 | seed=1, 89 | ) 90 | 91 | # cache_info2 = create_price_samples.cache_info() 92 | # assert cache_info2.misses == 2 93 | # assert cache_info2.hits == 0 94 | # assert cache_info2.currsize == 2 95 | assert sample2.sum() == pytest.approx(16959678.71517979, rel=0.01) 96 | 97 | stock_price = 167.0 98 | 99 | sample3 = create_price_array( 100 | inputs_data={ 101 | "model": "black-scholes", 102 | "stock_price": stock_price, 103 | "volatility": volatility, 104 | "interest_rate": interest_rate, 105 | "years_to_target_date": years_to_target, 106 | }, 107 | seed=0, 108 | ) 109 | 110 | # cache_info3 = create_price_samples.cache_info() 111 | # assert cache_info3.misses == 2 112 | # assert cache_info3.hits == 1 113 | # assert cache_info3.currsize == 2 114 | assert sample3.sum() == pytest.approx(16752035.781465728, rel=0.01) 115 | 116 | sample4 = create_price_array( 117 | inputs_data={ 118 | "model": "laplace", 119 | "stock_price": 168.99, 120 | "volatility": 0.483, 121 | "mu": 0.05, 122 | "years_to_target_date": 24 / 365, 123 | }, 124 | seed=0, 125 | ) 126 | 127 | # cache_info4 = create_price_samples.cache_info() 128 | # assert cache_info4.misses == 3 129 | # assert cache_info4.hits == 1 130 | # assert cache_info4.currsize == 3 131 | assert sample4.sum() == pytest.approx(17083995.574185822, rel=0.01) 132 | -------------------------------------------------------------------------------- /tests/test_models.py: -------------------------------------------------------------------------------- 1 | import datetime as dt 2 | 3 | import pytest 4 | 5 | from optionlab.models import Inputs 6 | from numpy import array 7 | 8 | 9 | def test_only_one_closed_position(nvidia): 10 | inputs = nvidia | { 11 | # The covered call strategy is defined 12 | "strategy": [ 13 | {"type": "closed", "prev_pos": 100}, 14 | {"type": "closed", "prev_pos": 100}, 15 | ], 16 | } 17 | 18 | with pytest.raises(ValueError) as err: 19 | Inputs.model_validate(inputs) 20 | 21 | assert "Only one position of type 'closed' is allowed!" in str(err.value) 22 | 23 | 24 | def test_validate_dates(nvidia): 25 | strategy = [{"type": "closed", "prev_pos": 100}] 26 | inputs = nvidia | { 27 | "start_date": dt.date(2023, 1, 14), 28 | "target_date": dt.date(2023, 1, 10), 29 | "strategy": strategy, 30 | } 31 | 32 | with pytest.raises(ValueError) as err: 33 | Inputs.model_validate(inputs) 34 | 35 | assert "Start date must be before target date!" in str(err.value) 36 | 37 | inputs = nvidia | { 38 | "start_date": dt.date(2023, 1, 14), 39 | "target_date": dt.date(2023, 1, 17), 40 | "strategy": [ 41 | { 42 | "type": "call", 43 | "strike": 185.0, 44 | "premium": 4.1, 45 | "n": 100, 46 | "action": "sell", 47 | "expiration": dt.date(2023, 1, 16), 48 | } 49 | ], 50 | } 51 | 52 | with pytest.raises(ValueError) as err: 53 | Inputs.model_validate(inputs) 54 | 55 | assert "Expiration dates must be after or on target date!" in str(err.value) 56 | 57 | inputs = nvidia | { 58 | "start_date": None, 59 | "target_date": None, 60 | "days_to_target_date": 30, 61 | "strategy": [ 62 | {"type": "stock", "n": 100, "action": "buy"}, 63 | { 64 | "type": "call", 65 | "strike": 185.0, 66 | "premium": 4.1, 67 | "n": 100, 68 | "action": "sell", 69 | "expiration": dt.date(2023, 1, 17), 70 | }, 71 | ], 72 | } 73 | 74 | with pytest.raises(ValueError) as err: 75 | Inputs.model_validate(inputs) 76 | 77 | assert "You can't mix a strategy expiration with a days_to_target_date." in str( 78 | err.value 79 | ) 80 | 81 | 82 | def test_array_distribution_with_no_array(nvidia): 83 | inputs = nvidia | { 84 | "model": "array", 85 | "strategy": [ 86 | {"type": "closed", "prev_pos": 100}, 87 | ], 88 | } 89 | 90 | with pytest.raises(ValueError) as err: 91 | Inputs.model_validate(inputs) 92 | 93 | assert ( 94 | "Array of terminal stock prices must be provided if model is 'array'." 95 | in str(err.value) 96 | ) 97 | 98 | inputs |= {"array": array([])} 99 | 100 | with pytest.raises(ValueError) as err: 101 | Inputs.model_validate(inputs) 102 | 103 | assert ( 104 | "Array of terminal stock prices must be provided if model is 'array'." 105 | in str(err.value) 106 | ) 107 | --------------------------------------------------------------------------------