├── .gitignore ├── LICENSE ├── README.md ├── colab └── deep_hedging_colab.ipynb ├── deep_hedging ├── __init__.py └── deep_hedging.py ├── env.yml ├── instruments ├── EuropeanCall.py └── __init__.py ├── loss_metrics ├── __init__.py ├── cvar.py └── entropy.py ├── presentation ├── data │ └── target_PnL_0.015.npy ├── default_params.py ├── dh_worker.py ├── main.py ├── main_window.py └── readme.txt ├── pyqt5 ├── default_params.py ├── dh_worker.py ├── main.py ├── main_window.py └── readme.txt ├── requirements.txt ├── stochastic_processes ├── BlackScholesProcess.py └── __init__.py └── utilities ├── __init__.py └── train_test_split.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | 131 | # Mac 132 | .DS_Store 133 | .swp 134 | -------------------------------------------------------------------------------- /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 | # Deep Hedging Demo 2 | ## Pricing Derivatives using Machine Learning 3 | 4 | ![Image of Demo](https://user-images.githubusercontent.com/7247589/99870023-ca5ec380-2b9d-11eb-8646-4e78ad87f8ad.png) 5 | 6 | ``` 1) Jupyter version: Run ./colab/deep_hedging_colab.ipynb on Colab. ``` 7 | 8 | ``` 2) Gui version: Run python ./pyqt5/main.py Check ./requirements.txt for main dependencies.``` 9 | 10 | The Black-Scholes (BS) model – developed in 1973 and based on Nobel Prize winning works – has been the de-facto standard for pricing options and other financial derivatives for nearly half a century. The model can be used, under the assumption of a perfect financial market, to calculate an options price and the associated risk sensitivities. These risk sensitivities can then be theoretically used by a trader to create a perfect hedging strategy that eliminates all risks in a portfolio of options. However, the necessary conditions for a perfect financial market, such as zero transaction cost and the possibility of continuous trading, are difficult to meet in the real world. Therefore, in practice, banks have to rely on their traders’ intuition and experience to augment the BS model hedges with manual adjustments to account for these market imperfections. 11 | The derivative desks of every bank all hedge their positions, and their PnL and risk exposure depend crucially on the quality of their hedges. If their hedges does not properly account for market imperfections, banks might underestimate the true risk exposure of their portfolios. On the other hand, if their hedges overestimate the cost of market imperfections, banks might overprice their positions (relative to their competitors) and hence risk losing trades and/or customers. Over the last few decades, the financial market has become increasingly sophisticated. Intuition and experience of traders might not be sufficiently fast and accurate to compute the impact of market imperfections on their portfolios and to come up with good manual adjustments to their BS model hedges. 12 | 13 | These limitations of the BS model are well-known, but neither academics nor practitioners have managed to develop alternatives to properly and systematically account for market frictions – at least not successful enough to be widely adopted by banks. Could machine learning (ML) be the cure? Last year, the Risk magazine reported that JP Morgan has begun to use machine learning to hedge (a.k.a. Deep Hedging) a portion of its vanilla index options flow book and plan to roll out the similar technology for single stocks, baskets and light exotics. According to Risk.net (2019), the technology can create hedging strategies that “automatically factor in market fictions, such as transaction costs, liquidity constraints and risk limits”. More amazingly, the ML algorithm “far outperformed” hedging strategies derived from the BS model, and it could reduce the cost of hedging (in certain asset class) by “as much as 80%”. The technology has been heralded by some as “a breakthrough in quantitative finance, one that could mark the end of the Black-Scholes era.” Hence, it is not surprising that firms, such as Bank of America, Societe Generale and IBM, are reportedly developing their own ML-based system for derivative hedging. 14 | 15 | Machine learning algorithms are often referred to as “black boxes” because of the inherent opaqueness and difficulties to inspect how an algorithm is able to accomplishing what is accomplishing. Buhler et al (2019) recently published a paper outlining the mechanism of this ground-breaking technology. We follow their outlined methodology to implement and replicate the “deep hedging” algorithm under different simulated market conditions. Given a distribution of the underlying assets and trader preference, the “deep hedging” algorithm attempts to identify the optimal hedge strategy (as a function of over 10k model parameters) that minimizes the residual risk of a hedged portfolio. We implement the “deep hedging” algorithm to demonstrate its potential benefit in a simplified yet sufficiently realistic setting. We first benchmark the deep hedging strategy against the classic Black-Scholes hedging strategy in a perfect world with no transaction cost, in which case the performance of both strategies should be similar. Then, we benchmark again in a world with market friction (i.e. non-zero transaction costs), in which case the deep hedging strategy should outperform the classic Black-Scholes hedging strategy. 16 | 17 | **References:** 18 | 19 | Risk.net, (2019). “Deep hedging and the end of the Black-Scholes era.” 20 | 21 | Hans Buhler et al, (2019). “Deep Hedging.” Quantitative Finance, 19(8). 22 | -------------------------------------------------------------------------------- /deep_hedging/__init__.py: -------------------------------------------------------------------------------- 1 | from .deep_hedging import Deep_Hedging_Model 2 | from .deep_hedging import Delta_SubModel 3 | -------------------------------------------------------------------------------- /deep_hedging/deep_hedging.py: -------------------------------------------------------------------------------- 1 | from tensorflow.keras.layers import Input, Dense, Concatenate, Subtract, \ 2 | Lambda, Add, Dot, BatchNormalization, Activation, LeakyReLU 3 | from tensorflow.keras.models import Model 4 | from tensorflow.keras.initializers import he_normal, Zeros, he_uniform, TruncatedNormal 5 | import tensorflow.keras.backend as K 6 | import tensorflow as tf 7 | import numpy as np 8 | 9 | intitalizer_dict = { 10 | "he_normal": he_normal(), 11 | "zeros": Zeros(), 12 | "he_uniform": he_uniform(), 13 | "truncated_normal": TruncatedNormal() 14 | } 15 | 16 | bias_initializer=he_uniform() 17 | 18 | class Strategy_Layer(tf.keras.layers.Layer): 19 | def __init__(self, d = None, m = None, use_batch_norm = None, \ 20 | kernel_initializer = "he_uniform", \ 21 | activation_dense = "relu", activation_output = "linear", 22 | delta_constraint = None, day = None): 23 | super().__init__(name = "delta_" + str(day)) 24 | self.d = d 25 | self.m = m 26 | self.use_batch_norm = use_batch_norm 27 | self.activation_dense = activation_dense 28 | self.activation_output = activation_output 29 | self.delta_constraint = delta_constraint 30 | self.kernel_initializer = kernel_initializer 31 | 32 | self.intermediate_dense = [None for _ in range(d)] 33 | self.intermediate_BN = [None for _ in range(d)] 34 | 35 | for i in range(d): 36 | self.intermediate_dense[i] = Dense(self.m, 37 | kernel_initializer=self.kernel_initializer, 38 | bias_initializer=bias_initializer, 39 | use_bias=(not self.use_batch_norm)) 40 | if self.use_batch_norm: 41 | self.intermediate_BN[i] = BatchNormalization(momentum = 0.99, trainable=True) 42 | 43 | self.output_dense = Dense(1, 44 | kernel_initializer=self.kernel_initializer, 45 | bias_initializer = bias_initializer, 46 | use_bias=True) 47 | 48 | def call(self, input): 49 | for i in range(self.d): 50 | if i == 0: 51 | output = self.intermediate_dense[i](input) 52 | else: 53 | output = self.intermediate_dense[i](output) 54 | 55 | if self.use_batch_norm: 56 | # Batch normalization. 57 | output = self.intermediate_BN[i](output, training=True) 58 | 59 | if self.activation_dense == "leaky_relu": 60 | output = LeakyReLU()(output) 61 | else: 62 | output = Activation(self.activation_dense)(output) 63 | 64 | output = self.output_dense(output) 65 | 66 | if self.activation_output == "leaky_relu": 67 | output = LeakyReLU()(output) 68 | elif self.activation_output == "sigmoid" or self.activation_output == "tanh" or \ 69 | self.activation_output == "hard_sigmoid": 70 | # Enforcing hedge constraints 71 | if self.delta_constraint is not None: 72 | output = Activation(self.activation_output)(output) 73 | delta_min, delta_max = self.delta_constraint 74 | output = Lambda(lambda x : (delta_max-delta_min)*x + delta_min)(output) 75 | else: 76 | output = Activation(self.activation_output)(output) 77 | 78 | return output 79 | 80 | def Deep_Hedging_Model(N = None, d = None, m = None, \ 81 | risk_free = None, dt = None, initial_wealth = 0.0, epsilon = 0.0, \ 82 | final_period_cost = False, strategy_type = None, use_batch_norm = None, \ 83 | kernel_initializer = "he_uniform", \ 84 | activation_dense = "relu", activation_output = "linear", 85 | delta_constraint = None, share_stretegy_across_time = False, 86 | cost_structure = "proportional"): 87 | 88 | # State variables. 89 | prc = Input(shape=(1,), name = "prc_0") 90 | information_set = Input(shape=(1,), name = "information_set_0") 91 | 92 | inputs = [prc, information_set] 93 | 94 | for j in range(N+1): 95 | if j < N: 96 | # Define the inputs for the strategy layers here. 97 | if strategy_type == "simple": 98 | helper1 = information_set 99 | elif strategy_type == "recurrent": 100 | if j ==0: 101 | # Tensorflow hack to deal with the dimension problem. 102 | # Strategy at t = -1 should be 0. 103 | # There is probably a better way but this works. 104 | # Constant tensor doesn't work. 105 | strategy = Lambda(lambda x: x*0.0)(prc) 106 | 107 | helper1 = Concatenate()([information_set,strategy]) 108 | 109 | # Determine if the strategy function depends on time t or not. 110 | if not share_stretegy_across_time: 111 | strategy_layer = Strategy_Layer(d = d, m = m, 112 | use_batch_norm = use_batch_norm, \ 113 | kernel_initializer = kernel_initializer, \ 114 | activation_dense = activation_dense, \ 115 | activation_output = activation_output, 116 | delta_constraint = delta_constraint, \ 117 | day = j) 118 | else: 119 | if j == 0: 120 | # Strategy does not depend on t so there's only a single 121 | # layer at t = 0 122 | strategy_layer = Strategy_Layer(d = d, m = m, 123 | use_batch_norm = use_batch_norm, \ 124 | kernel_initializer = kernel_initializer, \ 125 | activation_dense = activation_dense, \ 126 | activation_output = activation_output, 127 | delta_constraint = delta_constraint, \ 128 | day = j) 129 | 130 | strategyhelper = strategy_layer(helper1) 131 | 132 | 133 | # strategy_-1 is set to 0 134 | # delta_strategy = strategy_{t+1} - strategy_t 135 | if j == 0: 136 | delta_strategy = strategyhelper 137 | else: 138 | delta_strategy = Subtract(name = "diff_strategy_" + str(j))([strategyhelper, strategy]) 139 | 140 | if cost_structure == "proportional": 141 | # Proportional transaction cost 142 | absolutechanges = Lambda(lambda x : K.abs(x), name = "absolutechanges_" + str(j))(delta_strategy) 143 | costs = Dot(axes=1)([absolutechanges,prc]) 144 | costs = Lambda(lambda x : epsilon*x, name = "cost_" + str(j))(costs) 145 | elif cost_structure == "constant": 146 | # Tensorflow hack.. 147 | costs = Lambda(lambda x : epsilon + x*0.0)(prc) 148 | 149 | if j == 0: 150 | wealth = Lambda(lambda x : initial_wealth - x, name = "costDot_" + str(j))(costs) 151 | else: 152 | wealth = Subtract(name = "costDot_" + str(j))([wealth, costs]) 153 | 154 | # Wealth for the next period 155 | # w_{t+1} = w_t + (strategy_t-strategy_{t+1})*prc_t 156 | # = w_t - delta_strategy*prc_t 157 | mult = Dot(axes=1)([delta_strategy, prc]) 158 | wealth = Subtract(name = "wealth_" + str(j))([wealth, mult]) 159 | 160 | # Accumulate interest rate for next period. 161 | FV_factor = np.exp(risk_free*dt) 162 | wealth = Lambda(lambda x: x*FV_factor)(wealth) 163 | 164 | prc = Input(shape=(1,),name = "prc_" + str(j+1)) 165 | information_set = Input(shape=(1,), name = "information_set_" + str(j+1)) 166 | 167 | strategy = strategyhelper 168 | 169 | if j != N - 1: 170 | inputs += [prc, information_set] 171 | else: 172 | inputs += [prc] 173 | else: 174 | # The paper assumes no transaction costs for the final period 175 | # when the position is liquidated. 176 | if final_period_cost: 177 | if cost_structure == "proportional": 178 | # Proportional transaction cost 179 | absolutechanges = Lambda(lambda x : K.abs(x), name = "absolutechanges_" + str(j))(strategy) 180 | costs = Dot(axes=1)([absolutechanges,prc]) 181 | costs = Lambda(lambda x : epsilon*x, name = "cost_" + str(j))(costs) 182 | elif cost_structure == "constant": 183 | # Tensorflow hack.. 184 | costs = Lambda(lambda x : epsilon + x*0.0)(prc) 185 | 186 | wealth = Subtract(name = "costDot_" + str(j))([wealth, costs]) 187 | # Wealth for the final period 188 | # -delta_strategy = strategy_t 189 | mult = Dot(axes=1)([strategy, prc]) 190 | wealth = Add()([wealth, mult]) 191 | 192 | # Add the terminal payoff of any derivatives. 193 | payoff = Input(shape=(1,), name = "payoff") 194 | inputs += [payoff] 195 | 196 | wealth = Add(name = "wealth_" + str(j))([wealth,payoff]) 197 | return Model(inputs=inputs, outputs=wealth) 198 | 199 | def Delta_SubModel(model = None, days_from_today = None, share_stretegy_across_time = False, strategy_type = "simple"): 200 | if strategy_type == "simple": 201 | inputs = model.get_layer("delta_" + str(days_from_today)).input 202 | intermediate_inputs = inputs 203 | elif strategy_type == "recurrent": 204 | inputs = [Input(1,), Input(1,)] 205 | intermediate_inputs = Concatenate()(inputs) 206 | 207 | if not share_stretegy_across_time: 208 | outputs = model.get_layer("delta_" + str(days_from_today))(intermediate_inputs) 209 | else: 210 | outputs = model.get_layer("delta_0")(intermediate_inputs) 211 | 212 | return Model(inputs, outputs) 213 | -------------------------------------------------------------------------------- /env.yml: -------------------------------------------------------------------------------- 1 | name: base 2 | channels: 3 | - conda-forge 4 | - defaults 5 | dependencies: 6 | - brotlipy=0.7.0=py38h94c058a_1001 7 | - ca-certificates=2020.11.8=h033912b_0 8 | - certifi=2020.11.8=py38h50d1736_0 9 | - cffi=1.14.3=py38h2125817_2 10 | - chardet=3.0.4=py38h5347e94_1008 11 | - conda=4.9.2=py38h50d1736_0 12 | - conda-package-handling=1.7.2=py38h94c058a_0 13 | - cryptography=3.2.1=py38h5c1d3f9_0 14 | - idna=2.10=pyh9f0ad1d_0 15 | - libcxx=11.0.0=h439d374_0 16 | - libffi=3.3=hb1e8313_2 17 | - ncurses=6.2=h2e338ed_4 18 | - openssl=1.1.1h=haf1e3a3_0 19 | - pycosat=0.6.3=py38h94c058a_1005 20 | - pycparser=2.20=pyh9f0ad1d_2 21 | - pyopenssl=19.1.0=py_1 22 | - pysocks=1.7.1=py38h5347e94_2 23 | - python=3.8.3=h26836e1_1 24 | - python.app=2=py38_10 25 | - python_abi=3.8=1_cp38 26 | - readline=8.0=h0678c8f_2 27 | - requests=2.25.0=pyhd3deb0d_0 28 | - ruamel_yaml=0.15.80=py38h94c058a_1003 29 | - setuptools=49.6.0=py38h5347e94_2 30 | - six=1.15.0=pyh9f0ad1d_0 31 | - sqlite=3.33.0=h960bd1c_1 32 | - tk=8.6.10=hb0a8c7a_1 33 | - tqdm=4.53.0=pyhd3deb0d_0 34 | - urllib3=1.25.11=py_0 35 | - xz=5.2.5=haf1e3a3_1 36 | - yaml=0.2.5=haf1e3a3_0 37 | - zlib=1.2.11=h7795811_1010 38 | prefix: /usr/local/Caskroom/miniconda/base 39 | -------------------------------------------------------------------------------- /instruments/EuropeanCall.py: -------------------------------------------------------------------------------- 1 | import QuantLib as ql 2 | import numpy as np 3 | from scipy import stats 4 | from stochastic_processes import BlackScholesProcess 5 | 6 | # Assume continuous dividend with flat term-structure and flat dividend structure. 7 | class EuropeanCall: 8 | def __init__(self): 9 | pass 10 | 11 | def get_BS_price(self,S=None, sigma = None,risk_free = None, \ 12 | dividend = None, K = None, exercise_date = None, calculation_date = None, \ 13 | day_count = None, dt = None, evaluation_method = "Numpy"): 14 | 15 | if evaluation_method is "QuantLib": 16 | # For our purpose, assume all inputs are scalar. 17 | stochastic_process = BlackScholesProcess(s0 = S, sigma = sigma, \ 18 | risk_free = risk_free, dividend = dividend, day_count=day_count) 19 | 20 | engine = ql.AnalyticEuropeanEngine(stochastic_process.get_process(calculation_date)) 21 | 22 | ql_payoff = ql.PlainVanillaPayoff(ql.Option.Call, K) 23 | exercise_date = ql.EuropeanExercise(exercise_date) 24 | instrument = ql.VanillaOption(ql_payoff, exercise_date) 25 | 26 | if type(self.process).__name__ is "BlackScholesProcess": 27 | engine = ql.AnalyticEuropeanEngine(self.process.get_process(calculation_date)) 28 | 29 | instrument.setPricingEngine(engine) 30 | 31 | return instrument.NPV() 32 | elif evaluation_method is "Numpy": 33 | # For our purpose, assume s0 is a NumPy array, other inputs are scalar. 34 | T = np.arange(0, (exercise_date - calculation_date + 1))*dt 35 | T = np.repeat(np.flip(T[None,:]), S.shape[0], 0) 36 | 37 | # Ignore division by 0 warning (expected behaviors as the limits of CDF is defined). 38 | with np.errstate(divide='ignore'): 39 | d1 = np.divide(np.log(S / K) + (risk_free - dividend + 0.5 * sigma ** 2) * T, sigma * np.sqrt(T)) 40 | d2 = np.divide(np.log(S / K) + (risk_free - dividend - 0.5 * sigma ** 2) * T, sigma * np.sqrt(T)) 41 | 42 | return (S * stats.norm.cdf(d1, 0.0, 1.0) - K * np.exp(-risk_free * T) * stats.norm.cdf(d2, 0.0, 1.0)) 43 | 44 | def get_BS_delta(self,S=None, sigma = None,risk_free = None, \ 45 | dividend = None, K = None, exercise_date = None, calculation_date = None, \ 46 | day_count = None, dt = None, evaluation_method = "Numpy"): 47 | 48 | if evaluation_method is "QuantLib": 49 | # For our purpose, assume all inputs are scalar. 50 | stochastic_process = BlackScholesProcess(s0 = S, sigma = sigma, \ 51 | risk_free = risk_free, dividend = dividend, day_count=day_count) 52 | 53 | engine = ql.AnalyticEuropeanEngine(stochastic_process.get_process(calculation_date)) 54 | 55 | ql_payoff = ql.PlainVanillaPayoff(ql.Option.Call, K) 56 | exercise_date = ql.EuropeanExercise(exercise_date) 57 | instrument = ql.VanillaOption(ql_payoff, exercise_date) 58 | 59 | if type(self.process).__name__ is "BlackScholesProcess": 60 | engine = ql.AnalyticEuropeanEngine(self.process.get_process(calculation_date)) 61 | 62 | instrument.setPricingEngine(engine) 63 | 64 | return instrument.delta() 65 | elif evaluation_method is "Numpy": 66 | # For our purpose, assume s0 is a NumPy array, other inputs are scalar. 67 | T = np.arange(0, (exercise_date - calculation_date + 1))*dt 68 | T = np.repeat(np.flip(T[None,:]), S.shape[0], 0) 69 | 70 | # Ignore division by 0 warning (expected behaviors as the limits of CDF is defined). 71 | with np.errstate(divide='ignore'): 72 | d1 = np.divide(np.log(S / K) + (risk_free - dividend + 0.5 * sigma ** 2) * T, sigma * np.sqrt(T)) 73 | 74 | return stats.norm.cdf(d1, 0.0, 1.0) 75 | 76 | def get_BS_vega(self,S=None, sigma = None,risk_free = None, \ 77 | dividend = None, K = None, exercise_date = None, calculation_date = None, \ 78 | day_count = None, dt = None, evaluation_method = "Numpy"): 79 | 80 | if evaluation_method is "QuantLib": 81 | # For our purpose, assume all inputs are scalar. 82 | stochastic_process = BlackScholesProcess(s0 = S, sigma = sigma, \ 83 | risk_free = risk_free, dividend = dividend, day_count=day_count) 84 | 85 | engine = ql.AnalyticEuropeanEngine(stochastic_process.get_process(calculation_date)) 86 | 87 | ql_payoff = ql.PlainVanillaPayoff(ql.Option.Call, K) 88 | exercise_date = ql.EuropeanExercise(exercise_date) 89 | instrument = ql.VanillaOption(ql_payoff, exercise_date) 90 | 91 | if type(self.process).__name__ is "BlackScholesProcess": 92 | engine = ql.AnalyticEuropeanEngine(self.process.get_process(calculation_date)) 93 | 94 | instrument.setPricingEngine(engine) 95 | 96 | return instrument.vega() 97 | elif evaluation_method is "Numpy": 98 | # For our purpose, assume s0 is a NumPy array, other inputs are scalar. 99 | T = np.arange(0, (exercise_date - calculation_date + 1))*dt 100 | T = np.repeat(np.flip(T[None,:]), S.shape[0], 0) 101 | 102 | # Ignore division by 0 warning (expected behaviors as the limits of CDF is defined). 103 | with np.errstate(divide='ignore'): 104 | d1 = np.divide(np.log(S / K) + (risk_free - dividend + 0.5 * sigma ** 2) * T, sigma * np.sqrt(T)) 105 | 106 | return np.multiply(S, np.sqrt(T))*stats.norm.pdf(d1, 0.0, 1.0) 107 | 108 | def get_BS_PnL(self, S = None, payoff = None, delta = None, dt = None, risk_free = None, \ 109 | final_period_cost = None, epsilon = None, cost_structure="proportional"): 110 | # Compute Black-Scholes PnL (for a short position, i.e. the Bank sells 111 | # a call option. The model delta from Quantlib is a long delta. 112 | N = S.shape[1]-1 113 | 114 | PnL_BS = np.multiply(S[:,0], -delta[:,0]) \ 115 | 116 | if cost_structure == "proportional": 117 | PnL_BS -= np.abs(delta[:,0])*S[:,0]*epsilon 118 | elif cost_structure == "constant": 119 | PnL_BS -= epsilon 120 | 121 | PnL_BS = PnL_BS*np.exp(risk_free*dt) 122 | 123 | for t in range(1, N): 124 | PnL_BS += np.multiply(S[:,t], -delta[:,t] + delta[:,t-1]) 125 | 126 | if cost_structure == "proportional": 127 | PnL_BS -= np.abs(delta[:,t] -delta[:,t-1])*S[:,t]*epsilon 128 | elif cost_structure == "constant": 129 | PnL_BS -= epsilon 130 | 131 | PnL_BS = PnL_BS*np.exp(risk_free*dt) 132 | 133 | PnL_BS += np.multiply(S[:,N],delta[:,N-1]) + payoff 134 | 135 | if final_period_cost: 136 | if cost_structure == "proportional": 137 | PnL_BS -= np.abs(delta[:,N-1])*S[:,N]*epsilon 138 | elif cost_structure == "constant": 139 | PnL_BS -= epsilon 140 | 141 | return PnL_BS 142 | -------------------------------------------------------------------------------- /instruments/__init__.py: -------------------------------------------------------------------------------- 1 | from .EuropeanCall import EuropeanCall 2 | -------------------------------------------------------------------------------- /loss_metrics/__init__.py: -------------------------------------------------------------------------------- 1 | from .entropy import Entropy 2 | from .cvar import CVaR 3 | -------------------------------------------------------------------------------- /loss_metrics/cvar.py: -------------------------------------------------------------------------------- 1 | import tensorflow.keras.backend as K 2 | 3 | 4 | def CVaR(wealth = None, w = None, loss_param = None): 5 | alpha = loss_param 6 | # Expected shortfall risk measure 7 | return K.mean(w + (K.maximum(-wealth-w,0)/(1.0-alpha))) 8 | -------------------------------------------------------------------------------- /loss_metrics/entropy.py: -------------------------------------------------------------------------------- 1 | import tensorflow.keras.backend as K 2 | 3 | 4 | def Entropy(wealth=None, w=None, loss_param=None): 5 | _lambda = loss_param 6 | 7 | # Entropy (exponential) risk measure 8 | return (1/_lambda)*K.log(K.mean(K.exp(-_lambda*wealth))) 9 | -------------------------------------------------------------------------------- /presentation/data/target_PnL_0.015.npy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/YuMan-Tam/deep-hedging/b4c570a25f7134950579db37cc2cfe74ba4895ff/presentation/data/target_PnL_0.015.npy -------------------------------------------------------------------------------- /presentation/default_params.py: -------------------------------------------------------------------------------- 1 | # Define the initial parameters for the deep hedging demo 2 | def DeepHedgingParams(): 3 | params = [ 4 | {'name': 'European Call Option', 'type': 'group', 'children': [ 5 | {'name': 'S0', 'type': 'int', 'value': 100.0}, 6 | {'name': 'Strike', 'type': 'float', 'value': 100.0}, 7 | {'name': 'Implied Volatility', 'type': 'float', 'value': 0.2}, 8 | {'name': 'Risk-Free Rate', 'type': 'float', 'value': 0.0}, 9 | {'name': 'Dividend Yield', 'type': 'float', 'value': 0.0}, 10 | {'name': 'Maturity (in days)', 'type': 'int', 'value': 30}, 11 | {'name': 'Proportional Transaction Cost', 'type': 'group', 'children': [ 12 | {'name': 'Cost', 'type': 'float', 'value': 0.0}, 13 | ]}, 14 | ]}, 15 | {'name': 'Monte-Carlo Simulation', 'type': 'group', 'children': [ 16 | {'name': 'Sample Size', 'type': 'group', 'children': [ 17 | {'name': 'Training', 'type': 'int', 'value': 1*(10**5)}, 18 | {'name': 'Testing (as fraction of Training)', 'type': 'float', 'value': 0.2} 19 | ]}, 20 | ]}, 21 | {'name': 'Deep Hedging Strategy', 'type': 'group', 'children': [ 22 | {'name': 'Loss Function', 'type': 'group', 'children': [ 23 | {'name': 'Loss Type', 'type': 'list', 'values': {"Entropy": "Entropy", "CVaR": "CVaR"}, "default": "Entropy"}, 24 | {'name': 'Risk Aversion', 'type': 'float', 'value': 1.0} 25 | ]}, 26 | {'name': 'Network Structure', 'type': 'group', 'children': [ 27 | {'name': 'Network Type', 'type': 'list', 'values': {"Simple": "simple", "Recurrent": "recurrent"}, "default": "simple"}, 28 | {'name': 'Number of Hidden Layers', 'type': 'int', 'value': 1}, 29 | {'name': 'Number of Neurons', 'type': 'int', 'value': 15}, 30 | ]}, 31 | {'name': 'Learning Parameters', 'type': 'group', 'children': [ 32 | {'name': 'Learning Rate', 'type': 'float', 'value': 5e-3}, 33 | {'name': 'Mini-Batch Size', 'type': 'int', 'value': 256}, 34 | {'name': 'Number of Epochs', 'type': 'int', 'value': 50}, 35 | ]}, 36 | ]}, 37 | ] 38 | return params 39 | -------------------------------------------------------------------------------- /presentation/dh_worker.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | # Add the parent directory to the search paths to import the libraries. 5 | dir_path = os.path.dirname(os.path.realpath(__file__)) 6 | sys.path.insert(0, "/".join([dir_path, ".."])) 7 | 8 | import time 9 | 10 | import numpy as np 11 | 12 | import tensorflow as tf 13 | from tensorflow.keras.optimizers import Adam 14 | 15 | from pyqtgraph.Qt import QtCore 16 | 17 | from loss_metrics import Entropy 18 | 19 | 20 | # Reducing learning rate 21 | reduce_lr_param = {"patience": 2, "min_delta": 1e-3, "factor": 0.5} 22 | 23 | # Number of bins to plot for the PnL histograms. 24 | num_bins = 30 25 | 26 | 27 | # Put the deep-hedging algo in a separate thread than the plotting thread to 28 | # improve performance. 29 | class DHworker(QtCore.QThread): 30 | DH_outputs = QtCore.pyqtSignal(np.ndarray, 31 | np.ndarray, 32 | np.ndarray, 33 | np.float32, 34 | float, 35 | float, 36 | bool) 37 | 38 | def __init__(self): 39 | QtCore.QThread.__init__(self) 40 | 41 | def __del__(self): 42 | self.wait() 43 | 44 | def run_deep_hedge_algo(self, 45 | training_dataset=None, 46 | epochs=None, 47 | Ktrain=None, 48 | batch_size=None, 49 | model=None, 50 | submodel=None, 51 | strategy_type=None, 52 | loss_param=None, 53 | learning_rate=None, 54 | xtest=None, 55 | xtrain=None, 56 | initial_price_BS=None, 57 | width=None, 58 | I_range=None, 59 | x_range=None): 60 | self.training_dataset = training_dataset 61 | self.Ktrain = Ktrain 62 | self.batch_size = batch_size 63 | self.model = model 64 | self.submodel = submodel 65 | self.loss_param = loss_param 66 | self.initial_price_BS = initial_price_BS 67 | self.width = width 68 | self.epochs = epochs 69 | self.xtest = xtest 70 | self.xtrain = xtrain 71 | self.I_range = I_range 72 | self.x_range = x_range 73 | self.strategy_type = strategy_type 74 | self.learning_rate = learning_rate 75 | 76 | self.start() 77 | 78 | def pause(self): 79 | self._pause = True 80 | 81 | def cont(self): 82 | self._pause = False 83 | 84 | def stop(self): 85 | self._exit = True 86 | self.exit() 87 | 88 | def is_running(self): 89 | if self._pause or self._exit: 90 | return False 91 | else: 92 | return True 93 | 94 | def Reduce_Learning_Rate(self, num_epoch, loss): 95 | # Extract in-sample loss from the previous epoch. Comparison starts in 96 | # epoch 2 and the index for epoch 1 is 0 -> -2 97 | min_loss = self.loss_record[:, 1].min() 98 | if min_loss - loss < reduce_lr_param["min_delta"]: 99 | self.reduce_lr_counter += 1 100 | 101 | if self.reduce_lr_counter > reduce_lr_param["patience"]: 102 | self.learning_rate = self.learning_rate * reduce_lr_param["factor"] 103 | self.optimizer.learning_rate = self.learning_rate 104 | print( 105 | "The learning rate is reduced to {}.".format( 106 | self.learning_rate)) 107 | self.reduce_lr_counter = 0 108 | 109 | def run(self): 110 | # Initialize pause and stop buttons. 111 | self._exit = False 112 | self._pause = False 113 | 114 | # Variables to control skipped frames. If the DH algo output much 115 | # faster than the graphic output, the plots can be jammed. 116 | self.Figure_IsUpdated = True 117 | 118 | self.reduce_lr_counter = 0 119 | self.early_stopping_counter = 0 120 | 121 | certainty_equiv = tf.Variable(0.0, name="certainty_equiv") 122 | 123 | # Accelerator Function. 124 | model_func = tf.function(self.model) 125 | submodel_func = tf.function(self.submodel) 126 | 127 | self.optimizer = Adam(learning_rate=self.learning_rate) 128 | 129 | oos_loss = None 130 | PnL_DH = None 131 | DH_delta = None 132 | DH_bins = None 133 | num_batch = None 134 | 135 | num_epoch = 0 136 | while num_epoch <= self.epochs: 137 | # Exit event loop if the exit flag is set to True. 138 | if self._exit: 139 | mini_batch_iter = None 140 | self._exit = False 141 | self._pause = False 142 | break 143 | 144 | if not self._pause: 145 | try: 146 | mini_batch = mini_batch_iter.next() 147 | except BaseException: 148 | # Reduce learning rates and Early Stopping are based on 149 | # in-sample losses calculated once per epoch. 150 | in_sample_wealth = model_func(self.xtrain) 151 | in_sample_loss = Entropy( 152 | in_sample_wealth, certainty_equiv, self.loss_param) 153 | 154 | if num_epoch >= 1: 155 | print(("The deep-hedging price is {:0.4f} after " + 156 | "{} epoch.").format(oos_loss, num_epoch)) 157 | 158 | # Programming hack. The deep-hedging algo computes 159 | # faster than the computer can plot, so there could 160 | # be missing frames, i.e. there is no guarantee 161 | # that every batch is plotted. Here, I force a 162 | # signal to be emitted at the end of an epoch. 163 | time.sleep(1) 164 | 165 | self.DH_outputs.emit( 166 | PnL_DH, 167 | DH_delta, 168 | DH_bins, 169 | oos_loss.numpy().squeeze(), 170 | num_epoch, 171 | num_batch, 172 | True) 173 | 174 | # This is needed to prevent the output signals from 175 | # emitting faster than the system can plot a graph. 176 | # 177 | # The performance is much better than emitting at fixed 178 | # time intervals. 179 | self.Figure_IsUpdated = False 180 | 181 | if num_epoch == 1: 182 | self.loss_record = np.array( 183 | [num_epoch, in_sample_loss], ndmin=2) 184 | elif num_epoch > 1: 185 | self.Reduce_Learning_Rate(num_epoch, in_sample_loss) 186 | self.loss_record = np.vstack( 187 | [self.loss_record, 188 | np.array([num_epoch, in_sample_loss])]) 189 | 190 | mini_batch_iter = self.training_dataset.shuffle( 191 | self.Ktrain).batch(self.batch_size).__iter__() 192 | mini_batch = mini_batch_iter.next() 193 | 194 | num_batch = 0 195 | num_epoch += 1 196 | 197 | num_batch += 1 198 | 199 | # Record gradient 200 | with tf.GradientTape() as tape: 201 | wealth = model_func(mini_batch) 202 | loss = Entropy(wealth, certainty_equiv, self.loss_param) 203 | 204 | oos_wealth = model_func(self.xtest) 205 | PnL_DH = oos_wealth.numpy().squeeze() # Out-of-sample 206 | 207 | submodel_delta_range = np.expand_dims(self.I_range, axis=1) 208 | if self.strategy_type == "simple": 209 | submodel_inputs = submodel_delta_range 210 | elif self.strategy_type == "recurrent": 211 | # Assume previous delta is ATM. 212 | submodel_inputs = [ 213 | submodel_delta_range, 214 | np.ones_like(submodel_delta_range) * 0.5] 215 | DH_delta = submodel_func(submodel_inputs).numpy().squeeze() 216 | DH_bins, _ = np.histogram( 217 | PnL_DH + self.initial_price_BS, 218 | bins=num_bins, 219 | range=self.x_range) 220 | 221 | # Forward and backward passes 222 | grads = tape.gradient(loss, self.model.trainable_weights) 223 | self.optimizer.apply_gradients( 224 | zip(grads, self.model.trainable_weights)) 225 | 226 | # Compute Out-of-Sample Loss 227 | oos_loss = Entropy( 228 | oos_wealth, certainty_equiv, self.loss_param) 229 | 230 | if self.Figure_IsUpdated: 231 | self.DH_outputs.emit( 232 | PnL_DH, 233 | DH_delta, 234 | DH_bins, 235 | oos_loss.numpy().squeeze(), 236 | num_epoch, 237 | num_batch, 238 | False) 239 | 240 | # This is needed to prevent the output signals from emitting 241 | # faster than the system can plot a graph. 242 | # 243 | # The performance is much better than emitting at fixed time 244 | # intervals. 245 | self.Figure_IsUpdated = False 246 | 247 | # Mandatory pause for the first iteration to explain demo. 248 | if num_epoch == 1 and num_batch == 1: 249 | self.pause() 250 | else: 251 | time.sleep(1) 252 | -------------------------------------------------------------------------------- /presentation/main.py: -------------------------------------------------------------------------------- 1 | # Author: Yu-Man Tam 2 | # Email: yuman.tam@gmail.com 3 | # 4 | # Last updated: 5/22/2020 5 | # 6 | # Reference: Deep Hedging (2019, Quantitative Finance) by Buehler et al. 7 | # https://www.tandfonline.com/doi/abs/10.1080/14697688.2019.1571683 8 | 9 | import sys 10 | import os 11 | 12 | import tensorflow as tf 13 | 14 | # Add the parent directory to the search paths to import the libraries. 15 | dir_path = os.path.dirname(os.path.realpath(__file__)) 16 | sys.path.insert(0, "/".join([dir_path, ".."])) 17 | 18 | from pyqtgraph.Qt import QtWidgets 19 | from main_window import MainWindow 20 | 21 | # Tensorflow settings 22 | tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) 23 | tf.autograph.set_verbosity(0) 24 | 25 | if __name__ == '__main__': 26 | app = QtWidgets.QApplication(sys.argv) 27 | main = MainWindow() 28 | main.show() 29 | app.exec_() 30 | -------------------------------------------------------------------------------- /presentation/main_window.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | # Add the parent directory to the search paths to import the libraries. 5 | dir_path = os.path.dirname(os.path.realpath(__file__)) 6 | sys.path.insert(0, "/".join([dir_path, ".."])) 7 | 8 | import QuantLib as ql 9 | import numpy as np 10 | import tensorflow as tf 11 | import pyqtgraph as pg 12 | 13 | from tensorflow.keras.models import Model 14 | from tensorflow.keras.layers import Input, Concatenate 15 | from pyqtgraph.Qt import QtWidgets, QtGui, QtCore 16 | from pyqtgraph.parametertree import ParameterTree, Parameter 17 | from scipy.stats import norm 18 | 19 | from dh_worker import DHworker 20 | from default_params import DeepHedgingParams 21 | from loss_metrics import Entropy 22 | from deep_hedging import Deep_Hedging_Model 23 | from stochastic_processes import BlackScholesProcess 24 | from instruments import EuropeanCall 25 | from utilities import train_test_split 26 | 27 | # Specify the day (from today) for the delta plot. 28 | delta_plot_day = 15 29 | 30 | # European call option (short). 31 | calculation_date = ql.Date.todaysDate() 32 | 33 | # Day convention. 34 | day_count = ql.Actual365Fixed() # Actual/Actual (ISDA) 35 | 36 | # Information set (in string) 37 | # Choose from: S, log_S, normalized_log_S (by S0) 38 | information_set = "normalized_log_S" 39 | 40 | # Loss function 41 | # loss_type = "CVaR" (Expected Shortfall) -> loss_param = alpha 42 | # loss_type = "Entropy" -> loss_param = lambda 43 | loss_type = "Entropy" 44 | 45 | # Other NN parameters 46 | use_batch_norm = False 47 | kernel_initializer = "he_uniform" 48 | 49 | activation_dense = "leaky_relu" 50 | activation_output = "sigmoid" 51 | final_period_cost = False 52 | 53 | # Reducing learning rate 54 | reduce_lr_param = {"patience": 2, "min_delta": 1e-3, "factor": 0.5} 55 | 56 | # Number of bins to plot for the PnL histograms. 57 | num_bins = 30 58 | 59 | 60 | class MainWindow(QtWidgets.QMainWindow): 61 | def __init__(self): 62 | # Inheritance from the QMainWindow class 63 | # Reference: https://doc.qt.io/qt-5/qmainwindow.html 64 | super().__init__() 65 | self.days_from_today = delta_plot_day 66 | self.Thread_RunDH = DHworker() 67 | 68 | # The order of code is important here: Make sure the 69 | # emitted signals are connected before actually running 70 | # the Worker. 71 | self.Thread_RunDH.DH_outputs["PyQt_PyObject", 72 | "PyQt_PyObject", 73 | "PyQt_PyObject", 74 | "PyQt_PyObject", 75 | "double", 76 | "double", 77 | "bool"].connect(self.Update_Plots_Widget) 78 | 79 | # Define a top-level widget to hold everything 80 | self.w = QtGui.QWidget() 81 | 82 | # Create a grid layout to manage the widgets size and position 83 | self.layout = QtGui.QGridLayout() 84 | self.w.setLayout(self.layout) 85 | 86 | self.setCentralWidget(self.w) 87 | 88 | # Add the parameter menu. 89 | self.tree_height = 5 # Must be Odd number. 90 | 91 | self.tree = self.Deep_Hedging_Parameter_Widget() 92 | 93 | self.layout.addWidget(self.tree, 94 | 0, 0, self.tree_height, 2) # upper-left 95 | 96 | self.tree.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) 97 | self.tree.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) 98 | self.tree.setMinimumSize(350, 650) 99 | 100 | # Add a run button 101 | self.run_btn = QtGui.QPushButton('Run') 102 | self.layout.addWidget(self.run_btn, 103 | self.tree_height + 1, 104 | 0, 1, 1) # button goes in upper-left 105 | 106 | # Add a pause button 107 | self.pause_btn = QtGui.QPushButton('Pause') 108 | self.layout.addWidget(self.pause_btn, 109 | self.tree_height + 1, 110 | 1, 1, 1) # button goes in upper-left 111 | 112 | # Run the deep hedging algo in a separate thread when the run 113 | # button is clicked. 114 | self.run_btn.clicked.connect(self.RunButton) 115 | 116 | # Pause button. 117 | self.pause_btn.clicked.connect(self.Pause) 118 | 119 | def Deep_Hedging_Parameter_Widget(self): 120 | tree = ParameterTree() 121 | 122 | # Create tree of Parameter objects 123 | self.params = Parameter.create(name='params', type='group', 124 | children=DeepHedgingParams()) 125 | tree.setParameters(self.params, showTop=False) 126 | 127 | return tree 128 | 129 | # Define the event when the "Run" button is clicked. 130 | def RunButton(self): 131 | if self.run_btn.text() == "Stop": 132 | self.Thread_RunDH.stop() 133 | if self.pause_btn.text() == "Continue": 134 | self.pause_btn.setText("Pause") 135 | self.run_btn.setText("Run") 136 | elif self.run_btn.text() == "Run": 137 | self.run_btn.setText("Stop") 138 | 139 | # Set parameters 140 | self.Ktrain = self.params.param("Monte-Carlo Simulation", 141 | 'Sample Size', "Training").value() 142 | self.Ktest_ratio = \ 143 | self.params.param("Monte-Carlo Simulation", 144 | 'Sample Size', 145 | "Testing (as fraction of Training)").value() 146 | self.N = self.params.param("European Call Option", 147 | "Maturity (in days)").value() 148 | self.S0 = self.params.param("European Call Option", "S0").value() 149 | self.strike = self.params.param("European Call Option", 150 | "Strike").value() 151 | self.sigma = self.params.param("European Call Option", 152 | "Implied Volatility").value() 153 | self.risk_free = self.params.param("European Call Option", 154 | "Risk-Free Rate").value() 155 | self.dividend = self.params.param("European Call Option", 156 | "Dividend Yield").value() 157 | 158 | self.loss_param = self.params.param("Deep Hedging Strategy", 159 | 'Loss Function', 160 | "Risk Aversion").value() 161 | self.epsilon = self.params.param("European Call Option", 162 | "Proportional Transaction Cost", 163 | "Cost").value() 164 | self.d = self.params.param("Deep Hedging Strategy", 165 | "Network Structure", 166 | "Number of Hidden Layers").value() 167 | self.m = self.params.param("Deep Hedging Strategy", 168 | "Network Structure", 169 | "Number of Neurons").value() 170 | self.strategy_type = self.params.param("Deep Hedging Strategy", 171 | "Network Structure", 172 | "Network Type").value() 173 | self.lr = self.params.param("Deep Hedging Strategy", 174 | "Learning Parameters", 175 | "Learning Rate").value() 176 | self.batch_size = self.params.param("Deep Hedging Strategy", 177 | "Learning Parameters", 178 | "Mini-Batch Size").value() 179 | self.epochs = self.params.param("Deep Hedging Strategy", 180 | "Learning Parameters", 181 | "Number of Epochs").value() 182 | 183 | self.maturity_date = calculation_date + self.N 184 | self.payoff_func = lambda x: -np.maximum(x - self.strike, 0.0) 185 | 186 | # Simulate the stock price process. 187 | self.S = self.simulate_stock_prices() 188 | 189 | # Assemble the dataset for training and testing. 190 | # Structure of data: 191 | # 1) Trade set: [S] 192 | # 2) Information set: [S] 193 | # 3) payoff (dim = 1) 194 | self.training_dataset = self.assemble_data() 195 | 196 | # Compute Black-Scholes prices for benchmarking. 197 | self.price_BS, self.delta_BS, self.PnL_BS = \ 198 | self.get_Black_Scholes_Prices() 199 | 200 | # Compute the loss value for Black-Scholes PnL 201 | self.loss_BS = Entropy( 202 | self.PnL_BS, 203 | tf.Variable(0.0), 204 | self.loss_param).numpy() 205 | 206 | # Define model and sub-models 207 | self.model = self.Define_DH_model() 208 | self.submodel = self.Define_DH_Delta_Strategy_Model() 209 | 210 | plot_height_split = (self.tree_height + 1) / 2 211 | 212 | # For the presentation... 213 | self.flag_target = False 214 | if self.epsilon > 0: 215 | try: 216 | self.target_color = (0, 155, 0) 217 | self.target_PnL = np.load( 218 | "./data/target_PnL_" + str(self.epsilon) + ".npy") 219 | self.target_loss = Entropy( 220 | self.target_PnL, 221 | tf.Variable(0.0), 222 | self.loss_param).numpy() 223 | self.flag_target = True 224 | except BaseException: 225 | print("No saved file.") 226 | pass 227 | else: 228 | try: 229 | self.fig_loss.removeItem(self.DH_target_loss_textItem) 230 | except BaseException: 231 | pass 232 | 233 | # Add the PnL histogram (PlotWidget) - Black-Scholes vs Deep 234 | # Hedging. 235 | self.fig_PnL = self.PnL_Hist_Widget() 236 | self.layout.addWidget(self.fig_PnL, 0, 3, plot_height_split, 1) 237 | self.fig_PnL.setMinimumWidth(600) 238 | 239 | # Add the Delta line plot (PlotWidget) - Black-Scholes vs Deep 240 | # Hedging. 241 | self.fig_delta = self.Delta_Plot_Widget() 242 | self.layout.addWidget(self.fig_delta, 0, 4, plot_height_split, 1) 243 | self.fig_delta.setMinimumWidth(600) 244 | 245 | # Add the loss plot (PlotWidget) - Black-Scholes vs Deep Hedging. 246 | self.fig_loss = self.Loss_Plot_Widget() 247 | self.layout.addWidget( 248 | self.fig_loss, 249 | plot_height_split, 250 | 3, 251 | plot_height_split + 1, 252 | 2) 253 | self.fig_loss.setMinimumWidth(1200) 254 | 255 | # Run the deep hedging algo in a separate thread. 256 | self.Thread_RunDH.run_deep_hedge_algo( 257 | training_dataset=self.training_dataset, 258 | epochs=self.epochs, 259 | Ktrain=self.Ktrain, 260 | batch_size=self.batch_size, 261 | model=self.model, 262 | submodel=self.submodel, 263 | strategy_type=self.strategy_type, 264 | loss_param=self.loss_param, 265 | learning_rate=self.lr, 266 | xtest=self.xtest, 267 | xtrain=self.xtrain, 268 | initial_price_BS=self.price_BS[0][0], 269 | width=self.width, 270 | I_range=self.I_range, 271 | x_range=self.x_range) 272 | 273 | # Define action when the Pause button is clicked. 274 | 275 | def Pause(self): 276 | if self.pause_btn.text() == "Pause": 277 | self.Thread_RunDH.pause() 278 | self.pause_btn.setText("Continue") 279 | elif self.pause_btn.text() == "Continue": 280 | self.Thread_RunDH.cont() 281 | self.pause_btn.setText("Pause") 282 | 283 | # Define deep hedging model 284 | 285 | def Define_DH_model(self): 286 | # Setup and compile the model 287 | model = Deep_Hedging_Model( 288 | N=self.N, 289 | d=self.d, 290 | m=self.m, 291 | risk_free=self.risk_free, 292 | dt=self.dt, 293 | strategy_type=self.strategy_type, 294 | epsilon=self.epsilon, 295 | use_batch_norm=use_batch_norm, 296 | kernel_initializer=kernel_initializer, 297 | activation_dense=activation_dense, 298 | activation_output=activation_output, 299 | final_period_cost=final_period_cost, 300 | delta_constraint=None) 301 | return model 302 | 303 | def Define_DH_Delta_Strategy_Model(self): 304 | if self.strategy_type == "simple": 305 | # Set up the sub-model that outputs the delta. 306 | submodel = \ 307 | Model(self.model.get_layer("delta_" + 308 | str(self.days_from_today)).input, 309 | self.model.get_layer("delta_" + 310 | str(self.days_from_today)).output) 311 | elif self.strategy_type == "recurrent": 312 | # For "recurrent", the information set is price as well as the past 313 | # delta. 314 | inputs = [Input(1,), Input(1,)] 315 | 316 | intermediate_inputs = Concatenate()(inputs) 317 | 318 | outputs = self.model.get_layer( 319 | "delta_" + str(self.days_from_today))(intermediate_inputs) 320 | 321 | submodel = Model(inputs=inputs, outputs=outputs) 322 | return submodel 323 | 324 | # Draw PnL histogram (PlotWidget) - Black-Scholes vs Deep Hedging. 325 | 326 | def PnL_Hist_Widget(self): 327 | # Initialize the PnL Histogram Widget. 328 | fig_PnL = pg.PlotWidget() 329 | 330 | x_min = np.minimum(self.PnL_BS.min() + self.price_BS[0, 0], -3) 331 | x_max = np.maximum(self.PnL_BS.max() + self.price_BS[0, 0], 3) 332 | 333 | self.x_range = (x_min, x_max) 334 | self.BS_bins, self.bin_edges = np.histogram( 335 | self.PnL_BS + self.price_BS[0, 0], 336 | bins=num_bins, 337 | range=self.x_range) 338 | if self.flag_target: 339 | self.width = (self.bin_edges[1] - self.bin_edges[0]) / 3.0 340 | else: 341 | self.width = (self.bin_edges[1] - self.bin_edges[0]) / 2.0 342 | 343 | self.BS_hist = pg.BarGraphItem(x=self.bin_edges[:-2], 344 | height=self.BS_bins, 345 | width=self.width, 346 | brush='r', 347 | name="Red - Black-Scholes", 348 | antialias=False) 349 | 350 | fig_PnL.setTitle( 351 | "Profit and Loss (PnL) Histogram") 352 | fig_PnL.setLabels( 353 | left="Frequency", 354 | bottom="Profit and Loss (PnL) ") 355 | 356 | # Fix the problem that Y-axes keep moving when transactioni cost is 357 | # greater than zero. 358 | fig_PnL.setYRange(0, self.BS_bins.max() * 1.1) 359 | 360 | if self.flag_target: 361 | fig_PnL.setXRange(self.bin_edges.min(), 2) 362 | else: 363 | fig_PnL.setXRange(self.bin_edges.min(), 2) 364 | 365 | fig_PnL.addItem(self.BS_hist) 366 | 367 | if self.flag_target: 368 | self.DH_target_bins, _ = np.histogram( 369 | self.target_PnL + self.price_BS[0, 0], 370 | bins=num_bins, 371 | range=self.x_range) 372 | self.DH_target_hist = pg.BarGraphItem( 373 | x=self.bin_edges[ 374 | :-2] + 2 * self.width, 375 | height=self.DH_target_bins, 376 | width=self.width, 377 | brush=self.target_color, 378 | name="Green - Deep-Hedging PnL (Target)", 379 | antialias=False) 380 | fig_PnL.addItem(self.DH_target_hist) 381 | PnL_html = ("
" + 382 | "" + 383 | "Black-Scholes PnL (Benchmark)
" + 384 | "" + 385 | "Deep-Hedging PnL (Target)" + 386 | "
").format(str(self.target_color)) + \ 387 | "" + \ 388 | "Deep-Hedging PnL
" 389 | else: 390 | PnL_html = "
" + \ 391 | "" + \ 392 | "Black-Scholes PnL (Benchmark)
" + \ 393 | "" + \ 394 | "Deep-Hedging PnL
" 395 | 396 | fig_PnL_text = pg.TextItem( 397 | html=PnL_html, anchor=( 398 | 0, 0), angle=0, border='w', fill=( 399 | 225, 225, 200)) 400 | 401 | fig_PnL_text.setPos(self.bin_edges.min(), self.BS_bins.max() * 1.05) 402 | fig_PnL.addItem(fig_PnL_text) 403 | 404 | return fig_PnL 405 | 406 | # Draw Delta plot (PlotWidget) - Black-Scholes vs Deep Hedging. 407 | # Assume the PnL_Hist_Widget ran first, so we don't need to run the model 408 | # again. 409 | 410 | def Delta_Plot_Widget(self): 411 | self.tau = (self.N - self.days_from_today) * self.dt 412 | 413 | self.min_S = self.S_test[0][:, self.days_from_today].min() 414 | self.max_S = self.S_test[0][:, self.days_from_today].max() 415 | self.S_range = np.linspace(self.min_S, self.max_S, 51) 416 | 417 | # Attention: Need to transform it to be consistent with the information 418 | # set. 419 | if information_set == "S": 420 | self.I_range = self.S_range # Information set 421 | elif information_set == "log_S": 422 | self.I_range = np.log(self.S_range) 423 | elif information_set == "normalized_log_S": 424 | self.I_range = np.log(self.S_range / self.S0) 425 | 426 | # Compute Black-Scholes delta for S_range. 427 | # Reference: https://en.wikipedia.org/wiki/Greeks_(finance) 428 | self.d1 = (np.log(self.S_range) - np.log(self.strike) + 429 | (self.risk_free - self.dividend + (self.sigma**2) / 2) * 430 | self.tau) / (self.sigma * np.sqrt(self.tau)) 431 | 432 | self.model_delta = norm.cdf( 433 | self.d1) * np.exp(-self.dividend * self.tau) 434 | 435 | fig_delta = pg.PlotWidget() 436 | 437 | self.BS_delta_plot = pg.PlotCurveItem( 438 | pen=pg.mkPen(color="r", width=2.5), name="Black-Scholes") 439 | self.BS_delta_plot.setData(self.S_range, self.model_delta) 440 | 441 | fig_delta.setTitle( 442 | " Hedging Strategy: Delta (at t = 15 days)") 443 | fig_delta.setLabels( 444 | left="Delta", 445 | bottom="Stock Price") 446 | 447 | fig_delta_text = pg.TextItem( 448 | html="
" + 449 | "Black-Scholes Delta (Benchmark)
" + 450 | "" + 451 | "Deep-Hedging Delta
", 452 | anchor=( 453 | 0, 454 | 0), 455 | angle=0, 456 | border='w', 457 | fill=( 458 | 255, 459 | 255, 460 | 200)) 461 | fig_delta_text.setPos(self.S_range.min(), self.model_delta.max()) 462 | 463 | fig_delta.addItem(self.BS_delta_plot) 464 | fig_delta.addItem(fig_delta_text) 465 | 466 | return fig_delta 467 | 468 | # Draw loss plot (PlotWidget) - Black-Scholes vs Deep Hedging. 469 | 470 | def Loss_Plot_Widget(self): 471 | fig_loss = pg.PlotWidget() 472 | 473 | self.DH_loss_plot = pg.PlotDataItem( 474 | pen=pg.mkPen( 475 | color="b", width=6), symbolBrush=( 476 | 0, 0, 255), symbolPen='y', symbol='+', symbolSize=8) 477 | fig_loss.addItem(self.DH_loss_plot) 478 | 479 | # Add a line for the Black-Scholes price. 480 | fig_loss.addLine(y=self.loss_BS, pen=pg.mkPen(color="r", width=1.5)) 481 | 482 | self.BS_loss_html = ("
" + 483 | "" + 484 | "Black-Scholes Loss (Benchmark)
" + 485 | "{:0.3f}
").format( 487 | self.loss_BS) 488 | self.BS_loss_textItem = pg.TextItem( 489 | html=self.BS_loss_html, anchor=( 490 | 1, 1), angle=0, border='w', fill=( 491 | 255, 255, 200)) 492 | 493 | if self.flag_target: 494 | self.DH_target_loss_html = ("
" + 495 | "Deep-Hedging Loss " + 498 | "(Target) " + 499 | "
{:0.3f}" 502 | "
").format(self.target_loss) 503 | self.DH_target_loss_textItem = pg.TextItem( 504 | html=self.DH_target_loss_html, anchor=( 505 | 1, 1), angle=0, border='w', fill=( 506 | 255, 255, 200)) 507 | 508 | # Label the graph. 509 | fig_loss.setTitle( 510 | " Loss Function (Option Price) ") 511 | fig_loss.setLabels( 512 | left="Loss Value", 513 | bottom="Loss Function (Option Price) " + 514 | "- Number of Epochs") 515 | 516 | # Set appropriate xRange and yRange. 517 | fig_loss.setRange(xRange=(0, self.epochs)) 518 | 519 | # For the presentation... 520 | if self.flag_target: 521 | fig_loss.addLine( 522 | y=self.target_loss, pen=pg.mkPen( 523 | color=self.target_color, width=1.5)) 524 | 525 | return fig_loss 526 | 527 | # Update Plots - Black-Scholes vs Deep Hedging. 528 | def Update_Plots_Widget( 529 | self, 530 | PnL_DH=None, 531 | DH_delta=None, 532 | DH_bins=None, 533 | loss=None, 534 | num_epoch=None, 535 | num_batch=None, 536 | flag_last_batch_in_epoch=None): 537 | 538 | self.Update_PnL_Histogram( 539 | PnL_DH, 540 | DH_delta, 541 | DH_bins, 542 | loss, 543 | num_epoch, 544 | num_batch, 545 | flag_last_batch_in_epoch) 546 | 547 | self.Update_Delta_Plot( 548 | PnL_DH, 549 | DH_delta, 550 | DH_bins, 551 | loss, 552 | num_epoch, 553 | num_batch, 554 | flag_last_batch_in_epoch) 555 | 556 | self.Update_Loss_Plot( 557 | PnL_DH, 558 | DH_delta, 559 | DH_bins, 560 | loss, 561 | num_epoch, 562 | num_batch, 563 | flag_last_batch_in_epoch) 564 | 565 | self.Thread_RunDH.Figure_IsUpdated = True 566 | 567 | if num_epoch == self.epochs and \ 568 | flag_last_batch_in_epoch is True and \ 569 | self.epsilon > 0.0: 570 | np.save("../data/target_PnL_" + str(self.epsilon), PnL_DH) 571 | 572 | def Update_Loss_Plot( 573 | self, 574 | PnL_DH=None, 575 | DH_delta=None, 576 | DH_bins=None, 577 | loss=None, 578 | num_epoch=None, 579 | num_batch=None, 580 | flag_last_batch_in_epoch=None): 581 | 582 | DH_shift = 0.6 583 | 584 | # Get the latest viewRange 585 | yMin_View, yMax_View = self.fig_loss.viewRange()[1] 586 | 587 | # Update text position for Black-Scholes 588 | self.BS_loss_textItem.setPos( 589 | self.epochs * 0.8, self.loss_BS + 590 | (yMax_View - self.loss_BS) * 0.005) 591 | 592 | if self.flag_target: 593 | self.DH_target_loss_textItem.setPos( 594 | self.epochs * 0.6, self.target_loss + 595 | (yMax_View - self.target_loss) * 0.005) 596 | 597 | # Update text for Deep-Hedging. 598 | DH_loss_text_title = "
Deep-Hedging Loss
" 600 | DH_loss_text_step = " Epoch: {} " + \ 601 | "Batch: {}
" 602 | DH_loss_text_loss = "{:0.3f}
" 604 | 605 | DH_loss_text_str = ( 606 | DH_loss_text_title + 607 | DH_loss_text_step + 608 | DH_loss_text_loss).format( 609 | int(num_epoch), 610 | int(num_batch), 611 | loss) 612 | 613 | if num_epoch == 1 and num_batch == 1: 614 | self.fig_loss.addItem(self.BS_loss_textItem) 615 | 616 | if self.flag_target: 617 | self.fig_loss.addItem(self.DH_target_loss_textItem) 618 | 619 | # Setup the textbox for the deep-hedging loss. 620 | self.DH_loss_textItem = pg.TextItem( 621 | html=DH_loss_text_str, anchor=( 622 | 0, 0), angle=0, border='w', fill=( 623 | 255, 255, 200)) 624 | self.DH_loss_textItem.setPos((num_epoch - 1) + DH_shift, loss) 625 | self.fig_loss.addItem(self.DH_loss_textItem) 626 | 627 | self.fig_loss.enableAutoRange() 628 | 629 | # Mandatory pause to explain the demo. Remember to modify the 630 | # algo thread as well if one wants to remove the feature. 631 | # This part takes care the pause button. 632 | self.Pause() 633 | else: 634 | self.DH_loss_textItem.setHtml(DH_loss_text_str) 635 | if flag_last_batch_in_epoch: 636 | self.DH_loss_textItem.setPos(num_epoch + DH_shift, loss) 637 | if num_epoch == 1: 638 | # Establish the data for the out-of-sample loss at the end 639 | # of the first epoch. 640 | self.oos_loss_record = np.array([num_epoch, loss], ndmin=2) 641 | else: 642 | # Keep adding data at the end of each epoch. 643 | self.oos_loss_record = np.vstack( 644 | [self.oos_loss_record, np.array([num_epoch, loss])]) 645 | 646 | self.DH_loss_plot.setData(self.oos_loss_record) 647 | 648 | # Move the Black-Scholes textbox to the left to avoid collision of the 649 | # deep-hedging textbox. 650 | if num_epoch > self.epochs * 0.5: 651 | if self.epsilon == 0: 652 | anchor = (0, 0) 653 | elif self.epsilon > 0: 654 | anchor = (0, 1) 655 | 656 | self.fig_loss.removeItem(self.BS_loss_textItem) 657 | self.BS_loss_textItem = pg.TextItem( 658 | html=self.BS_loss_html, 659 | anchor=anchor, 660 | angle=0, 661 | border='w', 662 | fill=( 663 | 255, 664 | 255, 665 | 200)) 666 | self.BS_loss_textItem.setPos( 667 | 0, self.loss_BS + (yMax_View - self.loss_BS) * 0.005) 668 | self.fig_loss.addItem(self.BS_loss_textItem) 669 | 670 | def Update_PnL_Histogram( 671 | self, 672 | PnL_DH=None, 673 | DH_delta=None, 674 | DH_bins=None, 675 | loss=None, 676 | num_epoch=None, 677 | num_batch=None, 678 | flag_last_batch_in_epoch=None): 679 | if num_epoch == 1 and num_batch == 1: 680 | # Update PnL Histogram 681 | self.DH_hist = pg.BarGraphItem(x=self.bin_edges[:-2] + self.width, 682 | height=DH_bins, 683 | width=self.width, 684 | brush='b', 685 | name="Blue - Deep Hedging", 686 | antialias=False) 687 | self.fig_PnL.addItem(self.DH_hist) 688 | else: 689 | # Update PnL Histograms 690 | self.DH_hist.setOpts(height=DH_bins) 691 | 692 | def Update_Delta_Plot( 693 | self, 694 | PnL_DH=None, 695 | DH_delta=None, 696 | DH_bins=None, 697 | loss=None, 698 | num_epoch=None, 699 | num_batch=None, 700 | flag_last_batch_in_epoch=None): 701 | if num_epoch == 1 and num_batch == 1: 702 | # Update the Delta plot 703 | self.DH_delta_plot = pg.PlotDataItem( 704 | symbolBrush=( 705 | 0, 706 | 0, 707 | 255), 708 | symbolPen='b', 709 | symbol='+', 710 | symbolSize=10, 711 | name="Deep Hedging") 712 | self.DH_delta_plot.setData(self.S_range, DH_delta) 713 | self.fig_delta.addItem(self.DH_delta_plot) 714 | else: 715 | # Update the Delta plot 716 | self.DH_delta_plot.setData(self.S_range, DH_delta) 717 | 718 | def simulate_stock_prices(self): 719 | # Total obs = Training + Testing 720 | self.nobs = int(self.Ktrain * (1 + self.Ktest_ratio)) 721 | 722 | # Length of one time-step (as fraction of a year). 723 | self.dt = day_count.yearFraction( 724 | calculation_date, calculation_date + 1) 725 | self.maturity = self.N * self.dt # Maturities (in the unit of a year) 726 | 727 | self.stochastic_process = BlackScholesProcess( 728 | s0=self.S0, 729 | sigma=self.sigma, 730 | risk_free=self.risk_free, 731 | dividend=self.dividend, 732 | day_count=day_count) 733 | 734 | print("\nRun Monte-Carlo Simulations for the Stock Price Process.\n") 735 | return self.stochastic_process.gen_path( 736 | self.maturity, self.N, self.nobs) 737 | print("\n") 738 | 739 | def assemble_data(self): 740 | self.payoff_T = self.payoff_func( 741 | self.S[:, -1]) # Payoff of the call option 742 | 743 | self.trade_set = np.stack((self.S), axis=1) # Trading set 744 | 745 | if information_set == "S": 746 | self.infoset = np.stack((self.S), axis=1) # Information set 747 | elif information_set == "log_S": 748 | self.infoset = np.stack((np.log(self.S)), axis=1) 749 | elif information_set == "normalized_log_S": 750 | self.infoset = np.stack((np.log(self.S / self.S0)), axis=1) 751 | 752 | # Structure of xtrain: 753 | # 1) Trade set: [S] 754 | # 2) Information set: [S] 755 | # 3) payoff (dim = 1) 756 | self.x_all = [] 757 | for i in range(self.N + 1): 758 | self.x_all += [self.trade_set[i, :, None]] 759 | if i != self.N: 760 | self.x_all += [self.infoset[i, :, None]] 761 | self.x_all += [self.payoff_T[:, None]] 762 | 763 | # Split the entire sample into a training sample and a testing sample. 764 | self.test_size = int(self.Ktrain * self.Ktest_ratio) 765 | [self.xtrain, self.xtest] = train_test_split( 766 | self.x_all, test_size=self.test_size) 767 | [self.S_train, self.S_test] = train_test_split( 768 | [self.S], test_size=self.test_size) 769 | [self.option_payoff_train, self.option_payoff_test] = \ 770 | train_test_split([self.x_all[-1]], test_size=self.test_size) 771 | 772 | # Convert the training sample into tf.Data format (same as xtrain). 773 | training_dataset = tf.data.Dataset.from_tensor_slices( 774 | tuple(self.xtrain)) 775 | return training_dataset.cache() 776 | 777 | def get_Black_Scholes_Prices(self): 778 | # Obtain Black-Scholes price, delta, and PnL 779 | call = EuropeanCall() 780 | price_BS = call.get_BS_price( 781 | S=self.S_test[0], 782 | sigma=self.sigma, 783 | risk_free=self.risk_free, 784 | dividend=self.dividend, 785 | K=self.strike, 786 | exercise_date=self.maturity_date, 787 | calculation_date=calculation_date, 788 | day_count=day_count, 789 | dt=self.dt) 790 | delta_BS = call.get_BS_delta( 791 | S=self.S_test[0], 792 | sigma=self.sigma, 793 | risk_free=self.risk_free, 794 | dividend=self.dividend, 795 | K=self.strike, 796 | exercise_date=self.maturity_date, 797 | calculation_date=calculation_date, 798 | day_count=day_count, 799 | dt=self.dt) 800 | PnL_BS = call.get_BS_PnL(S=self.S_test[0], 801 | payoff=self.payoff_func(self.S_test[0][:, 802 | -1]), 803 | delta=delta_BS, 804 | dt=self.dt, 805 | risk_free=self.risk_free, 806 | final_period_cost=final_period_cost, 807 | epsilon=self.epsilon) 808 | return price_BS, delta_BS, PnL_BS 809 | -------------------------------------------------------------------------------- /presentation/readme.txt: -------------------------------------------------------------------------------- 1 | Instruction for Running on the Grid: 2 | 3 | Run: 4 | 5 | bsub -Is -q "python" numactl --cpunodebind=0 zsh python3 6 | 7 | Then, within Python: 8 | 9 | exec(open("main.py").read()) 10 | -------------------------------------------------------------------------------- /pyqt5/default_params.py: -------------------------------------------------------------------------------- 1 | # Define the initial parameters for the deep hedging demo 2 | def DeepHedgingParams(): 3 | params = [ 4 | {'name': 'European Call Option', 'type': 'group', 'children': [ 5 | {'name': 'S0', 'type': 'int', 'value': 100.0}, 6 | {'name': 'Strike', 'type': 'float', 'value': 100.0}, 7 | {'name': 'Implied Volatility', 'type': 'float', 'value': 0.2}, 8 | {'name': 'Risk-Free Rate', 'type': 'float', 'value': 0.0}, 9 | {'name': 'Dividend Yield', 'type': 'float', 'value': 0.0}, 10 | {'name': 'Maturity (in days)', 'type': 'int', 'value': 30}, 11 | {'name': 'Proportional Transaction Cost', 'type': 'group', 'children': [ 12 | {'name': 'Cost', 'type': 'float', 'value': 0.0}, 13 | ]}, 14 | ]}, 15 | {'name': 'Monte-Carlo Simulation', 'type': 'group', 'children': [ 16 | {'name': 'Sample Size', 'type': 'group', 'children': [ 17 | {'name': 'Training', 'type': 'int', 'value': 1*(10**5)}, 18 | {'name': 'Testing (as fraction of Training)', 'type': 'float', 'value': 0.2} 19 | ]}, 20 | ]}, 21 | {'name': 'Deep Hedging Strategy', 'type': 'group', 'children': [ 22 | {'name': 'Loss Function', 'type': 'group', 'children': [ 23 | {'name': 'Loss Type', 'type': 'list', 'values': {"Entropy": "Entropy", "CVaR": "CVaR"}, "default": "Entropy"}, 24 | {'name': 'Risk Aversion', 'type': 'float', 'value': 1.0} 25 | ]}, 26 | {'name': 'Network Structure', 'type': 'group', 'children': [ 27 | {'name': 'Network Type', 'type': 'list', 'values': {"Simple": "simple", "Recurrent": "recurrent"}, "default": "simple"}, 28 | {'name': 'Number of Hidden Layers', 'type': 'int', 'value': 1}, 29 | {'name': 'Number of Neurons', 'type': 'int', 'value': 15}, 30 | ]}, 31 | {'name': 'Learning Parameters', 'type': 'group', 'children': [ 32 | {'name': 'Learning Rate', 'type': 'float', 'value': 5e-3}, 33 | {'name': 'Mini-Batch Size', 'type': 'int', 'value': 256}, 34 | {'name': 'Number of Epochs', 'type': 'int', 'value': 50}, 35 | ]}, 36 | ]}, 37 | ] 38 | return params 39 | -------------------------------------------------------------------------------- /pyqt5/dh_worker.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | # Add the parent directory to the search paths to import the libraries. 5 | dir_path = os.path.dirname(os.path.realpath(__file__)) 6 | sys.path.insert(0, "/".join([dir_path, ".."])) 7 | 8 | import time 9 | 10 | import numpy as np 11 | 12 | import tensorflow as tf 13 | from tensorflow.keras.optimizers import Adam 14 | 15 | from pyqtgraph.Qt import QtCore 16 | 17 | from loss_metrics import Entropy 18 | 19 | 20 | # Reducing learning rate 21 | reduce_lr_param = {"patience": 2, "min_delta": 1e-3, "factor": 0.5} 22 | 23 | # Number of bins to plot for the PnL histograms. 24 | num_bins = 30 25 | 26 | 27 | # Put the deep-hedging algo in a separate thread than the plotting thread to 28 | # improve performance. 29 | class DHworker(QtCore.QThread): 30 | DH_outputs = QtCore.pyqtSignal(np.ndarray, 31 | np.ndarray, 32 | np.ndarray, 33 | np.float32, 34 | float, 35 | float, 36 | bool) 37 | 38 | def __init__(self): 39 | QtCore.QThread.__init__(self) 40 | 41 | def __del__(self): 42 | self.wait() 43 | 44 | def run_deep_hedge_algo(self, 45 | training_dataset=None, 46 | epochs=None, 47 | Ktrain=None, 48 | batch_size=None, 49 | model=None, 50 | submodel=None, 51 | strategy_type=None, 52 | loss_param=None, 53 | learning_rate=None, 54 | xtest=None, 55 | xtrain=None, 56 | initial_price_BS=None, 57 | width=None, 58 | I_range=None, 59 | x_range=None): 60 | self.training_dataset = training_dataset 61 | self.Ktrain = Ktrain 62 | self.batch_size = batch_size 63 | self.model = model 64 | self.submodel = submodel 65 | self.loss_param = loss_param 66 | self.initial_price_BS = initial_price_BS 67 | self.width = width 68 | self.epochs = epochs 69 | self.xtest = xtest 70 | self.xtrain = xtrain 71 | self.I_range = I_range 72 | self.x_range = x_range 73 | self.strategy_type = strategy_type 74 | self.learning_rate = learning_rate 75 | 76 | self.start() 77 | 78 | def pause(self): 79 | self._pause = True 80 | 81 | def cont(self): 82 | self._pause = False 83 | 84 | def stop(self): 85 | self._exit = True 86 | self.exit() 87 | 88 | def is_running(self): 89 | if self._pause or self._exit: 90 | return False 91 | else: 92 | return True 93 | 94 | def Reduce_Learning_Rate(self, num_epoch, loss): 95 | # Extract in-sample loss from the previous epoch. Comparison starts in 96 | # epoch 2 and the index for epoch 1 is 0 -> -2 97 | min_loss = self.loss_record[:, 1].min() 98 | if min_loss - loss < reduce_lr_param["min_delta"]: 99 | self.reduce_lr_counter += 1 100 | 101 | if self.reduce_lr_counter > reduce_lr_param["patience"]: 102 | self.learning_rate = self.learning_rate * reduce_lr_param["factor"] 103 | self.optimizer.learning_rate = self.learning_rate 104 | print( 105 | "The learning rate is reduced to {}.".format( 106 | self.learning_rate)) 107 | self.reduce_lr_counter = 0 108 | 109 | def run(self): 110 | # Initialize pause and stop buttons. 111 | self._exit = False 112 | self._pause = False 113 | 114 | # Variables to control skipped frames. If the DH algo output much 115 | # faster than the graphic output, the plots can be jammed. 116 | self.Figure_IsUpdated = True 117 | 118 | self.reduce_lr_counter = 0 119 | self.early_stopping_counter = 0 120 | 121 | certainty_equiv = tf.Variable(0.0, name="certainty_equiv") 122 | 123 | # Accelerator Function. 124 | model_func = tf.function(self.model) 125 | submodel_func = tf.function(self.submodel) 126 | 127 | self.optimizer = Adam(learning_rate=self.learning_rate) 128 | 129 | oos_loss = None 130 | PnL_DH = None 131 | DH_delta = None 132 | DH_bins = None 133 | num_batch = None 134 | 135 | num_epoch = 0 136 | while num_epoch <= self.epochs: 137 | # Exit event loop if the exit flag is set to True. 138 | if self._exit: 139 | mini_batch_iter = None 140 | self._exit = False 141 | self._pause = False 142 | break 143 | 144 | if not self._pause: 145 | try: 146 | mini_batch = mini_batch_iter.next() 147 | except BaseException: 148 | # Reduce learning rates and Early Stopping are based on 149 | # in-sample losses calculated once per epoch. 150 | in_sample_wealth = model_func(self.xtrain) 151 | in_sample_loss = Entropy( 152 | in_sample_wealth, certainty_equiv, self.loss_param) 153 | 154 | if num_epoch >= 1: 155 | print(("The deep-hedging price is {:0.4f} after " + 156 | "{} epoch.").format(oos_loss, num_epoch)) 157 | 158 | # Programming hack. The deep-hedging algo computes 159 | # faster than the computer can plot, so there could 160 | # be missing frames, i.e. there is no guarantee 161 | # that every batch is plotted. Here, I force a 162 | # signal to be emitted at the end of an epoch. 163 | time.sleep(1) 164 | 165 | self.DH_outputs.emit( 166 | PnL_DH, 167 | DH_delta, 168 | DH_bins, 169 | oos_loss.numpy().squeeze(), 170 | num_epoch, 171 | num_batch, 172 | True) 173 | 174 | # This is needed to prevent the output signals from 175 | # emitting faster than the system can plot a graph. 176 | # 177 | # The performance is much better than emitting at fixed 178 | # time intervals. 179 | self.Figure_IsUpdated = False 180 | 181 | if num_epoch == 1: 182 | self.loss_record = np.array( 183 | [num_epoch, in_sample_loss], ndmin=2) 184 | elif num_epoch > 1: 185 | self.Reduce_Learning_Rate(num_epoch, in_sample_loss) 186 | self.loss_record = np.vstack( 187 | [self.loss_record, 188 | np.array([num_epoch, in_sample_loss])]) 189 | 190 | mini_batch_iter = self.training_dataset.shuffle( 191 | self.Ktrain).batch(self.batch_size).__iter__() 192 | mini_batch = mini_batch_iter.next() 193 | 194 | num_batch = 0 195 | num_epoch += 1 196 | 197 | num_batch += 1 198 | 199 | # Record gradient 200 | with tf.GradientTape() as tape: 201 | wealth = model_func(mini_batch) 202 | loss = Entropy(wealth, certainty_equiv, self.loss_param) 203 | 204 | oos_wealth = model_func(self.xtest) 205 | PnL_DH = oos_wealth.numpy().squeeze() # Out-of-sample 206 | 207 | submodel_delta_range = np.expand_dims(self.I_range, axis=1) 208 | if self.strategy_type == "simple": 209 | submodel_inputs = submodel_delta_range 210 | elif self.strategy_type == "recurrent": 211 | # Assume previous delta is ATM. 212 | submodel_inputs = [ 213 | submodel_delta_range, 214 | np.ones_like(submodel_delta_range) * 0.5] 215 | DH_delta = submodel_func(submodel_inputs).numpy().squeeze() 216 | DH_bins, _ = np.histogram( 217 | PnL_DH + self.initial_price_BS, 218 | bins=num_bins, 219 | range=self.x_range) 220 | 221 | # Forward and backward passes 222 | grads = tape.gradient(loss, self.model.trainable_weights) 223 | self.optimizer.apply_gradients( 224 | zip(grads, self.model.trainable_weights)) 225 | 226 | # Compute Out-of-Sample Loss 227 | oos_loss = Entropy( 228 | oos_wealth, certainty_equiv, self.loss_param) 229 | 230 | if self.Figure_IsUpdated: 231 | self.DH_outputs.emit( 232 | PnL_DH, 233 | DH_delta, 234 | DH_bins, 235 | oos_loss.numpy().squeeze(), 236 | num_epoch, 237 | num_batch, 238 | False) 239 | 240 | # This is needed to prevent the output signals from emitting 241 | # faster than the system can plot a graph. 242 | # 243 | # The performance is much better than emitting at fixed time 244 | # intervals. 245 | self.Figure_IsUpdated = False 246 | 247 | # Mandatory pause for the first iteration to explain demo. 248 | if num_epoch == 1 and num_batch == 1: 249 | self.pause() 250 | else: 251 | time.sleep(1) 252 | -------------------------------------------------------------------------------- /pyqt5/main.py: -------------------------------------------------------------------------------- 1 | # Author: Yu-Man Tam 2 | # Email: yuman.tam@gmail.com 3 | # 4 | # Last updated: 5/22/2020 5 | # 6 | # Reference: Deep Hedging (2019, Quantitative Finance) by Buehler et al. 7 | # https://www.tandfonline.com/doi/abs/10.1080/14697688.2019.1571683 8 | 9 | import sys 10 | import os 11 | 12 | import tensorflow as tf 13 | 14 | # Add the parent directory to the search paths to import the libraries. 15 | dir_path = os.path.dirname(os.path.realpath(__file__)) 16 | sys.path.insert(0, "/".join([dir_path, ".."])) 17 | 18 | from pyqtgraph.Qt import QtWidgets 19 | from main_window import MainWindow 20 | 21 | # Tensorflow settings 22 | tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR) 23 | tf.autograph.set_verbosity(0) 24 | 25 | if __name__ == '__main__': 26 | app = QtWidgets.QApplication(sys.argv) 27 | main = MainWindow() 28 | main.show() 29 | app.exec_() 30 | -------------------------------------------------------------------------------- /pyqt5/main_window.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | # Add the parent directory to the search paths to import the libraries. 5 | dir_path = os.path.dirname(os.path.realpath(__file__)) 6 | sys.path.insert(0, "/".join([dir_path, ".."])) 7 | 8 | import QuantLib as ql 9 | import numpy as np 10 | import tensorflow as tf 11 | import pyqtgraph as pg 12 | 13 | from tensorflow.keras.models import Model 14 | from tensorflow.keras.layers import Input, Concatenate 15 | from pyqtgraph.Qt import QtWidgets, QtGui, QtCore 16 | from pyqtgraph.parametertree import ParameterTree, Parameter 17 | from scipy.stats import norm 18 | 19 | from dh_worker import DHworker 20 | from default_params import DeepHedgingParams 21 | from loss_metrics import Entropy 22 | from deep_hedging import Deep_Hedging_Model 23 | from stochastic_processes import BlackScholesProcess 24 | from instruments import EuropeanCall 25 | from utilities import train_test_split 26 | 27 | # Specify the day (from today) for the delta plot. 28 | delta_plot_day = 15 29 | 30 | # European call option (short). 31 | calculation_date = ql.Date.todaysDate() 32 | 33 | # Day convention. 34 | day_count = ql.Actual365Fixed() # Actual/Actual (ISDA) 35 | 36 | # Information set (in string) 37 | # Choose from: S, log_S, normalized_log_S (by S0) 38 | information_set = "normalized_log_S" 39 | 40 | # Loss function 41 | # loss_type = "CVaR" (Expected Shortfall) -> loss_param = alpha 42 | # loss_type = "Entropy" -> loss_param = lambda 43 | loss_type = "Entropy" 44 | 45 | # Other NN parameters 46 | use_batch_norm = False 47 | kernel_initializer = "he_uniform" 48 | 49 | activation_dense = "leaky_relu" 50 | activation_output = "sigmoid" 51 | final_period_cost = False 52 | 53 | # Reducing learning rate 54 | reduce_lr_param = {"patience": 2, "min_delta": 1e-3, "factor": 0.5} 55 | 56 | # Number of bins to plot for the PnL histograms. 57 | num_bins = 30 58 | 59 | 60 | class MainWindow(QtWidgets.QMainWindow): 61 | def __init__(self): 62 | # Inheritance from the QMainWindow class 63 | # Reference: https://doc.qt.io/qt-5/qmainwindow.html 64 | super().__init__() 65 | self.days_from_today = delta_plot_day 66 | self.Thread_RunDH = DHworker() 67 | 68 | # The order of code is important here: Make sure the 69 | # emitted signals are connected before actually running 70 | # the Worker. 71 | self.Thread_RunDH.DH_outputs["PyQt_PyObject", 72 | "PyQt_PyObject", 73 | "PyQt_PyObject", 74 | "PyQt_PyObject", 75 | "double", 76 | "double", 77 | "bool"].connect(self.Update_Plots_Widget) 78 | 79 | # Define a top-level widget to hold everything 80 | self.w = QtGui.QWidget() 81 | 82 | # Create a grid layout to manage the widgets size and position 83 | self.layout = QtGui.QGridLayout() 84 | self.w.setLayout(self.layout) 85 | 86 | self.setCentralWidget(self.w) 87 | 88 | # Add the parameter menu. 89 | self.tree_height = 5 # Must be Odd number. 90 | 91 | self.tree = self.Deep_Hedging_Parameter_Widget() 92 | 93 | self.layout.addWidget(self.tree, 94 | 0, 0, self.tree_height, 2) # upper-left 95 | 96 | self.tree.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) 97 | self.tree.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff) 98 | self.tree.setMinimumSize(350, 650) 99 | 100 | # Add a run button 101 | self.run_btn = QtGui.QPushButton('Run') 102 | self.layout.addWidget(self.run_btn, 103 | self.tree_height + 1, 104 | 0, 1, 1) # button goes in upper-left 105 | 106 | # Add a pause button 107 | self.pause_btn = QtGui.QPushButton('Pause') 108 | self.layout.addWidget(self.pause_btn, 109 | self.tree_height + 1, 110 | 1, 1, 1) # button goes in upper-left 111 | 112 | # Run the deep hedging algo in a separate thread when the run 113 | # button is clicked. 114 | self.run_btn.clicked.connect(self.RunButton) 115 | 116 | # Pause button. 117 | self.pause_btn.clicked.connect(self.Pause) 118 | 119 | def Deep_Hedging_Parameter_Widget(self): 120 | tree = ParameterTree() 121 | 122 | # Create tree of Parameter objects 123 | self.params = Parameter.create(name='params', type='group', 124 | children=DeepHedgingParams()) 125 | tree.setParameters(self.params, showTop=False) 126 | 127 | return tree 128 | 129 | # Define the event when the "Run" button is clicked. 130 | def RunButton(self): 131 | if self.run_btn.text() == "Stop": 132 | self.Thread_RunDH.stop() 133 | if self.pause_btn.text() == "Continue": 134 | self.pause_btn.setText("Pause") 135 | self.run_btn.setText("Run") 136 | elif self.run_btn.text() == "Run": 137 | self.run_btn.setText("Stop") 138 | 139 | # Set parameters 140 | self.Ktrain = self.params.param("Monte-Carlo Simulation", 141 | 'Sample Size', "Training").value() 142 | self.Ktest_ratio = \ 143 | self.params.param("Monte-Carlo Simulation", 144 | 'Sample Size', 145 | "Testing (as fraction of Training)").value() 146 | self.N = self.params.param("European Call Option", 147 | "Maturity (in days)").value() 148 | self.S0 = self.params.param("European Call Option", "S0").value() 149 | self.strike = self.params.param("European Call Option", 150 | "Strike").value() 151 | self.sigma = self.params.param("European Call Option", 152 | "Implied Volatility").value() 153 | self.risk_free = self.params.param("European Call Option", 154 | "Risk-Free Rate").value() 155 | self.dividend = self.params.param("European Call Option", 156 | "Dividend Yield").value() 157 | 158 | self.loss_param = self.params.param("Deep Hedging Strategy", 159 | 'Loss Function', 160 | "Risk Aversion").value() 161 | self.epsilon = self.params.param("European Call Option", 162 | "Proportional Transaction Cost", 163 | "Cost").value() 164 | self.d = self.params.param("Deep Hedging Strategy", 165 | "Network Structure", 166 | "Number of Hidden Layers").value() 167 | self.m = self.params.param("Deep Hedging Strategy", 168 | "Network Structure", 169 | "Number of Neurons").value() 170 | self.strategy_type = self.params.param("Deep Hedging Strategy", 171 | "Network Structure", 172 | "Network Type").value() 173 | self.lr = self.params.param("Deep Hedging Strategy", 174 | "Learning Parameters", 175 | "Learning Rate").value() 176 | self.batch_size = self.params.param("Deep Hedging Strategy", 177 | "Learning Parameters", 178 | "Mini-Batch Size").value() 179 | self.epochs = self.params.param("Deep Hedging Strategy", 180 | "Learning Parameters", 181 | "Number of Epochs").value() 182 | 183 | self.maturity_date = calculation_date + self.N 184 | self.payoff_func = lambda x: -np.maximum(x - self.strike, 0.0) 185 | 186 | # Simulate the stock price process. 187 | self.S = self.simulate_stock_prices() 188 | 189 | # Assemble the dataset for training and testing. 190 | # Structure of data: 191 | # 1) Trade set: [S] 192 | # 2) Information set: [S] 193 | # 3) payoff (dim = 1) 194 | self.training_dataset = self.assemble_data() 195 | 196 | # Compute Black-Scholes prices for benchmarking. 197 | self.price_BS, self.delta_BS, self.PnL_BS = \ 198 | self.get_Black_Scholes_Prices() 199 | 200 | # Compute the loss value for Black-Scholes PnL 201 | self.loss_BS = Entropy( 202 | self.PnL_BS, 203 | tf.Variable(0.0), 204 | self.loss_param).numpy() 205 | 206 | # Define model and sub-models 207 | self.model = self.Define_DH_model() 208 | self.submodel = self.Define_DH_Delta_Strategy_Model() 209 | 210 | plot_height_split = (self.tree_height + 1) / 2 211 | 212 | # For the presentation... 213 | self.flag_target = False 214 | if self.epsilon > 0: 215 | try: 216 | self.target_color = (0, 155, 0) 217 | self.target_PnL = np.load( 218 | "../data/target_PnL_" + str(self.epsilon) + ".npy") 219 | self.target_loss = Entropy( 220 | self.target_PnL, 221 | tf.Variable(0.0), 222 | self.loss_param).numpy() 223 | self.flag_target = True 224 | except BaseException: 225 | print("No saved file.") 226 | pass 227 | else: 228 | try: 229 | self.fig_loss.removeItem(self.DH_target_loss_textItem) 230 | except BaseException: 231 | pass 232 | 233 | # Add the PnL histogram (PlotWidget) - Black-Scholes vs Deep 234 | # Hedging. 235 | self.fig_PnL = self.PnL_Hist_Widget() 236 | self.layout.addWidget(self.fig_PnL, 0, 3, plot_height_split, 1) 237 | self.fig_PnL.setMinimumWidth(600) 238 | 239 | # Add the Delta line plot (PlotWidget) - Black-Scholes vs Deep 240 | # Hedging. 241 | self.fig_delta = self.Delta_Plot_Widget() 242 | self.layout.addWidget(self.fig_delta, 0, 4, plot_height_split, 1) 243 | self.fig_delta.setMinimumWidth(600) 244 | 245 | # Add the loss plot (PlotWidget) - Black-Scholes vs Deep Hedging. 246 | self.fig_loss = self.Loss_Plot_Widget() 247 | self.layout.addWidget( 248 | self.fig_loss, 249 | plot_height_split, 250 | 3, 251 | plot_height_split + 1, 252 | 2) 253 | self.fig_loss.setMinimumWidth(1200) 254 | 255 | # Run the deep hedging algo in a separate thread. 256 | self.Thread_RunDH.run_deep_hedge_algo( 257 | training_dataset=self.training_dataset, 258 | epochs=self.epochs, 259 | Ktrain=self.Ktrain, 260 | batch_size=self.batch_size, 261 | model=self.model, 262 | submodel=self.submodel, 263 | strategy_type=self.strategy_type, 264 | loss_param=self.loss_param, 265 | learning_rate=self.lr, 266 | xtest=self.xtest, 267 | xtrain=self.xtrain, 268 | initial_price_BS=self.price_BS[0][0], 269 | width=self.width, 270 | I_range=self.I_range, 271 | x_range=self.x_range) 272 | 273 | # Define action when the Pause button is clicked. 274 | 275 | def Pause(self): 276 | if self.pause_btn.text() == "Pause": 277 | self.Thread_RunDH.pause() 278 | self.pause_btn.setText("Continue") 279 | elif self.pause_btn.text() == "Continue": 280 | self.Thread_RunDH.cont() 281 | self.pause_btn.setText("Pause") 282 | 283 | # Define deep hedging model 284 | 285 | def Define_DH_model(self): 286 | # Setup and compile the model 287 | model = Deep_Hedging_Model( 288 | N=self.N, 289 | d=self.d, 290 | m=self.m, 291 | risk_free=self.risk_free, 292 | dt=self.dt, 293 | strategy_type=self.strategy_type, 294 | epsilon=self.epsilon, 295 | use_batch_norm=use_batch_norm, 296 | kernel_initializer=kernel_initializer, 297 | activation_dense=activation_dense, 298 | activation_output=activation_output, 299 | final_period_cost=final_period_cost, 300 | delta_constraint=None) 301 | return model 302 | 303 | def Define_DH_Delta_Strategy_Model(self): 304 | if self.strategy_type == "simple": 305 | # Set up the sub-model that outputs the delta. 306 | submodel = \ 307 | Model(self.model.get_layer("delta_" + 308 | str(self.days_from_today)).input, 309 | self.model.get_layer("delta_" + 310 | str(self.days_from_today)).output) 311 | elif self.strategy_type == "recurrent": 312 | # For "recurrent", the information set is price as well as the past 313 | # delta. 314 | inputs = [Input(1,), Input(1,)] 315 | 316 | intermediate_inputs = Concatenate()(inputs) 317 | 318 | outputs = self.model.get_layer( 319 | "delta_" + str(self.days_from_today))(intermediate_inputs) 320 | 321 | submodel = Model(inputs=inputs, outputs=outputs) 322 | return submodel 323 | 324 | # Draw PnL histogram (PlotWidget) - Black-Scholes vs Deep Hedging. 325 | 326 | def PnL_Hist_Widget(self): 327 | # Initialize the PnL Histogram Widget. 328 | fig_PnL = pg.PlotWidget() 329 | 330 | x_min = np.minimum(self.PnL_BS.min() + self.price_BS[0, 0], -3) 331 | x_max = np.maximum(self.PnL_BS.max() + self.price_BS[0, 0], 3) 332 | 333 | self.x_range = (x_min, x_max) 334 | self.BS_bins, self.bin_edges = np.histogram( 335 | self.PnL_BS + self.price_BS[0, 0], 336 | bins=num_bins, 337 | range=self.x_range) 338 | if self.flag_target: 339 | self.width = (self.bin_edges[1] - self.bin_edges[0]) / 3.0 340 | else: 341 | self.width = (self.bin_edges[1] - self.bin_edges[0]) / 2.0 342 | 343 | self.BS_hist = pg.BarGraphItem(x=self.bin_edges[:-2], 344 | height=self.BS_bins, 345 | width=self.width, 346 | brush='r', 347 | name="Red - Black-Scholes", 348 | antialias=False) 349 | 350 | fig_PnL.setTitle( 351 | "Profit and Loss (PnL) Histogram") 352 | fig_PnL.setLabels( 353 | left="Frequency", 354 | bottom="Profit and Loss (PnL) ") 355 | 356 | # Fix the problem that Y-axes keep moving when transactioni cost is 357 | # greater than zero. 358 | fig_PnL.setYRange(0, self.BS_bins.max() * 1.1) 359 | 360 | if self.flag_target: 361 | fig_PnL.setXRange(self.bin_edges.min(), 2) 362 | else: 363 | fig_PnL.setXRange(self.bin_edges.min(), 2) 364 | 365 | fig_PnL.addItem(self.BS_hist) 366 | 367 | if self.flag_target: 368 | self.DH_target_bins, _ = np.histogram( 369 | self.target_PnL + self.price_BS[0, 0], 370 | bins=num_bins, 371 | range=self.x_range) 372 | self.DH_target_hist = pg.BarGraphItem( 373 | x=self.bin_edges[ 374 | :-2] + 2 * self.width, 375 | height=self.DH_target_bins, 376 | width=self.width, 377 | brush=self.target_color, 378 | name="Green - Deep-Hedging PnL (Target)", 379 | antialias=False) 380 | fig_PnL.addItem(self.DH_target_hist) 381 | PnL_html = ("
" + 382 | "" + 383 | "Black-Scholes PnL (Benchmark)
" + 384 | "" + 385 | "Deep-Hedging PnL (Target)" + 386 | "
").format(str(self.target_color)) + \ 387 | "" + \ 388 | "Deep-Hedging PnL
" 389 | else: 390 | PnL_html = "
" + \ 391 | "" + \ 392 | "Black-Scholes PnL (Benchmark)
" + \ 393 | "" + \ 394 | "Deep-Hedging PnL
" 395 | 396 | fig_PnL_text = pg.TextItem( 397 | html=PnL_html, anchor=( 398 | 0, 0), angle=0, border='w', fill=( 399 | 225, 225, 200)) 400 | 401 | fig_PnL_text.setPos(self.bin_edges.min(), self.BS_bins.max() * 1.05) 402 | fig_PnL.addItem(fig_PnL_text) 403 | 404 | return fig_PnL 405 | 406 | # Draw Delta plot (PlotWidget) - Black-Scholes vs Deep Hedging. 407 | # Assume the PnL_Hist_Widget ran first, so we don't need to run the model 408 | # again. 409 | 410 | def Delta_Plot_Widget(self): 411 | self.tau = (self.N - self.days_from_today) * self.dt 412 | 413 | self.min_S = self.S_test[0][:, self.days_from_today].min() 414 | self.max_S = self.S_test[0][:, self.days_from_today].max() 415 | self.S_range = np.linspace(self.min_S, self.max_S, 51) 416 | 417 | # Attention: Need to transform it to be consistent with the information 418 | # set. 419 | if information_set == "S": 420 | self.I_range = self.S_range # Information set 421 | elif information_set == "log_S": 422 | self.I_range = np.log(self.S_range) 423 | elif information_set == "normalized_log_S": 424 | self.I_range = np.log(self.S_range / self.S0) 425 | 426 | # Compute Black-Scholes delta for S_range. 427 | # Reference: https://en.wikipedia.org/wiki/Greeks_(finance) 428 | self.d1 = (np.log(self.S_range) - np.log(self.strike) + 429 | (self.risk_free - self.dividend + (self.sigma**2) / 2) * 430 | self.tau) / (self.sigma * np.sqrt(self.tau)) 431 | 432 | self.model_delta = norm.cdf( 433 | self.d1) * np.exp(-self.dividend * self.tau) 434 | 435 | fig_delta = pg.PlotWidget() 436 | 437 | self.BS_delta_plot = pg.PlotCurveItem( 438 | pen=pg.mkPen(color="r", width=2.5), name="Black-Scholes") 439 | self.BS_delta_plot.setData(self.S_range, self.model_delta) 440 | 441 | fig_delta.setTitle( 442 | " Hedging Strategy: Delta (at t = 15 days)") 443 | fig_delta.setLabels( 444 | left="Delta", 445 | bottom="Stock Price") 446 | 447 | fig_delta_text = pg.TextItem( 448 | html="
" + 449 | "Black-Scholes Delta (Benchmark)
" + 450 | "" + 451 | "Deep-Hedging Delta
", 452 | anchor=( 453 | 0, 454 | 0), 455 | angle=0, 456 | border='w', 457 | fill=( 458 | 255, 459 | 255, 460 | 200)) 461 | fig_delta_text.setPos(self.S_range.min(), self.model_delta.max()) 462 | 463 | fig_delta.addItem(self.BS_delta_plot) 464 | fig_delta.addItem(fig_delta_text) 465 | 466 | return fig_delta 467 | 468 | # Draw loss plot (PlotWidget) - Black-Scholes vs Deep Hedging. 469 | 470 | def Loss_Plot_Widget(self): 471 | fig_loss = pg.PlotWidget() 472 | 473 | self.DH_loss_plot = pg.PlotDataItem( 474 | pen=pg.mkPen( 475 | color="b", width=6), symbolBrush=( 476 | 0, 0, 255), symbolPen='y', symbol='+', symbolSize=8) 477 | fig_loss.addItem(self.DH_loss_plot) 478 | 479 | # Add a line for the Black-Scholes price. 480 | fig_loss.addLine(y=self.loss_BS, pen=pg.mkPen(color="r", width=1.5)) 481 | 482 | self.BS_loss_html = ("
" + 483 | "" + 484 | "Black-Scholes Loss (Benchmark)
" + 485 | "{:0.3f}
").format( 487 | self.loss_BS) 488 | self.BS_loss_textItem = pg.TextItem( 489 | html=self.BS_loss_html, anchor=( 490 | 1, 1), angle=0, border='w', fill=( 491 | 255, 255, 200)) 492 | 493 | if self.flag_target: 494 | self.DH_target_loss_html = ("
" + 495 | "Deep-Hedging Loss " + 498 | "(Target) " + 499 | "
{:0.3f}" 502 | "
").format(self.target_loss) 503 | self.DH_target_loss_textItem = pg.TextItem( 504 | html=self.DH_target_loss_html, anchor=( 505 | 1, 1), angle=0, border='w', fill=( 506 | 255, 255, 200)) 507 | 508 | # Label the graph. 509 | fig_loss.setTitle( 510 | " Loss Function (Option Price) ") 511 | fig_loss.setLabels( 512 | left="Loss Value", 513 | bottom="Loss Function (Option Price) " + 514 | "- Number of Epochs") 515 | 516 | # Set appropriate xRange and yRange. 517 | fig_loss.setRange(xRange=(0, self.epochs)) 518 | 519 | # For the presentation... 520 | if self.flag_target: 521 | fig_loss.addLine( 522 | y=self.target_loss, pen=pg.mkPen( 523 | color=self.target_color, width=1.5)) 524 | 525 | return fig_loss 526 | 527 | # Update Plots - Black-Scholes vs Deep Hedging. 528 | def Update_Plots_Widget( 529 | self, 530 | PnL_DH=None, 531 | DH_delta=None, 532 | DH_bins=None, 533 | loss=None, 534 | num_epoch=None, 535 | num_batch=None, 536 | flag_last_batch_in_epoch=None): 537 | 538 | self.Update_PnL_Histogram( 539 | PnL_DH, 540 | DH_delta, 541 | DH_bins, 542 | loss, 543 | num_epoch, 544 | num_batch, 545 | flag_last_batch_in_epoch) 546 | 547 | self.Update_Delta_Plot( 548 | PnL_DH, 549 | DH_delta, 550 | DH_bins, 551 | loss, 552 | num_epoch, 553 | num_batch, 554 | flag_last_batch_in_epoch) 555 | 556 | self.Update_Loss_Plot( 557 | PnL_DH, 558 | DH_delta, 559 | DH_bins, 560 | loss, 561 | num_epoch, 562 | num_batch, 563 | flag_last_batch_in_epoch) 564 | 565 | self.Thread_RunDH.Figure_IsUpdated = True 566 | 567 | if num_epoch == self.epochs and \ 568 | flag_last_batch_in_epoch is True and \ 569 | self.epsilon > 0.0: 570 | np.save("../data/target_PnL_" + str(self.epsilon), PnL_DH) 571 | 572 | def Update_Loss_Plot( 573 | self, 574 | PnL_DH=None, 575 | DH_delta=None, 576 | DH_bins=None, 577 | loss=None, 578 | num_epoch=None, 579 | num_batch=None, 580 | flag_last_batch_in_epoch=None): 581 | 582 | DH_shift = 0.6 583 | 584 | # Get the latest viewRange 585 | yMin_View, yMax_View = self.fig_loss.viewRange()[1] 586 | 587 | # Update text position for Black-Scholes 588 | self.BS_loss_textItem.setPos( 589 | self.epochs * 0.8, self.loss_BS + 590 | (yMax_View - self.loss_BS) * 0.005) 591 | 592 | if self.flag_target: 593 | self.DH_target_loss_textItem.setPos( 594 | self.epochs * 0.6, self.target_loss + 595 | (yMax_View - self.target_loss) * 0.005) 596 | 597 | # Update text for Deep-Hedging. 598 | DH_loss_text_title = "
Deep-Hedging Loss
" 600 | DH_loss_text_step = " Epoch: {} " + \ 601 | "Batch: {}
" 602 | DH_loss_text_loss = "{:0.3f}
" 604 | 605 | DH_loss_text_str = ( 606 | DH_loss_text_title + 607 | DH_loss_text_step + 608 | DH_loss_text_loss).format( 609 | int(num_epoch), 610 | int(num_batch), 611 | loss) 612 | 613 | if num_epoch == 1 and num_batch == 1: 614 | self.fig_loss.addItem(self.BS_loss_textItem) 615 | 616 | if self.flag_target: 617 | self.fig_loss.addItem(self.DH_target_loss_textItem) 618 | 619 | # Setup the textbox for the deep-hedging loss. 620 | self.DH_loss_textItem = pg.TextItem( 621 | html=DH_loss_text_str, anchor=( 622 | 0, 0), angle=0, border='w', fill=( 623 | 255, 255, 200)) 624 | self.DH_loss_textItem.setPos((num_epoch - 1) + DH_shift, loss) 625 | self.fig_loss.addItem(self.DH_loss_textItem) 626 | 627 | self.fig_loss.enableAutoRange() 628 | 629 | # Mandatory pause to explain the demo. Remember to modify the 630 | # algo thread as well if one wants to remove the feature. 631 | # This part takes care the pause button. 632 | self.Pause() 633 | else: 634 | self.DH_loss_textItem.setHtml(DH_loss_text_str) 635 | if flag_last_batch_in_epoch: 636 | self.DH_loss_textItem.setPos(num_epoch + DH_shift, loss) 637 | if num_epoch == 1: 638 | # Establish the data for the out-of-sample loss at the end 639 | # of the first epoch. 640 | self.oos_loss_record = np.array([num_epoch, loss], ndmin=2) 641 | else: 642 | # Keep adding data at the end of each epoch. 643 | self.oos_loss_record = np.vstack( 644 | [self.oos_loss_record, np.array([num_epoch, loss])]) 645 | 646 | self.DH_loss_plot.setData(self.oos_loss_record) 647 | 648 | # Move the Black-Scholes textbox to the left to avoid collision of the 649 | # deep-hedging textbox. 650 | if num_epoch > self.epochs * 0.5: 651 | if self.epsilon == 0: 652 | anchor = (0, 0) 653 | elif self.epsilon > 0: 654 | anchor = (0, 1) 655 | 656 | self.fig_loss.removeItem(self.BS_loss_textItem) 657 | self.BS_loss_textItem = pg.TextItem( 658 | html=self.BS_loss_html, 659 | anchor=anchor, 660 | angle=0, 661 | border='w', 662 | fill=( 663 | 255, 664 | 255, 665 | 200)) 666 | self.BS_loss_textItem.setPos( 667 | 0, self.loss_BS + (yMax_View - self.loss_BS) * 0.005) 668 | self.fig_loss.addItem(self.BS_loss_textItem) 669 | 670 | def Update_PnL_Histogram( 671 | self, 672 | PnL_DH=None, 673 | DH_delta=None, 674 | DH_bins=None, 675 | loss=None, 676 | num_epoch=None, 677 | num_batch=None, 678 | flag_last_batch_in_epoch=None): 679 | if num_epoch == 1 and num_batch == 1: 680 | # Update PnL Histogram 681 | self.DH_hist = pg.BarGraphItem(x=self.bin_edges[:-2] + self.width, 682 | height=DH_bins, 683 | width=self.width, 684 | brush='b', 685 | name="Blue - Deep Hedging", 686 | antialias=False) 687 | self.fig_PnL.addItem(self.DH_hist) 688 | else: 689 | # Update PnL Histograms 690 | self.DH_hist.setOpts(height=DH_bins) 691 | 692 | def Update_Delta_Plot( 693 | self, 694 | PnL_DH=None, 695 | DH_delta=None, 696 | DH_bins=None, 697 | loss=None, 698 | num_epoch=None, 699 | num_batch=None, 700 | flag_last_batch_in_epoch=None): 701 | if num_epoch == 1 and num_batch == 1: 702 | # Update the Delta plot 703 | self.DH_delta_plot = pg.PlotDataItem( 704 | symbolBrush=( 705 | 0, 706 | 0, 707 | 255), 708 | symbolPen='b', 709 | symbol='+', 710 | symbolSize=10, 711 | name="Deep Hedging") 712 | self.DH_delta_plot.setData(self.S_range, DH_delta) 713 | self.fig_delta.addItem(self.DH_delta_plot) 714 | else: 715 | # Update the Delta plot 716 | self.DH_delta_plot.setData(self.S_range, DH_delta) 717 | 718 | def simulate_stock_prices(self): 719 | # Total obs = Training + Testing 720 | self.nobs = int(self.Ktrain * (1 + self.Ktest_ratio)) 721 | 722 | # Length of one time-step (as fraction of a year). 723 | self.dt = day_count.yearFraction( 724 | calculation_date, calculation_date + 1) 725 | self.maturity = self.N * self.dt # Maturities (in the unit of a year) 726 | 727 | self.stochastic_process = BlackScholesProcess( 728 | s0=self.S0, 729 | sigma=self.sigma, 730 | risk_free=self.risk_free, 731 | dividend=self.dividend, 732 | day_count=day_count) 733 | 734 | print("\nRun Monte-Carlo Simulations for the Stock Price Process.\n") 735 | return self.stochastic_process.gen_path( 736 | self.maturity, self.N, self.nobs) 737 | print("\n") 738 | 739 | def assemble_data(self): 740 | self.payoff_T = self.payoff_func( 741 | self.S[:, -1]) # Payoff of the call option 742 | 743 | self.trade_set = np.stack((self.S), axis=1) # Trading set 744 | 745 | if information_set == "S": 746 | self.infoset = np.stack((self.S), axis=1) # Information set 747 | elif information_set == "log_S": 748 | self.infoset = np.stack((np.log(self.S)), axis=1) 749 | elif information_set == "normalized_log_S": 750 | self.infoset = np.stack((np.log(self.S / self.S0)), axis=1) 751 | 752 | # Structure of xtrain: 753 | # 1) Trade set: [S] 754 | # 2) Information set: [S] 755 | # 3) payoff (dim = 1) 756 | self.x_all = [] 757 | for i in range(self.N + 1): 758 | self.x_all += [self.trade_set[i, :, None]] 759 | if i != self.N: 760 | self.x_all += [self.infoset[i, :, None]] 761 | self.x_all += [self.payoff_T[:, None]] 762 | 763 | # Split the entire sample into a training sample and a testing sample. 764 | self.test_size = int(self.Ktrain * self.Ktest_ratio) 765 | [self.xtrain, self.xtest] = train_test_split( 766 | self.x_all, test_size=self.test_size) 767 | [self.S_train, self.S_test] = train_test_split( 768 | [self.S], test_size=self.test_size) 769 | [self.option_payoff_train, self.option_payoff_test] = \ 770 | train_test_split([self.x_all[-1]], test_size=self.test_size) 771 | 772 | # Convert the training sample into tf.Data format (same as xtrain). 773 | training_dataset = tf.data.Dataset.from_tensor_slices( 774 | tuple(self.xtrain)) 775 | return training_dataset.cache() 776 | 777 | def get_Black_Scholes_Prices(self): 778 | # Obtain Black-Scholes price, delta, and PnL 779 | call = EuropeanCall() 780 | price_BS = call.get_BS_price( 781 | S=self.S_test[0], 782 | sigma=self.sigma, 783 | risk_free=self.risk_free, 784 | dividend=self.dividend, 785 | K=self.strike, 786 | exercise_date=self.maturity_date, 787 | calculation_date=calculation_date, 788 | day_count=day_count, 789 | dt=self.dt) 790 | delta_BS = call.get_BS_delta( 791 | S=self.S_test[0], 792 | sigma=self.sigma, 793 | risk_free=self.risk_free, 794 | dividend=self.dividend, 795 | K=self.strike, 796 | exercise_date=self.maturity_date, 797 | calculation_date=calculation_date, 798 | day_count=day_count, 799 | dt=self.dt) 800 | PnL_BS = call.get_BS_PnL(S=self.S_test[0], 801 | payoff=self.payoff_func(self.S_test[0][:, 802 | -1]), 803 | delta=delta_BS, 804 | dt=self.dt, 805 | risk_free=self.risk_free, 806 | final_period_cost=final_period_cost, 807 | epsilon=self.epsilon) 808 | return price_BS, delta_BS, PnL_BS 809 | -------------------------------------------------------------------------------- /pyqt5/readme.txt: -------------------------------------------------------------------------------- 1 | Instruction for Running on the Grid: 2 | 3 | Run: 4 | 5 | bsub -Is -q "python" numactl --cpunodebind=0 zsh python3 6 | 7 | Then, within Python: 8 | 9 | exec(open("deep_hedging_gui.py").read()) 10 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | Package Version 2 | ----------------------------- ------------------- 3 | pyqtgraph 0.11.0 4 | QtPy 1.9.0 5 | QuantLib 1.20 6 | scikit-learn 0.23.2 7 | scipy 1.5.2 8 | tensorflow 2.3.1 9 | tqdm 4.51.0 10 | -------------------------------------------------------------------------------- /stochastic_processes/BlackScholesProcess.py: -------------------------------------------------------------------------------- 1 | import QuantLib as ql 2 | import numpy as np 3 | from tqdm import trange 4 | 5 | # References: 6 | # https://www.implementingquantlib.com/2014/06/chapter-6-part-5-of-8-path-generators.html 7 | # https://www.quantlib.org/reference/index.html 8 | # https://github.com/lballabio/QuantLib-SWIG 9 | 10 | # Assigned seed for testing. Set to 0 for random seeds. 11 | 12 | # Geometric Brownian Motion. 13 | class BlackScholesProcess: 14 | def __init__(self,s0 = None, sigma = None, risk_free = None, \ 15 | dividend = None, day_count = None, seed=0): 16 | self.s0 = s0 17 | self.sigma = sigma 18 | self.risk_free = risk_free 19 | self.dividend = dividend 20 | self.day_count = day_count 21 | self.seed = seed 22 | 23 | def get_process(self, calculation_date = ql.Date.todaysDate()): 24 | spot_handle = ql.QuoteHandle(ql.SimpleQuote(self.s0)) 25 | rf_handle = ql.QuoteHandle(ql.SimpleQuote(self.risk_free)) 26 | dividend_handle = ql.QuoteHandle(ql.SimpleQuote(self.dividend)) 27 | 28 | volatility = ql.BlackConstantVol(0, ql.NullCalendar(),self.sigma,self.day_count) 29 | 30 | # Assume flat term-structure. 31 | flat_ts = ql.YieldTermStructureHandle(ql.FlatForward(0, ql.NullCalendar(), rf_handle, self.day_count)) 32 | dividend_yield = ql.YieldTermStructureHandle(ql.FlatForward(0, ql.NullCalendar(), dividend_handle, self.day_count)) 33 | 34 | ql.Settings.instance().evaluationDate = calculation_date 35 | 36 | return ql.GeneralizedBlackScholesProcess( 37 | spot_handle, 38 | dividend_yield, 39 | flat_ts, 40 | ql.BlackVolTermStructureHandle(volatility)) 41 | 42 | def gen_path(self, length = None, time_step = None, num_paths = None): 43 | # The variable length is in the unit of one year. 44 | rng = ql.GaussianRandomSequenceGenerator(ql.UniformRandomSequenceGenerator(time_step, ql.UniformRandomGenerator(self.seed))) 45 | seq = ql.GaussianMultiPathGenerator(self.get_process(), np.linspace(0,length,time_step+1), rng, False) 46 | 47 | value = np.zeros((num_paths, time_step+1)) 48 | 49 | for i in trange(num_paths): 50 | sample_path = seq.next() 51 | path = sample_path.value() 52 | value[i, :] = np.array(path[0]) 53 | return value 54 | -------------------------------------------------------------------------------- /stochastic_processes/__init__.py: -------------------------------------------------------------------------------- 1 | from .BlackScholesProcess import BlackScholesProcess 2 | -------------------------------------------------------------------------------- /utilities/__init__.py: -------------------------------------------------------------------------------- 1 | from .train_test_split import train_test_split 2 | -------------------------------------------------------------------------------- /utilities/train_test_split.py: -------------------------------------------------------------------------------- 1 | from sklearn import model_selection 2 | 3 | 4 | def train_test_split(data=None, test_size=None): 5 | """Split simulated data into training and testing sample.""" 6 | xtrain = [] 7 | xtest = [] 8 | for x in data: 9 | tmp_xtrain, tmp_xtest = model_selection.train_test_split( 10 | x, test_size=test_size, shuffle=False) 11 | xtrain += [tmp_xtrain] 12 | xtest += [tmp_xtest] 13 | return xtrain, xtest 14 | --------------------------------------------------------------------------------