├── .github
├── FUNDING.yml
└── workflows
│ └── python-publish.yml
├── .gitignore
├── LICENSE
├── README.md
├── optopsy
├── __init__.py
├── checks.py
├── core.py
├── datafeeds.py
├── definitions.py
├── rules.py
└── strategies.py
├── requirements.txt
├── samples
├── data
│ └── sample_spx_data.csv
├── spx_singles_example.py
├── spx_straddles_example.py
└── spx_strangles_example.py
├── setup.py
└── tests
├── __init__.py
├── conftest.py
├── test_checks.py
├── test_data
└── data.csv
├── test_datafeeds.py
├── test_rules.py
└── test_strategies.py
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: michaelchu
4 | patreon: # Replace with a single Patreon username
5 | open_collective: # Replace with a single Open Collective username
6 | ko_fi: # Replace with a single Ko-fi username
7 | tidelift: # Replace with a single Tidelift platform-name/package-name e.g., npm/babel
8 | community_bridge: # Replace with a single Community Bridge project-name e.g., cloud-foundry
9 | liberapay: # Replace with a single Liberapay username
10 | issuehunt: # Replace with a single IssueHunt username
11 | otechie: # Replace with a single Otechie username
12 | custom: # Replace with up to 4 custom sponsorship URLs e.g., ['link1', 'link2']
13 |
--------------------------------------------------------------------------------
/.github/workflows/python-publish.yml:
--------------------------------------------------------------------------------
1 | # This workflows will upload a Python Package using Twine when a release is created
2 | # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries
3 |
4 | name: Upload Python Package
5 |
6 | on:
7 | release:
8 | types: [created]
9 |
10 | jobs:
11 | deploy:
12 |
13 | runs-on: ubuntu-latest
14 |
15 | steps:
16 | - uses: actions/checkout@v2
17 | - name: Set up Python
18 | uses: actions/setup-python@v2
19 | with:
20 | python-version: '3.x'
21 | - name: Install dependencies
22 | run: |
23 | python -m pip install --upgrade pip
24 | pip install setuptools wheel twine
25 | - name: Build and publish
26 | env:
27 | TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }}
28 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
29 | run: |
30 | python setup.py sdist bdist_wheel
31 | twine upload dist/*
32 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ### Python template
2 |
3 | # Byte-compiled / optimized / DLL files
4 | __pycache__/
5 | *.py[cod]
6 | *$py.class
7 |
8 | # Virtual environments
9 | optopsy-env
10 |
11 | # C extensions
12 | *.so
13 |
14 | # Distribution / packaging
15 | .Python
16 | build/
17 | develop-eggs/
18 | dist/
19 | downloads/
20 | eggs/
21 | .eggs/
22 | lib/
23 | lib64/
24 | parts/
25 | sdist/
26 | var/
27 | wheels/
28 | *.egg-info/
29 | .installed.cfg
30 | *.egg
31 | MANIFEST
32 |
33 | .DS_Store
34 | .idea
35 | .vscode
36 |
37 | /tests/.pytest_cache/
38 |
39 | *.swp
40 | *.swo
41 |
42 | /venv/
--------------------------------------------------------------------------------
/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 | .
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | [](https://pepy.tech/project/optopsy)
2 | [](https://github.com/ambv/black)
3 |
4 | # Optopsy
5 |
6 | Optopsy is a nimble backtesting and statistics library for option strategies, it is designed to answer questions like
7 | "How do straddles perform on the SPX?" or "Which strikes and/or expiration dates should I choose to make the most potential profit?"
8 |
9 | Use cases for Optopsy:
10 | * Generate option strategies from raw option chain datasets for your own analysis
11 | * Discover performance statistics on **percentage change** for various options strategies on a given stock
12 |
13 | ## Supported Option Strategies
14 | * Calls/Puts
15 | * Straddles/Strangles
16 | * Vertical Call/Put Spreads
17 |
18 | ## Documentation
19 | Please see the [wiki](https://github.com/michaelchu/optopsy/wiki) for API reference.
20 |
21 | ## Usage
22 |
23 | ### Use Your Data
24 | * Use data from any source, just provide a Pandas dataframe with the required columns when calling optopsy functions.
25 |
26 | ### Dependencies
27 | You will need Python 3.6 or newer and Pandas 0.23.1 or newer and Numpy 1.14.3 or newer.
28 |
29 | ### Installation
30 | ```
31 | pip install optopsy==2.0.1
32 | ```
33 |
34 | ### Example
35 |
36 | Let's see how long calls perform on the SPX on a small demo dataset on the SPX:
37 |
38 | **Note:** As of July 2024, the link below is broken, however DeltaNeutral still provides free data [here](https://historicaloptiondata.com/free-data/).
39 | You should still be able to proceed by mapping the columns according to the current format of the sample data as shown below.
40 |
41 | ~~Download the following data sample from DeltaNeutral: http://www.deltaneutral.com/files/Sample_SPX_20151001_to_20151030.csv~~
42 |
43 | This dataset is for the month of October in 2015, lets load it into Optopsy. First create a small helper function
44 | that returns a file path to our file. We will store it under a folder named 'data', in the same directory as the working python file.
45 | ```
46 | def filepath():
47 | curr_file = os.path.abspath(os.path.dirname(__file__))
48 | return os.path.join(curr_file, "./data/Sample_SPX_20151001_to_20151030.csv")
49 | ```
50 |
51 | Next lets use this function to pass in the file path string into Optopsy's `csv_data()` function, we will map the column
52 | indices using the defined function parameters. We are omitting the `start_date` and `end_date` parameters in this call because
53 | we want to include the entire dataset. The numeric values represent the column number as found in the sample file, the
54 | numbers are 0-indexed:
55 | ```
56 | import optopsy as op
57 |
58 | spx_data = op.csv_data(
59 | filepath(),
60 | underlying_symbol=0,
61 | underlying_price=1,
62 | option_type=5,
63 | expiration=6,
64 | quote_date=7,
65 | strike=8,
66 | bid=10,
67 | ask=11,
68 | )
69 | ```
70 | The `csv_data()` function is a convenience function. Under the hood it uses Panda's `read_csv()` function to do the import.
71 | There are other parameters that can help with loading the csv data, consult the code/future documentation to see how to use them.
72 |
73 | Optopsy is a small simple library that offloads the heavy work of backtesting option strategies, the API is designed to be simple
74 | and easy to implement into your regular Panda's data analysis workflow. As such, we just need to call the `long_calls()` function
75 | to have Optopsy generate all combinations of a simple long call strategy for the specified time period and return a DataFrame. Here we
76 | also use Panda's `round()` function afterwards to return statistics within two decimal places.
77 |
78 | ```
79 | long_calls_spx_pct_chgs = op.long_calls(spx_data).round(2)
80 | ```
81 |
82 | The function will returned a Pandas DataFrame containing the statistics on the **percentange changes** of running long calls in all *valid* combinations on the SPX:
83 |
84 | | | dte_range | otm_pct_range | count | mean | std | min | 25% | 50% | 75% | max |
85 | |----|-------------|-----------------|---------|--------|-------|-------|-------|-------|-------|-------|
86 | | 0 | (0, 7] | (-0.5, -0.45] | 155 | 0.03 | 0.02 | -0.02 | 0.01 | 0.02 | 0.04 | 0.11 |
87 | | 1 | (0, 7] | (-0.45, -0.4] | 201 | 0.04 | 0.03 | -0.02 | 0.01 | 0.03 | 0.06 | 0.12 |
88 | | 2 | (0, 7] | (-0.4, -0.35] | 247 | 0.04 | 0.03 | -0.02 | 0.02 | 0.04 | 0.07 | 0.13 |
89 | | 3 | (0, 7] | (-0.35, -0.3] | 296 | 0.05 | 0.04 | -0.02 | 0.02 | 0.04 | 0.08 | 0.15 |
90 | | 4 | (0, 7] | (-0.3, -0.25] | 329 | 0.05 | 0.05 | -0.03 | 0.02 | 0.05 | 0.09 | 0.17 |
91 | | 5 | (0, 7] | (-0.25, -0.2] | 352 | 0.06 | 0.05 | -0.03 | 0.02 | 0.05 | 0.1 | 0.2 |
92 | | 6 | (0, 7] | (-0.2, -0.15] | 383 | 0.08 | 0.07 | -0.04 | 0.03 | 0.07 | 0.13 | 0.26 |
93 | | 7 | (0, 7] | (-0.15, -0.1] | 417 | 0.11 | 0.09 | -0.06 | 0.04 | 0.09 | 0.17 | 0.37 |
94 | | 8 | (0, 7] | (-0.1, -0.05] | 461 | 0.18 | 0.16 | -0.12 | 0.07 | 0.15 | 0.28 | 0.69 |
95 | | 9 | (0, 7] | (-0.05, -0.0] | 505 | 0.64 | 1.03 | -1 | 0.14 | 0.37 | 0.87 | 7.62 |
96 | | 10 | (0, 7] | (-0.0, 0.05] | 269 | 2.34 | 8.65 | -1 | -1 | -0.89 | 1.16 | 68 |
97 | | 11 | (0, 7] | (0.05, 0.1] | 2 | -1 | 0 | -1 | -1 | -1 | -1 | -1 |
98 | | 12 | (7, 14] | (-0.5, -0.45] | 70 | 0.06 | 0.03 | 0.02 | 0.03 | 0.07 | 0.08 | 0.12 |
99 | | 13 | (7, 14] | (-0.45, -0.4] | 165 | 0.09 | 0.04 | 0.02 | 0.06 | 0.08 | 0.1 | 0.17 |
100 | | 14 | (7, 14] | (-0.4, -0.35] | 197 | 0.09 | 0.04 | 0.02 | 0.07 | 0.09 | 0.12 | 0.19 |
101 | | 15 | (7, 14] | (-0.35, -0.3] | 235 | 0.11 | 0.04 | 0.02 | 0.09 | 0.1 | 0.13 | 0.21 |
102 | | 16 | (7, 14] | (-0.3, -0.25] | 265 | 0.13 | 0.05 | 0.03 | 0.1 | 0.12 | 0.15 | 0.25 |
103 | | 17 | (7, 14] | (-0.25, -0.2] | 280 | 0.15 | 0.06 | 0.03 | 0.11 | 0.14 | 0.18 | 0.3 |
104 | | 18 | (7, 14] | (-0.2, -0.15] | 307 | 0.18 | 0.08 | 0.04 | 0.14 | 0.18 | 0.23 | 0.38 |
105 | | 19 | (7, 14] | (-0.15, -0.1] | 332 | 0.25 | 0.11 | 0.05 | 0.18 | 0.24 | 0.31 | 0.54 |
106 | | 20 | (7, 14] | (-0.1, -0.05] | 370 | 0.4 | 0.18 | 0.07 | 0.29 | 0.39 | 0.52 | 0.97 |
107 | | 21 | (7, 14] | (-0.05, -0.0] | 404 | 1.02 | 0.68 | -0.46 | 0.58 | 0.86 | 1.32 | 4.4 |
108 | | 22 | (7, 14] | (-0.0, 0.05] | 388 | 1.52 | 4.45 | -1 | -0.99 | -0.73 | 2.65 | 32 |
109 | | 23 | (7, 14] | (0.05, 0.1] | 36 | -0.93 | 0.06 | -1 | -1 | -0.94 | -0.87 | -0.83 |
110 | | 24 | (14, 21] | (-0.5, -0.45] | 6 | 0.1 | 0.01 | 0.09 | 0.09 | 0.1 | 0.1 | 0.1 |
111 | | 25 | (14, 21] | (-0.45, -0.4] | 66 | 0.14 | 0.04 | 0.09 | 0.11 | 0.14 | 0.17 | 0.23 |
112 | | 26 | (14, 21] | (-0.4, -0.35] | 91 | 0.16 | 0.04 | 0.1 | 0.12 | 0.16 | 0.2 | 0.25 |
113 | | 27 | (14, 21] | (-0.35, -0.3] | 135 | 0.18 | 0.05 | 0.11 | 0.13 | 0.17 | 0.21 | 0.28 |
114 | | 28 | (14, 21] | (-0.3, -0.25] | 149 | 0.2 | 0.05 | 0.12 | 0.15 | 0.2 | 0.25 | 0.33 |
115 | | 29 | (14, 21] | (-0.25, -0.2] | 160 | 0.24 | 0.06 | 0.14 | 0.18 | 0.23 | 0.29 | 0.4 |
116 | | 30 | (14, 21] | (-0.2, -0.15] | 174 | 0.3 | 0.08 | 0.17 | 0.23 | 0.29 | 0.35 | 0.51 |
117 | | 31 | (14, 21] | (-0.15, -0.1] | 187 | 0.4 | 0.11 | 0.22 | 0.3 | 0.38 | 0.48 | 0.7 |
118 | | 32 | (14, 21] | (-0.1, -0.05] | 211 | 0.63 | 0.19 | 0.32 | 0.47 | 0.6 | 0.75 | 1.16 |
119 | | 33 | (14, 21] | (-0.05, -0.0] | 229 | 1.39 | 0.53 | 0.58 | 1 | 1.3 | 1.73 | 3.1 |
120 | | 34 | (14, 21] | (-0.0, 0.05] | 252 | 2.58 | 2.92 | -1 | -1 | 2.72 | 4.56 | 10.1 |
121 | | 35 | (14, 21] | (0.05, 0.1] | 93 | -0.82 | 0.92 | -1 | -1 | -1 | -1 | 6.39 |
122 | | 36 | (21, 28] | (-0.5, -0.45] | 1 | 0.11 | nan | 0.11 | 0.11 | 0.11 | 0.11 | 0.11 |
123 | | 37 | (21, 28] | (-0.45, -0.4] | 21 | 0.15 | 0.03 | 0.11 | 0.12 | 0.15 | 0.17 | 0.23 |
124 | | 38 | (21, 28] | (-0.4, -0.35] | 39 | 0.2 | 0.06 | 0.12 | 0.16 | 0.18 | 0.24 | 0.32 |
125 | | 39 | (21, 28] | (-0.35, -0.3] | 61 | 0.21 | 0.06 | 0.13 | 0.17 | 0.2 | 0.26 | 0.35 |
126 | | 40 | (21, 28] | (-0.3, -0.25] | 75 | 0.25 | 0.08 | 0.14 | 0.2 | 0.24 | 0.31 | 0.41 |
127 | | 41 | (21, 28] | (-0.25, -0.2] | 79 | 0.3 | 0.09 | 0.17 | 0.23 | 0.27 | 0.37 | 0.49 |
128 | | 42 | (21, 28] | (-0.2, -0.15] | 87 | 0.37 | 0.11 | 0.2 | 0.29 | 0.34 | 0.45 | 0.62 |
129 | | 43 | (21, 28] | (-0.15, -0.1] | 93 | 0.48 | 0.15 | 0.26 | 0.37 | 0.46 | 0.58 | 0.85 |
130 | | 44 | (21, 28] | (-0.1, -0.05] | 105 | 0.74 | 0.24 | 0.36 | 0.56 | 0.71 | 0.89 | 1.39 |
131 | | 45 | (21, 28] | (-0.05, -0.0] | 114 | 1.45 | 0.54 | 0.62 | 1.05 | 1.34 | 1.73 | 3.28 |
132 | | 46 | (21, 28] | (-0.0, 0.05] | 125 | 2.97 | 3.38 | -1 | 1.29 | 2.58 | 4.21 | 17.15 |
133 | | 47 | (21, 28] | (0.05, 0.1] | 85 | 0.82 | 5.3 | -1 | -1 | -1 | -1 | 19.5 |
134 | | 48 | (28, 35] | (-0.4, -0.35] | 5 | 0.31 | 0.01 | 0.3 | 0.3 | 0.31 | 0.32 | 0.32 |
135 | | 49 | (28, 35] | (-0.35, -0.3] | 7 | 0.34 | 0.01 | 0.32 | 0.33 | 0.35 | 0.35 | 0.36 |
136 | | 50 | (28, 35] | (-0.3, -0.25] | 12 | 0.39 | 0.02 | 0.36 | 0.37 | 0.39 | 0.4 | 0.42 |
137 | | 51 | (28, 35] | (-0.25, -0.2] | 13 | 0.46 | 0.02 | 0.42 | 0.44 | 0.45 | 0.47 | 0.49 |
138 | | 52 | (28, 35] | (-0.2, -0.15] | 14 | 0.55 | 0.04 | 0.5 | 0.53 | 0.55 | 0.58 | 0.62 |
139 | | 53 | (28, 35] | (-0.15, -0.1] | 15 | 0.73 | 0.07 | 0.63 | 0.67 | 0.72 | 0.77 | 0.84 |
140 | | 54 | (28, 35] | (-0.1, -0.05] | 17 | 1.06 | 0.14 | 0.86 | 0.94 | 1.05 | 1.17 | 1.32 |
141 | | 55 | (28, 35] | (-0.05, -0.0] | 19 | 1.95 | 0.44 | 1.36 | 1.58 | 1.87 | 2.26 | 2.79 |
142 | | 56 | (28, 35] | (-0.0, 0.05] | 20 | 5.72 | 2.23 | 2.94 | 3.85 | 5.23 | 7.33 | 9.97 |
143 | | 57 | (28, 35] | (0.05, 0.1] | 21 | 3.53 | 5.47 | -1 | -1 | -1 | 10.38 | 11.32 |
144 |
145 | There are more customization options for Optopsy's strategy functions, consult the codebase/future documentation to see how it can be used to adjust the results, such as increasing/decreasing
146 | the intervals and other data to be returned.
147 |
--------------------------------------------------------------------------------
/optopsy/__init__.py:
--------------------------------------------------------------------------------
1 | from .strategies import *
2 | from .datafeeds import *
3 |
--------------------------------------------------------------------------------
/optopsy/checks.py:
--------------------------------------------------------------------------------
1 | expected_types = {
2 | "underlying_symbol": ("object",),
3 | "underlying_price": ("int64", "float64"),
4 | "option_type": ("object",),
5 | "expiration": ("datetime64[ns]",),
6 | "quote_date": ("datetime64[ns]",),
7 | "strike": ("int64", "float64"),
8 | "bid": ("int64", "float64"),
9 | "ask": ("int64", "float64"),
10 | }
11 |
12 |
13 | def _run_checks(params, data):
14 | for k, v in params.items():
15 | if k in param_checks:
16 | param_checks[k](k, v)
17 | _check_data_types(data)
18 |
19 |
20 | def _check_positive_integer(key, value):
21 | if value <= 0 or not isinstance(value, int):
22 | raise ValueError(f"Invalid setting for {key}, must be positive integer")
23 |
24 |
25 | def _check_positive_integer_inclusive(key, value):
26 | if value < 0 or not isinstance(value, int):
27 | raise ValueError(f"Invalid setting for {key}, must be positive integer, or 0")
28 |
29 |
30 | def _check_positive_float(key, value):
31 | if value <= 0 or not isinstance(value, float):
32 | raise ValueError(f"Invalid setting for {key}, must be positive float type")
33 |
34 |
35 | def _check_side(key, value):
36 | if value != "long" and value != "short":
37 | raise ValueError(f"Invalid setting for '{key}', must be only 'long' or short'")
38 |
39 |
40 | def _check_bool_type(key, value):
41 | if not isinstance(value, bool):
42 | raise ValueError(f"Invalid setting for {key}, must be boolean type")
43 |
44 |
45 | def _check_list_type(key, value):
46 | if not isinstance(value, list):
47 | raise ValueError(f"Invalid setting for {key}, must be a list type")
48 |
49 |
50 | def _check_data_types(data):
51 | df_type_dict = data.dtypes.astype(str).to_dict()
52 | for k, et in expected_types.items():
53 | if k not in df_type_dict:
54 | raise ValueError("Expected column: {k} not found in DataFrame")
55 | if all(df_type_dict[k] != t for t in et):
56 | raise ValueError(
57 | f"{df_type_dict[k]} of {k} does not match expected types: {expected_types[k]}"
58 | )
59 |
60 |
61 | param_checks = {
62 | "dte_interval": _check_positive_integer,
63 | "max_entry_dte": _check_positive_integer,
64 | "exit_dte": _check_positive_integer_inclusive,
65 | "otm_pct_interval": _check_positive_float,
66 | "max_otm_pct": _check_positive_float,
67 | "min_bid_ask": _check_positive_float,
68 | "side": _check_side,
69 | "drop_nan": _check_bool_type,
70 | "raw": _check_bool_type,
71 | }
72 |
--------------------------------------------------------------------------------
/optopsy/core.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | import numpy as np
3 | from functools import reduce
4 | from .definitions import *
5 | from .checks import _run_checks
6 |
7 | pd.set_option("expand_frame_repr", False)
8 | pd.set_option("display.max_rows", None, "display.max_columns", None)
9 |
10 |
11 | def _assign_dte(data):
12 | return data.assign(dte=lambda r: (r["expiration"] - r["quote_date"]).dt.days)
13 |
14 |
15 | def _trim(data, col, lower, upper):
16 | return data.loc[(data[col] >= lower) & (data[col] <= upper)]
17 |
18 |
19 | def _ltrim(data, col, lower):
20 | return data.loc[data[col] >= lower]
21 |
22 |
23 | def _rtrim(data, col, upper):
24 | return data.loc[data[col] <= upper]
25 |
26 |
27 | def _get(data, col, val):
28 | return data.loc[data[col] == val]
29 |
30 |
31 | def _remove_min_bid_ask(data, min_bid_ask):
32 | return data.loc[(data["bid"] > min_bid_ask) & (data["ask"] > min_bid_ask)]
33 |
34 |
35 | def _remove_invalid_evaluated_options(data):
36 | return data.loc[
37 | (data["dte_exit"] <= data["dte_entry"])
38 | & (data["dte_entry"] != data["dte_exit"])
39 | ]
40 |
41 |
42 | def _cut_options_by_dte(data, dte_interval, max_entry_dte):
43 | dte_intervals = list(range(0, max_entry_dte, dte_interval))
44 | data["dte_range"] = pd.cut(data["dte_entry"], dte_intervals)
45 | return data
46 |
47 |
48 | def _cut_options_by_otm(data, otm_pct_interval, max_otm_pct_interval):
49 | # consider using np.linspace in future
50 | otm_pct_intervals = [
51 | round(i, 2)
52 | for i in list(
53 | np.arange(
54 | max_otm_pct_interval * -1,
55 | max_otm_pct_interval,
56 | otm_pct_interval,
57 | )
58 | )
59 | ]
60 | data["otm_pct_range"] = pd.cut(data["otm_pct_entry"], otm_pct_intervals)
61 | return data
62 |
63 |
64 | def _group_by_intervals(data, cols, drop_na):
65 | # this is a bottleneck, try to optimize
66 | grouped_dataset = data.groupby(cols)["pct_change"].describe()
67 |
68 | # if any non-count columns return NaN remove the row
69 | if drop_na:
70 | subset = [col for col in grouped_dataset.columns if "_count" not in col]
71 | grouped_dataset = grouped_dataset.dropna(subset=subset, how="all")
72 |
73 | return grouped_dataset
74 |
75 |
76 | def _evaluate_options(data, **kwargs):
77 |
78 | # trim option chains with strikes too far out from current price
79 | data = data.pipe(_calculate_otm_pct).pipe(
80 | _trim,
81 | "otm_pct",
82 | lower=kwargs["max_otm_pct"] * -1,
83 | upper=kwargs["max_otm_pct"],
84 | )
85 |
86 | # remove option chains that are worthless, it's unrealistic to enter
87 | # trades with worthless options
88 | entries = _remove_min_bid_ask(data, kwargs["min_bid_ask"])
89 |
90 | # to reduce unnecessary computation, filter for options with the desired exit DTE
91 | exits = _get(data, "dte", kwargs["exit_dte"])
92 |
93 | return (
94 | entries.merge(
95 | right=exits,
96 | on=["underlying_symbol", "option_type", "expiration", "strike"],
97 | suffixes=("_entry", "_exit"),
98 | )
99 | # by default we use the midpoint spread price to calculate entry and exit costs
100 | .assign(entry=lambda r: (r["bid_entry"] + r["ask_entry"]) / 2)
101 | .assign(exit=lambda r: (r["bid_exit"] + r["ask_exit"]) / 2)
102 | .pipe(_remove_invalid_evaluated_options)
103 | )[evaluated_cols]
104 |
105 |
106 | def _evaluate_all_options(data, **kwargs):
107 | return (
108 | data.pipe(_assign_dte)
109 | .pipe(_trim, "dte", kwargs["exit_dte"], kwargs["max_entry_dte"])
110 | .pipe(_evaluate_options, **kwargs)
111 | .pipe(_cut_options_by_dte, kwargs["dte_interval"], kwargs["max_entry_dte"])
112 | .pipe(
113 | _cut_options_by_otm,
114 | kwargs["otm_pct_interval"],
115 | kwargs["max_otm_pct"],
116 | )
117 | )
118 |
119 |
120 | def _calls(data):
121 | return data[data.option_type.str.lower().str.startswith("c")]
122 |
123 |
124 | def _puts(data):
125 | return data[data.option_type.str.lower().str.startswith("p")]
126 |
127 |
128 | def _calculate_otm_pct(data):
129 | return data.assign(
130 | otm_pct=lambda r: round((r["strike"] - r["underlying_price"]) / r["strike"], 2)
131 | )
132 |
133 |
134 | def _apply_ratios(data, leg_def):
135 | for idx in range(1, len(leg_def) + 1):
136 | entry_col = f"entry_leg{idx}"
137 | exit_col = f"exit_leg{idx}"
138 | entry_kwargs = {entry_col: lambda r: r[entry_col] * leg_def[idx - 1][0].value}
139 | exit_kwargs = {exit_col: lambda r: r[exit_col] * leg_def[idx - 1][0].value}
140 | data = data.assign(**entry_kwargs).assign(**exit_kwargs)
141 |
142 | return data
143 |
144 |
145 | def _assign_profit(data, leg_def, suffixes):
146 | data = _apply_ratios(data, leg_def)
147 |
148 | # determine all entry and exit columns
149 | entry_cols = ["entry" + s for s in suffixes]
150 | exit_cols = ["exit" + s for s in suffixes]
151 |
152 | # calculate the total entry costs and exit proceeds
153 | data["total_entry_cost"] = data.loc[:, entry_cols].sum(axis=1)
154 | data["total_exit_proceeds"] = data.loc[:, exit_cols].sum(axis=1)
155 |
156 | data["pct_change"] = (
157 | data["total_exit_proceeds"] - data["total_entry_cost"]
158 | ) / data["total_entry_cost"].abs()
159 |
160 | return data
161 |
162 |
163 | def _strategy_engine(data, leg_def, join_on=None, rules=None):
164 | if len(leg_def) == 1:
165 | data["pct_change"] = (data["exit"] - data["entry"]) / data["entry"].abs()
166 | return leg_def[0][1](data)
167 |
168 | def _rule_func(d, r, ld):
169 | return d if r is None else r(d, ld)
170 |
171 | partials = [leg[1](data) for leg in leg_def]
172 | suffixes = [f"_leg{idx}" for idx in range(1, len(leg_def) + 1)]
173 |
174 | # noinspection PyTypeChecker
175 | return (
176 | reduce(
177 | lambda left, right: pd.merge(
178 | left, right, on=join_on, how="inner", suffixes=suffixes
179 | ),
180 | partials,
181 | )
182 | .pipe(_rule_func, rules, leg_def)
183 | .pipe(_assign_profit, leg_def, suffixes)
184 | )
185 |
186 |
187 | def _process_strategy(data, **context):
188 | _run_checks(context["params"], data)
189 | return (
190 | _evaluate_all_options(
191 | data,
192 | dte_interval=context["params"]["dte_interval"],
193 | max_entry_dte=context["params"]["max_entry_dte"],
194 | exit_dte=context["params"]["exit_dte"],
195 | otm_pct_interval=context["params"]["otm_pct_interval"],
196 | max_otm_pct=context["params"]["max_otm_pct"],
197 | min_bid_ask=context["params"]["min_bid_ask"],
198 | )
199 | .pipe(
200 | _strategy_engine,
201 | context["leg_def"],
202 | context.get("join_on"),
203 | context.get("rules"),
204 | )
205 | .pipe(
206 | _format_output,
207 | context["params"],
208 | context["internal_cols"],
209 | context["external_cols"],
210 | )
211 | )
212 |
213 |
214 | def _format_output(data, params, internal_cols, external_cols):
215 | if params["raw"]:
216 | return data[internal_cols].reset_index(drop=True)
217 |
218 | return data.pipe(
219 | _group_by_intervals, external_cols, params["drop_nan"]
220 | ).reset_index()
221 |
--------------------------------------------------------------------------------
/optopsy/datafeeds.py:
--------------------------------------------------------------------------------
1 | import pandas as pd
2 | from .core import _trim, _ltrim, _rtrim
3 | from .checks import _check_data_types
4 |
5 | default_kwargs = {
6 | "start_date": None,
7 | "end_date": None,
8 | "underlying_symbol": 0,
9 | "underlying_price": 1,
10 | "option_type": 2,
11 | "expiration": 3,
12 | "quote_date": 4,
13 | "strike": 5,
14 | "bid": 6,
15 | "ask": 7,
16 | }
17 |
18 |
19 | def _trim_dates(data, start_date, end_date):
20 | if start_date is not None and end_date is not None:
21 | return _trim(data, "expiration", start_date, end_date)
22 | elif start_date is None and end_date is not None:
23 | return _rtrim(data, "expiration", end_date)
24 | elif start_date is not None and end_date is None:
25 | return _ltrim(data, "expiration", start_date)
26 | else:
27 | return data
28 |
29 |
30 | def _trim_cols(data, column_mapping):
31 | cols = [c for c, _ in column_mapping if c is not None]
32 | return data.iloc[:, cols]
33 |
34 |
35 | def _standardize_cols(data, column_mapping):
36 | col_names = list(data.columns)
37 | cols = {col_names[idx]: label for idx, label in column_mapping if idx is not None}
38 | return data.rename(columns=cols)
39 |
40 |
41 | def _infer_date_cols(data):
42 | data["expiration"] = pd.to_datetime(data.expiration, infer_datetime_format=True)
43 | data["quote_date"] = pd.to_datetime(data.quote_date, infer_datetime_format=True)
44 | return data
45 |
46 |
47 | # noinspection PyIncorrectDocstring
48 | def csv_data(file_path, **kwargs):
49 | """
50 | Uses pandas DataFrame.read_csv function to import data from CSV files.
51 | It will automatically generate standardized headers for this library to use.
52 |
53 | Args:
54 | file_path: str, path to csv file
55 | start_date: datetime, start date of data set to consider, date is inclusive
56 | end_date: datetime, end date of data set to consider, date is inclusive
57 | underlying_symbol: int, index of column containing underlying symbol of option chain
58 | underlying_price: int, index of column containing underlying stock price
59 | quote_date: int, index of column containing quote date of option chain
60 | expiration: int, index of column containing expiration of option chain
61 | strike: int, index of column containing strike price of option chain
62 | option_type: int, index of column containing option type of option chain
63 | bid: int, index of column containing bid price of option chain
64 | ask: int, index of column containing ask price of option chain
65 |
66 | Returns:
67 | DataFrame: A dataframe of option chains with standardized columns
68 |
69 | """
70 | params = {**default_kwargs, **kwargs}
71 |
72 | column_mapping = [
73 | (params["underlying_symbol"], "underlying_symbol"),
74 | (params["underlying_price"], "underlying_price"),
75 | (params["option_type"], "option_type"),
76 | (params["expiration"], "expiration"),
77 | (params["quote_date"], "quote_date"),
78 | (params["strike"], "strike"),
79 | (params["bid"], "bid"),
80 | (params["ask"], "ask"),
81 | ]
82 |
83 | return (
84 | pd.read_csv(file_path)
85 | .pipe(_standardize_cols, column_mapping)
86 | .pipe(_trim_cols, column_mapping)
87 | .pipe(_infer_date_cols)
88 | .pipe(_trim_dates, params["start_date"], params["end_date"])
89 | )
90 |
--------------------------------------------------------------------------------
/optopsy/definitions.py:
--------------------------------------------------------------------------------
1 | # columns of options after evaluation
2 | evaluated_cols = [
3 | "underlying_symbol",
4 | "option_type",
5 | "expiration",
6 | "dte_entry",
7 | "strike",
8 | "otm_pct_entry",
9 | "underlying_price_entry",
10 | "underlying_price_exit",
11 | "entry",
12 | "exit",
13 | ]
14 |
15 | # columns of dataframe after generating strategy
16 | single_strike_internal_cols = [
17 | "underlying_symbol",
18 | "underlying_price_entry",
19 | "option_type",
20 | "expiration",
21 | "dte_entry",
22 | "strike",
23 | "entry",
24 | "exit",
25 | "pct_change",
26 | ]
27 |
28 |
29 | straddle_internal_cols = [
30 | "underlying_symbol",
31 | "underlying_price_entry",
32 | "expiration",
33 | "dte_entry",
34 | "option_type_leg1",
35 | "option_type_leg2",
36 | "strike",
37 | "total_entry_cost",
38 | "total_exit_proceeds",
39 | "pct_change",
40 | ]
41 |
42 |
43 | double_strike_internal_cols = [
44 | "underlying_symbol",
45 | "underlying_price_entry_leg1",
46 | "expiration",
47 | "dte_entry",
48 | "option_type_leg1",
49 | "strike_leg1",
50 | "option_type_leg2",
51 | "strike_leg2",
52 | "total_entry_cost",
53 | "total_exit_proceeds",
54 | "pct_change",
55 | ]
56 |
57 | triple_strike_internal_cols = [
58 | "underlying_symbol",
59 | "underlying_price_entry",
60 | "expiration",
61 | "dte_entry",
62 | "option_type_leg1",
63 | "strike_leg1",
64 | "option_type_leg2",
65 | "strike_leg2",
66 | "option_type_leg3",
67 | "strike_leg3",
68 | "entry",
69 | "exit",
70 | "long_profit",
71 | "short_profit",
72 | "long_pct_change",
73 | "short_pct_change",
74 | ]
75 |
76 | quadruple_strike_internal_cols = [
77 | "underlying_symbol",
78 | "underlying_price_entry",
79 | "expiration",
80 | "dte_entry",
81 | "dte_range",
82 | "option_type_leg1",
83 | "strike_leg1",
84 | "option_type_leg2",
85 | "strike_leg2",
86 | "option_type_leg3",
87 | "strike_leg3",
88 | "option_type_leg4",
89 | "strike_leg4",
90 | "entry",
91 | "exit",
92 | "long_profit",
93 | "short_profit",
94 | "long_pct_change",
95 | "short_pct_change",
96 | ]
97 |
98 | # base columns of dataframe after aggregation(minus the calculated columns)
99 | single_strike_external_cols = ["dte_range", "otm_pct_range"]
100 | double_strike_external_cols = ["dte_range", "otm_pct_range_leg1", "otm_pct_range_leg2"]
101 | triple_strike_external_cols = [
102 | "dte_range",
103 | "otm_pct_range_leg1",
104 | "otm_pct_range_leg2",
105 | "otm_pct_range_leg3",
106 | ]
107 | quadruple_strike_external_cols = [
108 | "dte_range",
109 | "otm_pct_range_leg1",
110 | "otm_pct_range_leg2",
111 | "otm_pct_range_leg3",
112 | "otm_pct_range_leg4",
113 | ]
114 |
--------------------------------------------------------------------------------
/optopsy/rules.py:
--------------------------------------------------------------------------------
1 | def _rule_non_overlapping_strike(data, leg_def):
2 | leg_count = len(leg_def)
3 | if leg_count == 1:
4 | return data
5 |
6 | query = " & ".join(
7 | [f"strike_leg{leg + 1} > strike_leg{leg}" for leg in range(1, leg_count)]
8 | )
9 |
10 | return data.query(query)
11 |
--------------------------------------------------------------------------------
/optopsy/strategies.py:
--------------------------------------------------------------------------------
1 | from .core import _calls, _puts, _process_strategy
2 | from .definitions import (
3 | single_strike_external_cols,
4 | single_strike_internal_cols,
5 | double_strike_external_cols,
6 | double_strike_internal_cols,
7 | straddle_internal_cols,
8 | )
9 | from .rules import _rule_non_overlapping_strike
10 | from enum import Enum
11 |
12 | default_kwargs = {
13 | "dte_interval": 7,
14 | "max_entry_dte": 90,
15 | "exit_dte": 0,
16 | "otm_pct_interval": 0.05,
17 | "max_otm_pct": 0.5,
18 | "min_bid_ask": 0.05,
19 | "drop_nan": True,
20 | "raw": False,
21 | }
22 |
23 |
24 | class Side(Enum):
25 | long = 1
26 | short = -1
27 |
28 |
29 | def _singles(data, leg_def, **kwargs):
30 | params = {**default_kwargs, **kwargs}
31 | return _process_strategy(
32 | data,
33 | internal_cols=single_strike_internal_cols,
34 | external_cols=single_strike_external_cols,
35 | leg_def=leg_def,
36 | params=params,
37 | )
38 |
39 |
40 | def _straddles(data, leg_def, **kwargs):
41 | params = {**default_kwargs, **kwargs}
42 |
43 | return _process_strategy(
44 | data,
45 | internal_cols=straddle_internal_cols,
46 | external_cols=single_strike_external_cols,
47 | leg_def=leg_def,
48 | join_on=[
49 | "underlying_symbol",
50 | "expiration",
51 | "strike",
52 | "dte_entry",
53 | "dte_range",
54 | "otm_pct_range",
55 | "underlying_price_entry",
56 | ],
57 | params=params,
58 | )
59 |
60 |
61 | def _strangles(data, leg_def, **kwargs):
62 | params = {**default_kwargs, **kwargs}
63 | return _process_strategy(
64 | data,
65 | internal_cols=double_strike_internal_cols,
66 | external_cols=double_strike_external_cols,
67 | leg_def=leg_def,
68 | rules=_rule_non_overlapping_strike,
69 | join_on=["underlying_symbol", "expiration", "dte_entry", "dte_range"],
70 | params=params,
71 | )
72 |
73 |
74 | def _call_spread(data, leg_def, **kwargs):
75 | params = {**default_kwargs, **kwargs}
76 | return _process_strategy(
77 | data,
78 | internal_cols=double_strike_internal_cols,
79 | external_cols=double_strike_external_cols,
80 | leg_def=leg_def,
81 | rules=_rule_non_overlapping_strike,
82 | join_on=["underlying_symbol", "expiration", "dte_entry", "dte_range"],
83 | params=params,
84 | )
85 |
86 |
87 | def _put_spread(data, leg_def, **kwargs):
88 | params = {**default_kwargs, **kwargs}
89 | return _process_strategy(
90 | data,
91 | internal_cols=double_strike_internal_cols,
92 | external_cols=double_strike_external_cols,
93 | leg_def=leg_def,
94 | rules=_rule_non_overlapping_strike,
95 | join_on=["underlying_symbol", "expiration", "dte_entry", "dte_range"],
96 | params=params,
97 | )
98 |
99 |
100 | def long_calls(data, **kwargs):
101 | return _singles(data, [(Side.long, _calls)], **kwargs)
102 |
103 |
104 | def long_puts(data, **kwargs):
105 | return _singles(data, [(Side.long, _puts)], **kwargs)
106 |
107 |
108 | def short_calls(data, **kwargs):
109 | return _singles(data, [(Side.short, _calls)], **kwargs)
110 |
111 |
112 | def short_puts(data, **kwargs):
113 | return _singles(data, [(Side.short, _puts)], **kwargs)
114 |
115 |
116 | def long_straddles(data, **kwargs):
117 | return _straddles(data, [(Side.long, _puts), (Side.long, _calls)], **kwargs)
118 |
119 |
120 | def short_straddles(data, **kwargs):
121 | return _straddles(data, [(Side.short, _puts), (Side.short, _calls)], **kwargs)
122 |
123 |
124 | def long_strangles(data, **kwargs):
125 | return _strangles(data, [(Side.long, _puts), (Side.long, _calls)], **kwargs)
126 |
127 |
128 | def short_strangles(data, **kwargs):
129 | return _strangles(data, [(Side.short, _puts), (Side.short, _calls)], **kwargs)
130 |
131 |
132 | def long_call_spread(data, **kwargs):
133 | return _call_spread(data, [(Side.long, _calls), (Side.short, _calls)], **kwargs)
134 |
135 |
136 | def short_call_spread(data, **kwargs):
137 | return _call_spread(data, [(Side.short, _calls), (Side.long, _calls)], **kwargs)
138 |
139 |
140 | def long_put_spread(data, **kwargs):
141 | return _put_spread(data, [(Side.short, _puts), (Side.long, _puts)], **kwargs)
142 |
143 |
144 | def short_put_spread(data, **kwargs):
145 | return _put_spread(data, [(Side.long, _puts), (Side.short, _puts)], **kwargs)
146 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | # It is recommended to install Miniconda3 for Python 3.6.1 and Pandas
2 | pandas>=0.23.1
3 | pytest>=3.10.0
4 | numpy>=1.14.3
5 |
--------------------------------------------------------------------------------
/samples/data/sample_spx_data.csv:
--------------------------------------------------------------------------------
1 | underlying,underlying_last, exchange,optionroot,optionext,type,expiration,quotedate,strike,last,bid,ask,volume,openinterest,impliedvol,delta,gamma,theta,vega,optionalias
2 | SPX,1921.42,*,SPX151016C00400000,,call,10/16/2015,10/01/2015,400,0,1518.7,1525.2,0,0,0.2589,1,0,-1.2854,0,SPX151016C00400000
3 | SPX,1921.42,*,SPX151016C00500000,,call,10/16/2015,10/01/2015,500,0,1418.8,1425.2,0,0,0.2589,1,0,-1.6068,0,SPX151016C00500000
4 | SPX,1921.42,*,SPX151016C00600000,,call,10/16/2015,10/01/2015,600,0,1318.8,1325.2,0,0,0.2589,1,0,-1.9282,0,SPX151016C00600000
5 | SPX,1921.42,*,SPX151016C00700000,,call,10/16/2015,10/01/2015,700,0,1218.8,1225.3,0,0,0.2589,1,0,-2.2495,0,SPX151016C00700000
6 | SPX,1921.42,*,SPX151016C00750000,,call,10/16/2015,10/01/2015,750,0,1168.8,1175.3,0,0,0.2589,1,0,-2.4102,0,SPX151016C00750000
7 |
--------------------------------------------------------------------------------
/samples/spx_singles_example.py:
--------------------------------------------------------------------------------
1 | import os
2 | import optopsy as op
3 | import tabulate as tb
4 |
5 |
6 | def filepath():
7 | curr_file = os.path.abspath(os.path.dirname(__file__))
8 |
9 | # for demo purposes only, download your copy of data from sites such as:
10 | # CBOE Datashop: https://datashop.cboe.com/
11 | # HistoricalOptionData: https://www.historicaloptiondata.com/
12 | # DeltaNeutral: http://www.deltaneutral.com/
13 |
14 | # following file was downloaded from: http://www.deltaneutral.com/files/Sample_SPX_20151001_to_20151030.csv
15 | return os.path.join(curr_file, "./data/Sample_SPX_20151001_to_20151030.csv")
16 |
17 |
18 | def run_strategy():
19 |
20 | # indices for the column params are 0-indexed
21 | spx_data = op.csv_data(
22 | filepath(),
23 | underlying_symbol=0,
24 | underlying_price=1,
25 | option_type=5,
26 | expiration=6,
27 | quote_date=7,
28 | strike=8,
29 | bid=10,
30 | ask=11,
31 | )
32 |
33 | # Backtest all single calls(long) on the SPX
34 |
35 | # All public optopsy functions return a regular Pandas DataFrame so you can use
36 | # regular pandas functions as you see fit to analyse the dataset
37 | long_single_calls = op.long_calls(spx_data).round(2)
38 |
39 | print("Statistics for SPX long calls from 2015-10-01 to 2015-10-30 \n")
40 | print(
41 | tb.tabulate(
42 | long_single_calls,
43 | headers=long_single_calls.columns,
44 | tablefmt="github",
45 | numalign="right",
46 | )
47 | )
48 |
49 |
50 | if __name__ == "__main__":
51 | import timeit
52 |
53 | start = timeit.default_timer()
54 |
55 | # All the program statements
56 | run_strategy()
57 |
58 | stop = timeit.default_timer()
59 | execution_time = round(stop - start, 0)
60 |
61 | print("Program Executed in " + str(execution_time)) # It returns time in seconds
62 |
--------------------------------------------------------------------------------
/samples/spx_straddles_example.py:
--------------------------------------------------------------------------------
1 | import os
2 | import optopsy as op
3 | import tabulate as tb
4 |
5 |
6 | def filepath():
7 | curr_file = os.path.abspath(os.path.dirname(__file__))
8 |
9 | # for demo purposes only, download your copy of data from sites such as:
10 | # CBOE Datashop: https://datashop.cboe.com/
11 | # HistoricalOptionData: https://www.historicaloptiondata.com/
12 | # DeltaNeutral: http://www.deltaneutral.com/
13 |
14 | # following file was downloaded from: http://www.deltaneutral.com/files/Sample_SPX_20151001_to_20151030.csv
15 | return os.path.join(curr_file, "./data/Sample_SPX_20151001_to_20151030.csv")
16 |
17 |
18 | def run_strategy():
19 |
20 | # indices for the column params are 0-indexed
21 | spx_data = op.csv_data(
22 | filepath(),
23 | underlying_symbol=0,
24 | underlying_price=1,
25 | option_type=5,
26 | expiration=6,
27 | quote_date=7,
28 | strike=8,
29 | bid=10,
30 | ask=11,
31 | )
32 |
33 | # Backtest all straddes(long) on the SPX
34 |
35 | # All public optopsy functions return a regular Pandas DataFrame so you can use
36 | # regular pandas functions as you see fit to analyse the dataset
37 | straddles = op.long_straddles(spx_data).round(2)
38 |
39 | print("Statistics for SPX straddles from 2015-10-01 to 2015-10-30 \n")
40 | print(
41 | tb.tabulate(
42 | straddles,
43 | headers=straddles.columns,
44 | tablefmt="github",
45 | numalign="right",
46 | )
47 | )
48 |
49 |
50 | if __name__ == "__main__":
51 | import timeit
52 |
53 | start = timeit.default_timer()
54 |
55 | # All the program statements
56 | run_strategy()
57 |
58 | stop = timeit.default_timer()
59 | execution_time = round(stop - start, 0)
60 |
61 | print("Program Executed in " + str(execution_time)) # It returns time in seconds
62 |
--------------------------------------------------------------------------------
/samples/spx_strangles_example.py:
--------------------------------------------------------------------------------
1 | import os
2 | import optopsy as op
3 | import tabulate as tb
4 |
5 |
6 | def filepath():
7 | curr_file = os.path.abspath(os.path.dirname(__file__))
8 |
9 | # for demo purposes only, download your copy of data from sites such as:
10 | # CBOE Datashop: https://datashop.cboe.com/
11 | # HistoricalOptionData: https://www.historicaloptiondata.com/
12 | # DeltaNeutral: http://www.deltaneutral.com/
13 |
14 | # following file was downloaded from: http://www.deltaneutral.com/files/Sample_SPX_20151001_to_20151030.csv
15 | return os.path.join(curr_file, "./data/Sample_SPX_20151001_to_20151030.csv")
16 |
17 |
18 | def run_strategy():
19 |
20 | # indices for the column params are 0-indexed
21 | spx_data = op.csv_data(
22 | filepath(),
23 | underlying_symbol=0,
24 | underlying_price=1,
25 | option_type=5,
26 | expiration=6,
27 | quote_date=7,
28 | strike=8,
29 | bid=10,
30 | ask=11,
31 | )
32 |
33 | # Backtest all strangles(long) on the SPX
34 |
35 | # All public optopsy functions return a regular Pandas DataFrame so you can use
36 | # regular pandas functions as you see fit to analyse the dataset
37 | strangles = op.long_strangles(spx_data).round(2)
38 |
39 | print("Statistics for SPX strangles from 2015-10-01 to 2015-10-30 \n")
40 | print(
41 | tb.tabulate(
42 | strangles,
43 | headers=strangles.columns,
44 | tablefmt="github",
45 | numalign="right",
46 | )
47 | )
48 |
49 |
50 | if __name__ == "__main__":
51 | import timeit
52 |
53 | start = timeit.default_timer()
54 |
55 | # All the program statements
56 | run_strategy()
57 |
58 | stop = timeit.default_timer()
59 | execution_time = round(stop - start, 0)
60 |
61 | print("Program Executed in " + str(execution_time)) # It returns time in seconds
62 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 |
3 | setup(
4 | name="optopsy",
5 | description="A nimble backtesting and statistics library for options strategies",
6 | long_description=open("README.md").read(),
7 | long_description_content_type="text/markdown",
8 | version="2.0.1",
9 | url="https://github.com/michaelchu/optopsy",
10 | author="Michael Chu",
11 | author_email="mchchu88@gmail.com",
12 | license="GPL-3.0-or-later",
13 | classifiers=[
14 | "Operating System :: OS Independent",
15 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)",
16 | "Programming Language :: Python :: 3.6",
17 | ],
18 | packages=["optopsy"],
19 | install_requires=["pandas", "numpy"],
20 | )
21 |
--------------------------------------------------------------------------------
/tests/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/michaelchu/optopsy/b1cf036d7e6f420c335384fbd8db02b6ad0e281c/tests/__init__.py
--------------------------------------------------------------------------------
/tests/conftest.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | import pandas as pd
3 | import datetime as datetime
4 |
5 |
6 | @pytest.fixture(scope="module")
7 | def data():
8 | exp_date = datetime.datetime(2018, 1, 31)
9 | quote_dates = [datetime.datetime(2018, 1, 1), datetime.datetime(2018, 1, 31)]
10 | cols = [
11 | "underlying_symbol",
12 | "underlying_price",
13 | "option_type",
14 | "expiration",
15 | "quote_date",
16 | "strike",
17 | "bid",
18 | "ask",
19 | ]
20 | d = [
21 | ["SPX", 213.93, "call", exp_date, quote_dates[0], 212.5, 7.35, 7.45],
22 | ["SPX", 213.93, "call", exp_date, quote_dates[0], 215.0, 6.00, 6.05],
23 | ["SPX", 213.93, "put", exp_date, quote_dates[0], 212.5, 5.70, 5.80],
24 | ["SPX", 213.93, "put", exp_date, quote_dates[0], 215.0, 7.10, 7.20],
25 | ["SPX", 220, "call", exp_date, quote_dates[1], 212.5, 7.45, 7.55],
26 | ["SPX", 220, "call", exp_date, quote_dates[1], 215.0, 4.96, 5.05],
27 | ["SPX", 220, "put", exp_date, quote_dates[1], 212.5, 0.0, 0.0],
28 | ["SPX", 220, "put", exp_date, quote_dates[1], 215.0, 0.0, 0.0],
29 | ]
30 | return pd.DataFrame(data=d, columns=cols)
31 |
--------------------------------------------------------------------------------
/tests/test_checks.py:
--------------------------------------------------------------------------------
1 | import pytest
2 | import optopsy.checks as op
3 |
4 |
5 | def test_check_positive_integer():
6 | with pytest.raises(ValueError):
7 | op._check_positive_integer("some key", -1)
8 | op._check_positive_integer("some key", 0)
9 | op._check_positive_integer("some key", 1.0)
10 |
11 | assert op._check_positive_integer("some key", 1) is None
12 |
13 |
14 | def test_check_positive_integer_inclusive():
15 | with pytest.raises(ValueError):
16 | op._check_positive_integer_inclusive("some key", -1)
17 | op._check_positive_integer_inclusive("some key", 1.0)
18 |
19 | assert op._check_positive_integer_inclusive("some key", 1) is None
20 | assert op._check_positive_integer_inclusive("some key", 0) is None
21 |
22 |
23 | def test_check_positive_float():
24 | with pytest.raises(ValueError):
25 | op._check_positive_float("some key", -1)
26 | op._check_positive_float("some key", 0)
27 | op._check_positive_float("some key", 1)
28 |
29 | assert op._check_positive_float("some key", 1.0) is None
30 |
31 |
32 | def test_check_side():
33 | with pytest.raises(ValueError):
34 | op._check_side("some key", "invalid")
35 |
36 | assert op._check_side("some key", "short") is None
37 | assert op._check_side("some key", "long") is None
38 |
39 |
40 | def test_check_bool_type():
41 | with pytest.raises(ValueError):
42 | op._check_bool_type("some key", "invalid")
43 |
44 | assert op._check_bool_type("some key", True) is None
45 | assert op._check_bool_type("some key", False) is None
46 |
47 |
48 | def test_check_list_type():
49 | with pytest.raises(ValueError):
50 | op._check_list_type("some key", "invalid")
51 |
52 | assert op._check_list_type("some key", []) is None
53 |
54 |
55 | def test_check_data_types():
56 | import pandas as pd
57 |
58 | invalid_cols = {"some_col": ["some val"]}
59 | invalid_types = {"underlying_symbol": [123]}
60 |
61 | with pytest.raises(ValueError, match="Expected column"):
62 | op._check_data_types(pd.DataFrame(invalid_cols))
63 |
64 | with pytest.raises(
65 | ValueError, match="underlying_symbol does not match expected types"
66 | ):
67 | op._check_data_types(pd.DataFrame(invalid_types))
68 |
--------------------------------------------------------------------------------
/tests/test_data/data.csv:
--------------------------------------------------------------------------------
1 | col1,col2,col3,col4,col5,col6,col7,col8,col9
2 | SPX,359.69,call,1/20/1990,1/2/1990,225,135.5,135.5,0
3 | SPX,359.69,call,1/20/2000,1/2/2000,320,40.9,40.9,0
4 | SPX,359.69,call,1/20/2010,1/2/2010,325,35.9,35.9,0
5 | SPX,359.69,call,1/20/2020,1/2/2020,330,30.9,30.9,0
--------------------------------------------------------------------------------
/tests/test_datafeeds.py:
--------------------------------------------------------------------------------
1 | import os
2 | from datetime import datetime
3 | import optopsy as op
4 |
5 |
6 | def filepath():
7 | curr_file = os.path.abspath(os.path.dirname(__file__))
8 | return os.path.join(curr_file, "./test_data/data.csv")
9 |
10 |
11 | def test_import_csv_file():
12 | data = op.datafeeds.csv_data(
13 | filepath(),
14 | underlying_symbol=0,
15 | underlying_price=1,
16 | option_type=2,
17 | expiration=3,
18 | quote_date=4,
19 | strike=5,
20 | bid=6,
21 | ask=7,
22 | )
23 |
24 | expected_columns = [
25 | "underlying_symbol",
26 | "underlying_price",
27 | "option_type",
28 | "expiration",
29 | "quote_date",
30 | "strike",
31 | "bid",
32 | "ask",
33 | ]
34 | assert list(data.columns) == expected_columns
35 | assert not data.empty
36 |
37 |
38 | def test_import_csv_with_date_range():
39 | data = op.datafeeds.csv_data(
40 | filepath(),
41 | start_date=datetime(1990, 1, 1),
42 | end_date=datetime(1990, 12, 31),
43 | underlying_symbol=0,
44 | underlying_price=1,
45 | option_type=2,
46 | expiration=3,
47 | quote_date=4,
48 | strike=5,
49 | bid=6,
50 | ask=7,
51 | )
52 | assert len(data) == 1
53 | assert data.iloc[0]["expiration"] == datetime(1990, 1, 20)
54 |
55 |
56 | def test_import_csv_with_start_date():
57 | data = op.datafeeds.csv_data(
58 | filepath(),
59 | start_date=datetime(2000, 1, 1),
60 | underlying_symbol=0,
61 | underlying_price=1,
62 | option_type=2,
63 | expiration=3,
64 | quote_date=4,
65 | strike=5,
66 | bid=6,
67 | ask=7,
68 | )
69 | assert len(data) == 3
70 | assert data.iloc[0]["expiration"] == datetime(2000, 1, 20)
71 | assert data.iloc[1]["expiration"] == datetime(2010, 1, 20)
72 | assert data.iloc[2]["expiration"] == datetime(2020, 1, 20)
73 |
74 |
75 | def test_import_csv_with_end_date():
76 | data = op.datafeeds.csv_data(
77 | filepath(),
78 | end_date=datetime(2010, 1, 1),
79 | underlying_symbol=0,
80 | underlying_price=1,
81 | option_type=2,
82 | expiration=3,
83 | quote_date=4,
84 | strike=5,
85 | bid=6,
86 | ask=7,
87 | )
88 | assert len(data) == 2
89 | assert data.iloc[0]["expiration"] == datetime(1990, 1, 20)
90 | assert data.iloc[1]["expiration"] == datetime(2000, 1, 20)
91 |
92 |
93 | def test_import_csv_with_no_date_range():
94 | data = op.datafeeds.csv_data(
95 | filepath(),
96 | underlying_symbol=0,
97 | underlying_price=1,
98 | option_type=2,
99 | expiration=3,
100 | quote_date=4,
101 | strike=5,
102 | bid=6,
103 | ask=7,
104 | )
105 | assert len(data) == 4
106 | assert data.iloc[0]["expiration"] == datetime(1990, 1, 20)
107 | assert data.iloc[1]["expiration"] == datetime(2000, 1, 20)
108 | assert data.iloc[2]["expiration"] == datetime(2010, 1, 20)
109 | assert data.iloc[3]["expiration"] == datetime(2020, 1, 20)
110 |
--------------------------------------------------------------------------------
/tests/test_rules.py:
--------------------------------------------------------------------------------
1 | from optopsy.strategies import Side
2 | from optopsy.core import _calls
3 | from optopsy.rules import _rule_non_overlapping_strike
4 |
5 |
6 | def test_no_overlapping_strikes(data):
7 | leg_def = [(Side.long, _calls)]
8 | result = _rule_non_overlapping_strike(_calls(data), leg_def)
9 | assert len(result) == 4
10 | assert "call" in list(result["option_type"].values)
11 |
--------------------------------------------------------------------------------
/tests/test_strategies.py:
--------------------------------------------------------------------------------
1 | from optopsy.strategies import *
2 | from optopsy.definitions import *
3 |
4 |
5 | describe_cols = [
6 | "count",
7 | "mean",
8 | "std",
9 | "min",
10 | "25%",
11 | "50%",
12 | "75%",
13 | "max",
14 | ]
15 |
16 |
17 | def test_single_long_calls_raw(data):
18 | results = long_calls(data, raw=True)
19 | assert len(results) == 2
20 | assert list(results.columns) == single_strike_internal_cols
21 | assert "call" in list(results["option_type"].values)
22 | assert round(results.iloc[0]["pct_change"], 2) == 0.01
23 | assert round(results.iloc[1]["pct_change"], 2) == -0.17
24 |
25 |
26 | def test_single_long_puts_raw(data):
27 | results = long_puts(data, raw=True)
28 | assert len(results) == 2
29 | assert list(results.columns) == single_strike_internal_cols
30 | assert "put" in list(results["option_type"].values)
31 | assert round(results.iloc[0]["pct_change"], 2) == -1
32 | assert round(results.iloc[1]["pct_change"], 2) == -1
33 |
34 |
35 | def test_single_short_calls_raw(data):
36 | results = short_calls(data, raw=True)
37 | assert len(results) == 2
38 | assert list(results.columns) == single_strike_internal_cols
39 | assert "call" in list(results["option_type"].values)
40 | assert round(results.iloc[0]["pct_change"], 2) == 0.01
41 | assert round(results.iloc[1]["pct_change"], 2) == -0.17
42 |
43 |
44 | def test_single_short_puts_raw(data):
45 | results = short_puts(data, raw=True)
46 | assert len(results) == 2
47 | assert list(results.columns) == single_strike_internal_cols
48 | assert "put" in list(results["option_type"].values)
49 | assert round(results.iloc[0]["pct_change"], 2) == -1
50 | assert round(results.iloc[1]["pct_change"], 2) == -1
51 |
52 |
53 | def test_singles_long_calls(data):
54 | results = long_calls(data)
55 | assert len(results) == 1
56 | assert results.iloc[0]["count"] == 2.0
57 | assert round(results.iloc[0]["mean"], 2) == -0.08
58 | assert list(results.columns) == single_strike_external_cols + describe_cols
59 |
60 |
61 | def test_singles_long_puts(data):
62 | results = long_puts(data)
63 | assert len(results) == 1
64 | assert results.iloc[0]["count"] == 2.0
65 | assert round(results.iloc[0]["mean"], 2) == -1.0
66 | assert list(results.columns) == single_strike_external_cols + describe_cols
67 |
68 |
69 | def test_singles_short_calls(data):
70 | results = short_calls(data)
71 | assert len(results) == 1
72 | assert results.iloc[0]["count"] == 2.0
73 | assert round(results.iloc[0]["mean"], 2) == -0.08
74 | assert list(results.columns) == single_strike_external_cols + describe_cols
75 |
76 |
77 | def test_singles_short_puts(data):
78 | results = short_puts(data)
79 | assert len(results) == 1
80 | assert results.iloc[0]["count"] == 2.0
81 | assert round(results.iloc[0]["mean"], 2) == -1.0
82 | assert list(results.columns) == single_strike_external_cols + describe_cols
83 |
84 |
85 | def test_straddles_long_raw(data):
86 | results = long_straddles(data, raw=True)
87 | assert list(results.columns) == straddle_internal_cols
88 | assert results.iloc[0]["option_type_leg1"] == "put"
89 | assert results.iloc[0]["option_type_leg2"] == "call"
90 | assert round(results.iloc[0]["pct_change"], 2) == -0.43
91 | assert round(results.iloc[1]["pct_change"], 2) == -0.62
92 |
93 |
94 | def test_straddles_short_raw(data):
95 | results = short_straddles(data, raw=True)
96 | assert list(results.columns) == straddle_internal_cols
97 | assert results.iloc[0]["option_type_leg1"] == "put"
98 | assert results.iloc[0]["option_type_leg2"] == "call"
99 | assert round(results.iloc[0]["pct_change"], 2) == 0.43
100 | assert round(results.iloc[1]["pct_change"], 2) == 0.62
101 |
102 |
103 | def test_long_straddles(data):
104 | results = long_straddles(data)
105 | assert len(results) == 1
106 | assert results.iloc[0]["count"] == 2.0
107 | assert round(results.iloc[0]["mean"], 2) == -0.52
108 | assert list(results.columns) == single_strike_external_cols + describe_cols
109 |
110 |
111 | def test_short_straddles(data):
112 | results = short_straddles(data)
113 | assert len(results) == 1
114 | assert results.iloc[0]["count"] == 2.0
115 | assert round(results.iloc[0]["mean"], 2) == 0.52
116 | assert list(results.columns) == single_strike_external_cols + describe_cols
117 |
118 |
119 | def test_strangles_long_raw(data):
120 | results = long_strangles(data, raw=True)
121 | assert len(results) == 1
122 | assert list(results.columns) == double_strike_internal_cols
123 | assert results.iloc[0]["option_type_leg1"] == "put"
124 | assert results.iloc[0]["option_type_leg2"] == "call"
125 | assert round(results.iloc[0]["pct_change"], 2) == -0.57
126 |
127 |
128 | def test_strangles_short_raw(data):
129 | results = short_strangles(data, raw=True)
130 | assert len(results) == 1
131 | assert list(results.columns) == double_strike_internal_cols
132 | assert results.iloc[0]["option_type_leg1"] == "put"
133 | assert results.iloc[0]["option_type_leg2"] == "call"
134 | assert round(results.iloc[0]["pct_change"], 2) == 0.57
135 |
136 |
137 | def test_long_strangles(data):
138 | results = long_strangles(data)
139 | assert len(results) == 1
140 | assert results.iloc[0]["count"] == 1.0
141 | assert round(results.iloc[0]["mean"], 2) == -0.57
142 | assert list(results.columns) == double_strike_external_cols + describe_cols
143 |
144 |
145 | def test_short_strangles(data):
146 | results = short_strangles(data)
147 | assert len(results) == 1
148 | assert results.iloc[0]["count"] == 1.0
149 | assert round(results.iloc[0]["mean"], 2) == 0.57
150 | assert list(results.columns) == double_strike_external_cols + describe_cols
151 |
152 |
153 | def test_long_call_spread_raw(data):
154 | results = long_call_spread(data, raw=True)
155 | assert len(results) == 1
156 | assert list(results.columns) == double_strike_internal_cols
157 | assert results.iloc[0]["option_type_leg1"] == "call"
158 | assert results.iloc[0]["option_type_leg2"] == "call"
159 | assert round(results.iloc[0]["pct_change"], 2) == 0.81
160 |
161 |
162 | def test_long_put_spread_raw(data):
163 | results = long_put_spread(data, raw=True)
164 | assert len(results) == 1
165 | assert list(results.columns) == double_strike_internal_cols
166 | assert results.iloc[0]["option_type_leg1"] == "put"
167 | assert results.iloc[0]["option_type_leg2"] == "put"
168 | assert round(results.iloc[0]["pct_change"], 2) == -1
169 |
170 |
171 | def test_short_call_spread_raw(data):
172 | results = short_call_spread(data, raw=True)
173 | assert len(results) == 1
174 | assert list(results.columns) == double_strike_internal_cols
175 | assert results.iloc[0]["option_type_leg1"] == "call"
176 | assert results.iloc[0]["option_type_leg2"] == "call"
177 | assert round(results.iloc[0]["pct_change"], 2) == -0.81
178 |
179 |
180 | def test_short_put_spread_raw(data):
181 | results = short_put_spread(data, raw=True)
182 | assert len(results) == 1
183 | assert list(results.columns) == double_strike_internal_cols
184 | assert results.iloc[0]["option_type_leg1"] == "put"
185 | assert results.iloc[0]["option_type_leg2"] == "put"
186 | assert round(results.iloc[0]["pct_change"], 2) == 1
187 |
--------------------------------------------------------------------------------