diff --git a/.travis.yml b/.travis.yml index 9dc836dc..0f6967bd 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,10 +1,10 @@ language: python -python: - - '3.6' - # setup.py reading README breaks this? - # - pypy - # no pandas support - # - nightly + +matrix: + include: + - python: 3.7 + dist: xenial + sudo: required before_install: - sudo apt-get -qq update diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..94a9ed02 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/Pipfile b/Pipfile index f061f1d3..47bf04bd 100644 --- a/Pipfile +++ b/Pipfile @@ -8,7 +8,7 @@ name = "pypi" Cython = "*" # matham's next-gen async port of kivy Kivy = {git = "git://github.com/matham/kivy.git", ref = "async-loop"} -tractor = {git = "git://github.com/tgoodlet/tractor.git", ref = "master"} +tractor = {git = "git://github.com/tgoodlet/tractor.git"} pdbpp = "*" msgpack = "*" trio = "*" diff --git a/Pipfile.lock b/Pipfile.lock index c6dc94f0..19afd44b 100644 --- a/Pipfile.lock +++ b/Pipfile.lock @@ -1,7 +1,7 @@ { "_meta": { "hash": { - "sha256": "336e710094a9a95325fc8b1c952ae1080c574fff3909d817a731b82d2af890d6" + "sha256": "775dc298007b9ceedd0a9d2e3b4b5b9cb5d11d5db3ed0700e30ed1e646459e45" }, "pipfile-spec": 6, "requires": {}, @@ -16,32 +16,30 @@ "default": { "asks": { "hashes": [ - "sha256:c3fc1115dfeb414ef0863da6f60f02aea7487f92f76b645738774bf93e8577de" + "sha256:1679e5bd1dfa6c5d2220bdf2b8921c9c0d063d08370a7c66b9e167113681406f" ], - "markers": "python_version >= '3.5.2'", - "version": "==2.0.0" + "version": "==2.2.0" }, "async-generator": { "hashes": [ "sha256:01c7bf666359b4967d2cda0000cc2e4af16a0ae098cbffcb8472fb9e8ad6585b", "sha256:6ebb3d106c12920aaae42ccb6f787ef5eefdcdd166ea3d628fa8476abe712144" ], - "markers": "python_version >= '3.5'", "version": "==1.10" }, "attrs": { "hashes": [ - "sha256:4b90b09eeeb9b88c35bc642cbac057e45a5fd85367b985bd2809c62b7b939265", - "sha256:e0d0eb91441a3b53dab4d9b743eafc1ac44476296a2053b6ca3af0b139faf87b" + "sha256:10cbf6e27dbce8c30807caf056c8eb50917e0eaafe86347671b57254006c3e69", + "sha256:ca4be454458f9dec299268d472aaa5a11f67a4ff70093396e1ceae9c76cf4bbb" ], - "version": "==18.1.0" + "version": "==18.2.0" }, "click": { "hashes": [ - "sha256:29f99fc6125fbc931b758dc053b3114e55c77a6e4c6c3a2674a2dc986016381d", - "sha256:f15516df478d5a56180fbf80e68f206010e6d160fc39fa508b65e035fd75130b" + "sha256:2335065e6395b9e67ca716de5f7526736bfa6ceead690adf616d925bdc622b13", + "sha256:5b94b49521f6456670fdb30cd82a4eca9412788a93fa6dd6df72c94d5a8ff2d7" ], - "version": "==6.7" + "version": "==7.0" }, "colorlog": { "hashes": [ @@ -52,38 +50,37 @@ }, "cython": { "hashes": [ - "sha256:022592d419fc754509d0e0461eb2958dbaa45fb60d51c8a61778c58994edbe36", - "sha256:07659f4c57582104d9486c071de512fbd7e087a3a630535298442cc0e20a3f5a", - "sha256:13c73e2ffa93a615851e03fad97591954d143b5b62361b9adef81f46a31cd8ef", - "sha256:13eab5a2835a84ff62db343035603044c908d2b3b6eec09d67fdf9970acf7ac9", - "sha256:183b35a48f58862c4ec1e821f07bb7b1156c8c8559c85c32ae086f28947474eb", - "sha256:2f526b0887128bf20ab2acc905a975f62b5a04ab2f63ecbe5a30fc28285d0e0c", - "sha256:32de8637f5e6c5a76667bc7c8fc644bd9314dc19af36db8ce30a0b92ada0f642", - "sha256:4172c183ef4fb2ace6a29cdf7fc9200c5a471a7f775ff691975b774bd9ed3ad2", - "sha256:553956ec06ecbd731ef0c538eb28a5b46bedea7ab89b18237ff28b4b99d65eee", - "sha256:660eeb6870687fd3eda91e00ba4e72220545c254c8c4d967fd0c910f4fbb8cbc", - "sha256:693a8619ef066ece055ed065a15cf440f9d3ebd1bca60e87ea19144833756433", - "sha256:759c799e9ef418f163b5412e295e14c0a48fe3b4dcba9ab8aab69e9f511cfefd", - "sha256:827d3a91b7a7c31ce69e5974496fd9a8ba28eb498b988affb66d0d30de11d934", - "sha256:87e57b5d730cfab225d95e7b23abbc0c6f77598bd66639e93c73ce8afbae6f38", - "sha256:9400e5db8383346b0694a3e794d8bded18a27b21123516dcdf4b79d7ec28e98b", - "sha256:9ec27681c5b1b457aacb1cbda5db04aa28b76da2af6e1e1fd15f233eafe6a0b0", - "sha256:ae4784f040a3313c8bd00c8d04934b7ade63dc59692d8f00a5235be8ed72a445", - "sha256:b2ba8310ebd3c0e0b884d5e95bbd99d467d6af922acd1e44fe4b819839b2150e", - "sha256:b64575241f64f6ec005a4d4137339fb0ba5e156e826db2fdb5f458060d9979e0", - "sha256:c78ad0df75a9fc03ab28ca1b950c893a208c451a18f76796c3e25817d6994001", - "sha256:cdbb917e41220bd3812234dbe59d15391adbc2c5d91ae11a5273aab9e32ba7ec", - "sha256:d2223a80c623e2a8e97953ab945dfaa9385750a494438dcb55562eb1ddd9565a", - "sha256:e22f21cf92a9f8f007a280e3b3462c886d9068132a6c698dec10ad6125e3ca1e", - "sha256:ea5c16c48e561f4a6f6b8c24807494b77a79e156b8133521c400f22ca712101b", - "sha256:ee7a9614d51fe16e32ca5befe72e0808baff481791728449d0b17c8b0fe29eb9", - "sha256:ef86de9299e4ab2ebb129fb84b886bf40b9aced9807c6d6d5f28b46fb905f82c", - "sha256:f3e4860f5458a9875caa3de65e255720c0ed2ce71f0bcdab02497b32104f9db8", - "sha256:fc6c20a8ac22202a779ad4c59756647be0826993d2151a03c015e76d2368ae5f" + "sha256:019008a69e6b7c102f2ed3d733a288d1784363802b437dd2b91e6256b12746da", + "sha256:1441fe19c56c90b8c2159d7b861c31a134d543ef7886fd82a5d267f9f11f35ac", + "sha256:1d1a5e9d6ed415e75a676b72200ad67082242ec4d2d76eb7446da255ae72d3f7", + "sha256:339f5b985de3662b1d6c69991ab46fdbdc736feb4ac903ef6b8c00e14d87f4d8", + "sha256:35bdf3f48535891fee2eaade70e91d5b2cc1ee9fc2a551847c7ec18bce55a92c", + "sha256:3d0afba0aec878639608f013045697fb0969ff60b3aea2daec771ea8d01ad112", + "sha256:42c53786806e24569571a7a24ebe78ec6b364fe53e79a3f27eddd573cacd398f", + "sha256:48b919da89614d201e72fbd8247b5ae8881e296cf968feb5595a015a14c67f1f", + "sha256:49906e008eeb91912654a36c200566392bd448b87a529086694053a280f8af2d", + "sha256:49fc01a7c9c4e3c1784e9a15d162c2cac3990fcc28728227a6f8f0837aabda7c", + "sha256:501b671b639b9ca17ad303f8807deb1d0ff754d1dab106f2607d14b53cb0ff0b", + "sha256:5574574142364804423ab4428bd331a05c65f7ecfd31ac97c936f0c720fe6a53", + "sha256:6092239a772b3c6604be9e94b9ab4f0dacb7452e8ad299fd97eae0611355b679", + "sha256:71ff5c7632501c4f60edb8a24fd0a772e04c5bdca2856d978d04271b63666ef7", + "sha256:7dcf2ad14e25b05eda8bdd104f8c03a642a384aeefd25a5b51deac0826e646fa", + "sha256:8ca3a99f5a7443a6a8f83a5d8fcc11854b44e6907e92ba8640d8a8f7b9085e21", + "sha256:927da3b5710fb705aab173ad630b45a4a04c78e63dcd89411a065b2fe60e4770", + "sha256:94916d1ede67682638d3cc0feb10648ff14dc51fb7a7f147f4fedce78eaaea97", + "sha256:a3e5e5ca325527d312cdb12a4dab8b0459c458cad1c738c6f019d0d8d147081c", + "sha256:a7716a98f0b9b8f61ddb2bae7997daf546ac8fc594be6ba397f4bde7d76bfc62", + "sha256:acf10d1054de92af8d5bfc6620bb79b85f04c98214b4da7db77525bfa9fc2a89", + "sha256:de46ffb67e723975f5acab101c5235747af1e84fbbc89bf3533e2ea93fb26947", + "sha256:df428969154a9a4cd9748c7e6efd18432111fbea3d700f7376046c38c5e27081", + "sha256:f5ebf24b599caf466f9da8c4115398d663b2567b89e92f58a835e9da4f74669f", + "sha256:f79e45d5c122c4fb1fd54029bf1d475cecc05f4ed5b68136b0d6ec268bae68b6", + "sha256:f7a43097d143bd7846ffba6d2d8cd1cc97f233318dbd0f50a235ea01297a096b", + "sha256:fceb8271bc2fd3477094ca157c824e8ea840a7b393e89e766eea9a3b9ce7e0c6", + "sha256:ff919ceb40259f5332db43803aa6c22ff487e86036ce3921ae04b9185efc99a4" ], "index": "pypi", - "markers": "python_version >= '2.6' and python_version != '3.1.*' and python_version != '3.0.*' and python_version != '3.2.*'", - "version": "==0.28.5" + "version": "==0.29" }, "e1839a8": { "editable": true, @@ -136,51 +133,49 @@ }, "multio": { "hashes": [ - "sha256:dcaee4d5d77cde8caf7902c8621aaa192febb384c7b1291fd47cfa41ac0eaebc" + "sha256:e8bce12aa8d2e076d96f4c4b6bfb70c01e0e0af9892f9ffc4ec868854e1b877e" ], - "markers": "python_version >= '3.5.2'", - "version": "==0.2.3" + "version": "==0.2.4" }, "numpy": { "hashes": [ - "sha256:14fb76bde161c87dcec52d91c78f65aa8a23aa2e1530a71f412dabe03927d917", - "sha256:21041014b7529237994a6b578701c585703fbb3b1bea356cdb12a5ea7804241c", - "sha256:24f3bb9a5f6c3936a8ccd4ddfc1210d9511f4aeb879a12efd2e80bec647b8695", - "sha256:34033b581bc01b1135ca2e3e93a94daea7c739f21a97a75cca93e29d9f0c8e71", - "sha256:3fbccb399fe9095b1c1d7b41e7c7867db8aa0d2347fc44c87a7a180cedda112b", - "sha256:50718eea8e77a1bedcc85befd22c8dbf5a24c9d2c0c1e36bbb8d7a38da847eb3", - "sha256:55daf757e5f69aa75b4477cf4511bf1f96325c730e4ad32d954ccb593acd2585", - "sha256:61efc65f325770bbe787f34e00607bc124f08e6c25fdf04723848585e81560dc", - "sha256:62cb836506f40ce2529bfba9d09edc4b2687dd18c56cf4457e51c3e7145402fd", - "sha256:64c6acf5175745fd1b7b7e17c74fdbfb7191af3b378bc54f44560279f41238d3", - "sha256:674ea7917f0657ddb6976bd102ac341bc493d072c32a59b98e5b8c6eaa2d5ec0", - "sha256:73a816e441dace289302e04a7a34ec4772ed234ab6885c968e3ca2fc2d06fe2d", - "sha256:78c35dc7ad184aebf3714dbf43f054714c6e430e14b9c06c49a864fb9e262030", - "sha256:7f17efe9605444fcbfd990ba9b03371552d65a3c259fc2d258c24fb95afdd728", - "sha256:816645178f2180be257a576b735d3ae245b1982280b97ae819550ce8bcdf2b6b", - "sha256:924f37e66db78464b4b85ed4b6d2e5cda0c0416e657cac7ccbef14b9fa2c40b5", - "sha256:a17a8fd5df4fec5b56b4d11c9ba8b9ebfb883c90ec361628d07be00aaa4f009a", - "sha256:aaa519335a71f87217ca8a680c3b66b61960e148407bdf5c209c42f50fe30f49", - "sha256:ae3864816287d0e86ead580b69921daec568fe680857f07ee2a87bf7fd77ce24", - "sha256:b5f8c15cb9173f6cdf0f994955e58d1265331029ae26296232379461a297e5f2", - "sha256:c3ac359ace241707e5a48fe2922e566ac666aacacf4f8031f2994ac429c31344", - "sha256:c7c660cc0209fdf29a4e50146ca9ac9d8664acaded6b6ae2f5d0ae2e91a0f0cd", - "sha256:d690a2ff49f6c3bc35336693c9924fe5916be3cc0503fe1ea6c7e2bf951409ee", - "sha256:e2317cf091c2e7f0dacdc2e72c693cc34403ca1f8e3807622d0bb653dc978616", - "sha256:f28e73cf18d37a413f7d5de35d024e6b98f14566a10d82100f9dc491a7d449f9", - "sha256:f2a778dd9bb3e4590dbe3bbac28e7c7134280c4ec97e3bf8678170ee58c67b21", - "sha256:f5a758252502b466b9c2b201ea397dae5a914336c987f3a76c3741a82d43c96e", - "sha256:fb4c33a404d9eff49a0cdc8ead0af6453f62f19e071b60d283f9dc05581e4134" + "sha256:0df89ca13c25eaa1621a3f09af4c8ba20da849692dcae184cb55e80952c453fb", + "sha256:154c35f195fd3e1fad2569930ca51907057ae35e03938f89a8aedae91dd1b7c7", + "sha256:18e84323cdb8de3325e741a7a8dd4a82db74fde363dce32b625324c7b32aa6d7", + "sha256:1e8956c37fc138d65ded2d96ab3949bd49038cc6e8a4494b1515b0ba88c91565", + "sha256:23557bdbca3ccbde3abaa12a6e82299bc92d2b9139011f8c16ca1bb8c75d1e95", + "sha256:24fd645a5e5d224aa6e39d93e4a722fafa9160154f296fd5ef9580191c755053", + "sha256:36e36b6868e4440760d4b9b44587ea1dc1f06532858d10abba98e851e154ca70", + "sha256:3d734559db35aa3697dadcea492a423118c5c55d176da2f3be9c98d4803fc2a7", + "sha256:416a2070acf3a2b5d586f9a6507bb97e33574df5bd7508ea970bbf4fc563fa52", + "sha256:4a22dc3f5221a644dfe4a63bf990052cc674ef12a157b1056969079985c92816", + "sha256:4d8d3e5aa6087490912c14a3c10fbdd380b40b421c13920ff468163bc50e016f", + "sha256:4f41fd159fba1245e1958a99d349df49c616b133636e0cf668f169bce2aeac2d", + "sha256:561ef098c50f91fbac2cc9305b68c915e9eb915a74d9038ecf8af274d748f76f", + "sha256:56994e14b386b5c0a9b875a76d22d707b315fa037affc7819cda08b6d0489756", + "sha256:73a1f2a529604c50c262179fcca59c87a05ff4614fe8a15c186934d84d09d9a5", + "sha256:7da99445fd890206bfcc7419f79871ba8e73d9d9e6b82fe09980bc5bb4efc35f", + "sha256:99d59e0bcadac4aa3280616591fb7bcd560e2218f5e31d5223a2e12a1425d495", + "sha256:a4cc09489843c70b22e8373ca3dfa52b3fab778b57cf81462f1203b0852e95e3", + "sha256:a61dc29cfca9831a03442a21d4b5fd77e3067beca4b5f81f1a89a04a71cf93fa", + "sha256:b1853df739b32fa913cc59ad9137caa9cc3d97ff871e2bbd89c2a2a1d4a69451", + "sha256:b1f44c335532c0581b77491b7715a871d0dd72e97487ac0f57337ccf3ab3469b", + "sha256:b261e0cb0d6faa8fd6863af26d30351fd2ffdb15b82e51e81e96b9e9e2e7ba16", + "sha256:c857ae5dba375ea26a6228f98c195fec0898a0fd91bcf0e8a0cae6d9faf3eca7", + "sha256:cf5bb4a7d53a71bb6a0144d31df784a973b36d8687d615ef6a7e9b1809917a9b", + "sha256:db9814ff0457b46f2e1d494c1efa4111ca089e08c8b983635ebffb9c1573361f", + "sha256:df04f4bad8a359daa2ff74f8108ea051670cafbca533bb2636c58b16e962989e", + "sha256:ecf81720934a0e18526177e645cbd6a8a21bb0ddc887ff9738de07a1df5c6b61", + "sha256:edfa6fba9157e0e3be0f40168eb142511012683ac3dc82420bee4a3f3981b30e" ], - "markers": "python_version >= '2.7' and python_version != '3.1.*' and python_version != '3.3.*' and python_version != '3.0.*' and python_version != '3.2.*'", - "version": "==1.15.0" + "version": "==1.15.4" }, "outcome": { "hashes": [ - "sha256:d54e5d469088af53022f64a753b288d6bab0fe42e513eb7146137d560e2e516e", - "sha256:de68deb145ace3b9217a9461d6bfb4f720fdf01f77bfd65936906d8301bd08d2" + "sha256:7357af9ba2a08fdff8c742818909c5d146fc1fe75aee4bddadaa4f8ad726d262", + "sha256:9d58c05db36a900ce60c6da0167d76e28869f64b338d60fa3a61841cfa54ac71" ], - "version": "==0.1.0" + "version": "==1.0.0" }, "pandas": { "hashes": [ @@ -198,6 +193,7 @@ "sha256:6efa9fa6e1434141df8872d0fa4226fc301b17aacf37429193f9d70b426ea28f", "sha256:be4715c9d8367e51dbe6bc6d05e205b1ae234f0dc5465931014aa1c4af44c1ba", "sha256:bea90da782d8e945fccfc958585210d23de374fa9294a9481ed2abcef637ebfc", + "sha256:d318d77ab96f66a59e792a481e2701fba879e1a453aefeebdb17444fe204d1ed", "sha256:d785fc08d6f4207437e900ffead930a61e634c5e4f980ba6d3dc03c9581748c7", "sha256:de9559287c4fe8da56e8c3878d2374abc19d1ba2b807bfa7553e912a8e5ba87c", "sha256:f4f98b190bb918ac0bc0e3dd2ab74ff3573da9f43106f6dba6385406912ec00f", @@ -222,17 +218,17 @@ }, "python-dateutil": { "hashes": [ - "sha256:1adb80e7a782c12e52ef9a8182bebeb73f1d7e24e374397af06fb4956c8dc5c0", - "sha256:e27001de32f627c22380a688bcc43ce83504a7bc5da472209b4c70f02829f0b8" + "sha256:063df5763652e21de43de7d9e00ccf239f953a832941e37be541614732cdfc93", + "sha256:88f9287c0174266bb0d8cedd395cfba9c58e87e5ad86b2ce58859bc11be3cf02" ], - "version": "==2.7.3" + "version": "==2.7.5" }, "pytz": { "hashes": [ - "sha256:a061aa0a9e06881eb8b3b2b43f05b9439d6583c206d0a6c340ff72a7b6669053", - "sha256:ffb9ef1de172603304d9d2819af6f5ece76f2e85ec10692a524dd876e72bf277" + "sha256:31cb35c89bd7d333cd32c5f278fca91b523b0834369e757f4c5641ea252236ca", + "sha256:8e0f8568c118d3077b46be7d654cc8167fa916092e28320cde048e54bfc9f1e6" ], - "version": "==2018.5" + "version": "==2018.7" }, "six": { "hashes": [ @@ -241,24 +237,31 @@ ], "version": "==1.11.0" }, + "sniffio": { + "hashes": [ + "sha256:2e9b81429e3b7c9e119fcee2673ee3be3229982adc68b3f59317863aba05ebb7", + "sha256:afb4997584a920e6e378a81ded2b3e71a696b85a68c4bfbe4dadf1ba57a9ef45" + ], + "version": "==1.0.0" + }, "sortedcontainers": { "hashes": [ - "sha256:607294c6e291a270948420f7ffa1fb3ed47384a4c08db6d1e9c92d08a6981982", - "sha256:ef38b128302ee8f65d81e31c9d8fbf10d81df4d6d06c9c0b66f01d33747525bb" + "sha256:220bb2e3e1886297fd7cdd6d164cb5cf237be1cfae1a3a3e526d149c52816682", + "sha256:b74f2756fb5e23512572cc76f0fe0832fd86310f77dfee54335a35fb33f6b950" ], - "version": "==2.0.4" + "version": "==2.0.5" }, "tractor": { "git": "git://github.com/tgoodlet/tractor.git", - "ref": "7f0f2e52a9c483e53bdf3216fdf8c0dde9bb69a9" + "ref": "71bb87aa3a249af37ec68d00b0a5853f58923f1e" }, "trio": { "hashes": [ - "sha256:ce0b4f59e2f41af0433247f92ce83116bf356a3c2ab5ca5942cf359a1105b4a8", - "sha256:f07d599d639209ffea373f0e2fe8a9ee0dbd1bb8133cd6cb7bab23146587419b" + "sha256:65cf596eccad597f46fce1d53220e5aca9a143e52cc99e11f33e429b0c4de33f", + "sha256:6d905d950dfa1db3fad6b5ef5637c221947123fd2b0e112033fecfc582318c3b" ], "index": "pypi", - "version": "==0.5.0" + "version": "==0.9.0" }, "wmctrl": { "hashes": [ @@ -270,39 +273,37 @@ "develop": { "asks": { "hashes": [ - "sha256:c3fc1115dfeb414ef0863da6f60f02aea7487f92f76b645738774bf93e8577de" + "sha256:1679e5bd1dfa6c5d2220bdf2b8921c9c0d063d08370a7c66b9e167113681406f" ], - "markers": "python_version >= '3.5.2'", - "version": "==2.0.0" + "version": "==2.2.0" }, "async-generator": { "hashes": [ "sha256:01c7bf666359b4967d2cda0000cc2e4af16a0ae098cbffcb8472fb9e8ad6585b", "sha256:6ebb3d106c12920aaae42ccb6f787ef5eefdcdd166ea3d628fa8476abe712144" ], - "markers": "python_version >= '3.5'", "version": "==1.10" }, "atomicwrites": { "hashes": [ - "sha256:240831ea22da9ab882b551b31d4225591e5e447a68c5e188db5b89ca1d487585", - "sha256:a24da68318b08ac9c9c45029f4a10371ab5b20e4226738e150e6e7c571630ae6" + "sha256:0312ad34fcad8fac3704d441f7b317e50af620823353ec657a53e981f92920c0", + "sha256:ec9ae8adaae229e4f8446952d204a3e4b5fdd2d099f9be3aaf556120135fb3ee" ], - "version": "==1.1.5" + "version": "==1.2.1" }, "attrs": { "hashes": [ - "sha256:4b90b09eeeb9b88c35bc642cbac057e45a5fd85367b985bd2809c62b7b939265", - "sha256:e0d0eb91441a3b53dab4d9b743eafc1ac44476296a2053b6ca3af0b139faf87b" + "sha256:10cbf6e27dbce8c30807caf056c8eb50917e0eaafe86347671b57254006c3e69", + "sha256:ca4be454458f9dec299268d472aaa5a11f67a4ff70093396e1ceae9c76cf4bbb" ], - "version": "==18.1.0" + "version": "==18.2.0" }, "click": { "hashes": [ - "sha256:29f99fc6125fbc931b758dc053b3114e55c77a6e4c6c3a2674a2dc986016381d", - "sha256:f15516df478d5a56180fbf80e68f206010e6d160fc39fa508b65e035fd75130b" + "sha256:2335065e6395b9e67ca716de5f7526736bfa6ceead690adf616d925bdc622b13", + "sha256:5b94b49521f6456670fdb30cd82a4eca9412788a93fa6dd6df72c94d5a8ff2d7" ], - "version": "==6.7" + "version": "==7.0" }, "colorlog": { "hashes": [ @@ -313,38 +314,37 @@ }, "cython": { "hashes": [ - "sha256:022592d419fc754509d0e0461eb2958dbaa45fb60d51c8a61778c58994edbe36", - "sha256:07659f4c57582104d9486c071de512fbd7e087a3a630535298442cc0e20a3f5a", - "sha256:13c73e2ffa93a615851e03fad97591954d143b5b62361b9adef81f46a31cd8ef", - "sha256:13eab5a2835a84ff62db343035603044c908d2b3b6eec09d67fdf9970acf7ac9", - "sha256:183b35a48f58862c4ec1e821f07bb7b1156c8c8559c85c32ae086f28947474eb", - "sha256:2f526b0887128bf20ab2acc905a975f62b5a04ab2f63ecbe5a30fc28285d0e0c", - "sha256:32de8637f5e6c5a76667bc7c8fc644bd9314dc19af36db8ce30a0b92ada0f642", - "sha256:4172c183ef4fb2ace6a29cdf7fc9200c5a471a7f775ff691975b774bd9ed3ad2", - "sha256:553956ec06ecbd731ef0c538eb28a5b46bedea7ab89b18237ff28b4b99d65eee", - "sha256:660eeb6870687fd3eda91e00ba4e72220545c254c8c4d967fd0c910f4fbb8cbc", - "sha256:693a8619ef066ece055ed065a15cf440f9d3ebd1bca60e87ea19144833756433", - "sha256:759c799e9ef418f163b5412e295e14c0a48fe3b4dcba9ab8aab69e9f511cfefd", - "sha256:827d3a91b7a7c31ce69e5974496fd9a8ba28eb498b988affb66d0d30de11d934", - "sha256:87e57b5d730cfab225d95e7b23abbc0c6f77598bd66639e93c73ce8afbae6f38", - "sha256:9400e5db8383346b0694a3e794d8bded18a27b21123516dcdf4b79d7ec28e98b", - "sha256:9ec27681c5b1b457aacb1cbda5db04aa28b76da2af6e1e1fd15f233eafe6a0b0", - "sha256:ae4784f040a3313c8bd00c8d04934b7ade63dc59692d8f00a5235be8ed72a445", - "sha256:b2ba8310ebd3c0e0b884d5e95bbd99d467d6af922acd1e44fe4b819839b2150e", - "sha256:b64575241f64f6ec005a4d4137339fb0ba5e156e826db2fdb5f458060d9979e0", - "sha256:c78ad0df75a9fc03ab28ca1b950c893a208c451a18f76796c3e25817d6994001", - "sha256:cdbb917e41220bd3812234dbe59d15391adbc2c5d91ae11a5273aab9e32ba7ec", - "sha256:d2223a80c623e2a8e97953ab945dfaa9385750a494438dcb55562eb1ddd9565a", - "sha256:e22f21cf92a9f8f007a280e3b3462c886d9068132a6c698dec10ad6125e3ca1e", - "sha256:ea5c16c48e561f4a6f6b8c24807494b77a79e156b8133521c400f22ca712101b", - "sha256:ee7a9614d51fe16e32ca5befe72e0808baff481791728449d0b17c8b0fe29eb9", - "sha256:ef86de9299e4ab2ebb129fb84b886bf40b9aced9807c6d6d5f28b46fb905f82c", - "sha256:f3e4860f5458a9875caa3de65e255720c0ed2ce71f0bcdab02497b32104f9db8", - "sha256:fc6c20a8ac22202a779ad4c59756647be0826993d2151a03c015e76d2368ae5f" + "sha256:019008a69e6b7c102f2ed3d733a288d1784363802b437dd2b91e6256b12746da", + "sha256:1441fe19c56c90b8c2159d7b861c31a134d543ef7886fd82a5d267f9f11f35ac", + "sha256:1d1a5e9d6ed415e75a676b72200ad67082242ec4d2d76eb7446da255ae72d3f7", + "sha256:339f5b985de3662b1d6c69991ab46fdbdc736feb4ac903ef6b8c00e14d87f4d8", + "sha256:35bdf3f48535891fee2eaade70e91d5b2cc1ee9fc2a551847c7ec18bce55a92c", + "sha256:3d0afba0aec878639608f013045697fb0969ff60b3aea2daec771ea8d01ad112", + "sha256:42c53786806e24569571a7a24ebe78ec6b364fe53e79a3f27eddd573cacd398f", + "sha256:48b919da89614d201e72fbd8247b5ae8881e296cf968feb5595a015a14c67f1f", + "sha256:49906e008eeb91912654a36c200566392bd448b87a529086694053a280f8af2d", + "sha256:49fc01a7c9c4e3c1784e9a15d162c2cac3990fcc28728227a6f8f0837aabda7c", + "sha256:501b671b639b9ca17ad303f8807deb1d0ff754d1dab106f2607d14b53cb0ff0b", + "sha256:5574574142364804423ab4428bd331a05c65f7ecfd31ac97c936f0c720fe6a53", + "sha256:6092239a772b3c6604be9e94b9ab4f0dacb7452e8ad299fd97eae0611355b679", + "sha256:71ff5c7632501c4f60edb8a24fd0a772e04c5bdca2856d978d04271b63666ef7", + "sha256:7dcf2ad14e25b05eda8bdd104f8c03a642a384aeefd25a5b51deac0826e646fa", + "sha256:8ca3a99f5a7443a6a8f83a5d8fcc11854b44e6907e92ba8640d8a8f7b9085e21", + "sha256:927da3b5710fb705aab173ad630b45a4a04c78e63dcd89411a065b2fe60e4770", + "sha256:94916d1ede67682638d3cc0feb10648ff14dc51fb7a7f147f4fedce78eaaea97", + "sha256:a3e5e5ca325527d312cdb12a4dab8b0459c458cad1c738c6f019d0d8d147081c", + "sha256:a7716a98f0b9b8f61ddb2bae7997daf546ac8fc594be6ba397f4bde7d76bfc62", + "sha256:acf10d1054de92af8d5bfc6620bb79b85f04c98214b4da7db77525bfa9fc2a89", + "sha256:de46ffb67e723975f5acab101c5235747af1e84fbbc89bf3533e2ea93fb26947", + "sha256:df428969154a9a4cd9748c7e6efd18432111fbea3d700f7376046c38c5e27081", + "sha256:f5ebf24b599caf466f9da8c4115398d663b2567b89e92f58a835e9da4f74669f", + "sha256:f79e45d5c122c4fb1fd54029bf1d475cecc05f4ed5b68136b0d6ec268bae68b6", + "sha256:f7a43097d143bd7846ffba6d2d8cd1cc97f233318dbd0f50a235ea01297a096b", + "sha256:fceb8271bc2fd3477094ca157c824e8ea840a7b393e89e766eea9a3b9ce7e0c6", + "sha256:ff919ceb40259f5332db43803aa6c22ff487e86036ce3921ae04b9185efc99a4" ], "index": "pypi", - "markers": "python_version >= '2.6' and python_version != '3.1.*' and python_version != '3.0.*' and python_version != '3.2.*'", - "version": "==0.28.5" + "version": "==0.29" }, "fancycompleter": { "hashes": [ @@ -397,51 +397,49 @@ }, "multio": { "hashes": [ - "sha256:dcaee4d5d77cde8caf7902c8621aaa192febb384c7b1291fd47cfa41ac0eaebc" + "sha256:e8bce12aa8d2e076d96f4c4b6bfb70c01e0e0af9892f9ffc4ec868854e1b877e" ], - "markers": "python_version >= '3.5.2'", - "version": "==0.2.3" + "version": "==0.2.4" }, "numpy": { "hashes": [ - "sha256:14fb76bde161c87dcec52d91c78f65aa8a23aa2e1530a71f412dabe03927d917", - "sha256:21041014b7529237994a6b578701c585703fbb3b1bea356cdb12a5ea7804241c", - "sha256:24f3bb9a5f6c3936a8ccd4ddfc1210d9511f4aeb879a12efd2e80bec647b8695", - "sha256:34033b581bc01b1135ca2e3e93a94daea7c739f21a97a75cca93e29d9f0c8e71", - "sha256:3fbccb399fe9095b1c1d7b41e7c7867db8aa0d2347fc44c87a7a180cedda112b", - "sha256:50718eea8e77a1bedcc85befd22c8dbf5a24c9d2c0c1e36bbb8d7a38da847eb3", - "sha256:55daf757e5f69aa75b4477cf4511bf1f96325c730e4ad32d954ccb593acd2585", - "sha256:61efc65f325770bbe787f34e00607bc124f08e6c25fdf04723848585e81560dc", - "sha256:62cb836506f40ce2529bfba9d09edc4b2687dd18c56cf4457e51c3e7145402fd", - "sha256:64c6acf5175745fd1b7b7e17c74fdbfb7191af3b378bc54f44560279f41238d3", - "sha256:674ea7917f0657ddb6976bd102ac341bc493d072c32a59b98e5b8c6eaa2d5ec0", - "sha256:73a816e441dace289302e04a7a34ec4772ed234ab6885c968e3ca2fc2d06fe2d", - "sha256:78c35dc7ad184aebf3714dbf43f054714c6e430e14b9c06c49a864fb9e262030", - "sha256:7f17efe9605444fcbfd990ba9b03371552d65a3c259fc2d258c24fb95afdd728", - "sha256:816645178f2180be257a576b735d3ae245b1982280b97ae819550ce8bcdf2b6b", - "sha256:924f37e66db78464b4b85ed4b6d2e5cda0c0416e657cac7ccbef14b9fa2c40b5", - "sha256:a17a8fd5df4fec5b56b4d11c9ba8b9ebfb883c90ec361628d07be00aaa4f009a", - "sha256:aaa519335a71f87217ca8a680c3b66b61960e148407bdf5c209c42f50fe30f49", - "sha256:ae3864816287d0e86ead580b69921daec568fe680857f07ee2a87bf7fd77ce24", - "sha256:b5f8c15cb9173f6cdf0f994955e58d1265331029ae26296232379461a297e5f2", - "sha256:c3ac359ace241707e5a48fe2922e566ac666aacacf4f8031f2994ac429c31344", - "sha256:c7c660cc0209fdf29a4e50146ca9ac9d8664acaded6b6ae2f5d0ae2e91a0f0cd", - "sha256:d690a2ff49f6c3bc35336693c9924fe5916be3cc0503fe1ea6c7e2bf951409ee", - "sha256:e2317cf091c2e7f0dacdc2e72c693cc34403ca1f8e3807622d0bb653dc978616", - "sha256:f28e73cf18d37a413f7d5de35d024e6b98f14566a10d82100f9dc491a7d449f9", - "sha256:f2a778dd9bb3e4590dbe3bbac28e7c7134280c4ec97e3bf8678170ee58c67b21", - "sha256:f5a758252502b466b9c2b201ea397dae5a914336c987f3a76c3741a82d43c96e", - "sha256:fb4c33a404d9eff49a0cdc8ead0af6453f62f19e071b60d283f9dc05581e4134" + "sha256:0df89ca13c25eaa1621a3f09af4c8ba20da849692dcae184cb55e80952c453fb", + "sha256:154c35f195fd3e1fad2569930ca51907057ae35e03938f89a8aedae91dd1b7c7", + "sha256:18e84323cdb8de3325e741a7a8dd4a82db74fde363dce32b625324c7b32aa6d7", + "sha256:1e8956c37fc138d65ded2d96ab3949bd49038cc6e8a4494b1515b0ba88c91565", + "sha256:23557bdbca3ccbde3abaa12a6e82299bc92d2b9139011f8c16ca1bb8c75d1e95", + "sha256:24fd645a5e5d224aa6e39d93e4a722fafa9160154f296fd5ef9580191c755053", + "sha256:36e36b6868e4440760d4b9b44587ea1dc1f06532858d10abba98e851e154ca70", + "sha256:3d734559db35aa3697dadcea492a423118c5c55d176da2f3be9c98d4803fc2a7", + "sha256:416a2070acf3a2b5d586f9a6507bb97e33574df5bd7508ea970bbf4fc563fa52", + "sha256:4a22dc3f5221a644dfe4a63bf990052cc674ef12a157b1056969079985c92816", + "sha256:4d8d3e5aa6087490912c14a3c10fbdd380b40b421c13920ff468163bc50e016f", + "sha256:4f41fd159fba1245e1958a99d349df49c616b133636e0cf668f169bce2aeac2d", + "sha256:561ef098c50f91fbac2cc9305b68c915e9eb915a74d9038ecf8af274d748f76f", + "sha256:56994e14b386b5c0a9b875a76d22d707b315fa037affc7819cda08b6d0489756", + "sha256:73a1f2a529604c50c262179fcca59c87a05ff4614fe8a15c186934d84d09d9a5", + "sha256:7da99445fd890206bfcc7419f79871ba8e73d9d9e6b82fe09980bc5bb4efc35f", + "sha256:99d59e0bcadac4aa3280616591fb7bcd560e2218f5e31d5223a2e12a1425d495", + "sha256:a4cc09489843c70b22e8373ca3dfa52b3fab778b57cf81462f1203b0852e95e3", + "sha256:a61dc29cfca9831a03442a21d4b5fd77e3067beca4b5f81f1a89a04a71cf93fa", + "sha256:b1853df739b32fa913cc59ad9137caa9cc3d97ff871e2bbd89c2a2a1d4a69451", + "sha256:b1f44c335532c0581b77491b7715a871d0dd72e97487ac0f57337ccf3ab3469b", + "sha256:b261e0cb0d6faa8fd6863af26d30351fd2ffdb15b82e51e81e96b9e9e2e7ba16", + "sha256:c857ae5dba375ea26a6228f98c195fec0898a0fd91bcf0e8a0cae6d9faf3eca7", + "sha256:cf5bb4a7d53a71bb6a0144d31df784a973b36d8687d615ef6a7e9b1809917a9b", + "sha256:db9814ff0457b46f2e1d494c1efa4111ca089e08c8b983635ebffb9c1573361f", + "sha256:df04f4bad8a359daa2ff74f8108ea051670cafbca533bb2636c58b16e962989e", + "sha256:ecf81720934a0e18526177e645cbd6a8a21bb0ddc887ff9738de07a1df5c6b61", + "sha256:edfa6fba9157e0e3be0f40168eb142511012683ac3dc82420bee4a3f3981b30e" ], - "markers": "python_version >= '2.7' and python_version != '3.1.*' and python_version != '3.3.*' and python_version != '3.0.*' and python_version != '3.2.*'", - "version": "==1.15.0" + "version": "==1.15.4" }, "outcome": { "hashes": [ - "sha256:d54e5d469088af53022f64a753b288d6bab0fe42e513eb7146137d560e2e516e", - "sha256:de68deb145ace3b9217a9461d6bfb4f720fdf01f77bfd65936906d8301bd08d2" + "sha256:7357af9ba2a08fdff8c742818909c5d146fc1fe75aee4bddadaa4f8ad726d262", + "sha256:9d58c05db36a900ce60c6da0167d76e28869f64b338d60fa3a61841cfa54ac71" ], - "version": "==0.1.0" + "version": "==1.0.0" }, "pandas": { "hashes": [ @@ -459,6 +457,7 @@ "sha256:6efa9fa6e1434141df8872d0fa4226fc301b17aacf37429193f9d70b426ea28f", "sha256:be4715c9d8367e51dbe6bc6d05e205b1ae234f0dc5465931014aa1c4af44c1ba", "sha256:bea90da782d8e945fccfc958585210d23de374fa9294a9481ed2abcef637ebfc", + "sha256:d318d77ab96f66a59e792a481e2701fba879e1a453aefeebdb17444fe204d1ed", "sha256:d785fc08d6f4207437e900ffead930a61e634c5e4f980ba6d3dc03c9581748c7", "sha256:de9559287c4fe8da56e8c3878d2374abc19d1ba2b807bfa7553e912a8e5ba87c", "sha256:f4f98b190bb918ac0bc0e3dd2ab74ff3573da9f43106f6dba6385406912ec00f", @@ -480,19 +479,17 @@ }, "pluggy": { "hashes": [ - "sha256:6e3836e39f4d36ae72840833db137f7b7d35105079aee6ec4a62d9f80d594dd1", - "sha256:95eb8364a4708392bae89035f45341871286a333f749c3141c20573d2b3876e1" + "sha256:447ba94990e8014ee25ec853339faf7b0fc8050cdc3289d4d71f7f410fb90095", + "sha256:bde19360a8ec4dfd8a20dcb811780a30998101f078fc7ded6162f0076f50508f" ], - "markers": "python_version >= '2.7' and python_version != '3.1.*' and python_version != '3.3.*' and python_version != '3.0.*' and python_version != '3.2.*'", - "version": "==0.7.1" + "version": "==0.8.0" }, "py": { "hashes": [ - "sha256:3fd59af7435864e1a243790d322d763925431213b6b8529c6ca71081ace3bbf7", - "sha256:e31fb2767eb657cbde86c454f02e99cb846d3cd9d61b318525140214fdc0e98e" + "sha256:bf92637198836372b520efcba9e020c330123be8ce527e535d185ed4b6f45694", + "sha256:e76826342cefe3c3d5f7e8ee4316b80d1dd8a300781612ddbc765c17ba25a6c6" ], - "markers": "python_version >= '2.7' and python_version != '3.1.*' and python_version != '3.3.*' and python_version != '3.0.*' and python_version != '3.2.*'", - "version": "==1.5.4" + "version": "==1.7.0" }, "pygments": { "hashes": [ @@ -503,25 +500,25 @@ }, "pytest": { "hashes": [ - "sha256:86a8dbf407e437351cef4dba46736e9c5a6e3c3ac71b2e942209748e76ff2086", - "sha256:e74466e97ac14582a8188ff4c53e6cc3810315f342f6096899332ae864c1d432" + "sha256:3f193df1cfe1d1609d4c583838bea3d532b18d6160fd3f55c9447fdca30848ec", + "sha256:e246cf173c01169b9617fc07264b7b1316e78d7a650055235d6d897bc80d9660" ], "index": "pypi", - "version": "==3.7.1" + "version": "==3.10.1" }, "python-dateutil": { "hashes": [ - "sha256:1adb80e7a782c12e52ef9a8182bebeb73f1d7e24e374397af06fb4956c8dc5c0", - "sha256:e27001de32f627c22380a688bcc43ce83504a7bc5da472209b4c70f02829f0b8" + "sha256:063df5763652e21de43de7d9e00ccf239f953a832941e37be541614732cdfc93", + "sha256:88f9287c0174266bb0d8cedd395cfba9c58e87e5ad86b2ce58859bc11be3cf02" ], - "version": "==2.7.3" + "version": "==2.7.5" }, "pytz": { "hashes": [ - "sha256:a061aa0a9e06881eb8b3b2b43f05b9439d6583c206d0a6c340ff72a7b6669053", - "sha256:ffb9ef1de172603304d9d2819af6f5ece76f2e85ec10692a524dd876e72bf277" + "sha256:31cb35c89bd7d333cd32c5f278fca91b523b0834369e757f4c5641ea252236ca", + "sha256:8e0f8568c118d3077b46be7d654cc8167fa916092e28320cde048e54bfc9f1e6" ], - "version": "==2018.5" + "version": "==2018.7" }, "six": { "hashes": [ @@ -530,20 +527,27 @@ ], "version": "==1.11.0" }, + "sniffio": { + "hashes": [ + "sha256:2e9b81429e3b7c9e119fcee2673ee3be3229982adc68b3f59317863aba05ebb7", + "sha256:afb4997584a920e6e378a81ded2b3e71a696b85a68c4bfbe4dadf1ba57a9ef45" + ], + "version": "==1.0.0" + }, "sortedcontainers": { "hashes": [ - "sha256:607294c6e291a270948420f7ffa1fb3ed47384a4c08db6d1e9c92d08a6981982", - "sha256:ef38b128302ee8f65d81e31c9d8fbf10d81df4d6d06c9c0b66f01d33747525bb" + "sha256:220bb2e3e1886297fd7cdd6d164cb5cf237be1cfae1a3a3e526d149c52816682", + "sha256:b74f2756fb5e23512572cc76f0fe0832fd86310f77dfee54335a35fb33f6b950" ], - "version": "==2.0.4" + "version": "==2.0.5" }, "trio": { "hashes": [ - "sha256:ce0b4f59e2f41af0433247f92ce83116bf356a3c2ab5ca5942cf359a1105b4a8", - "sha256:f07d599d639209ffea373f0e2fe8a9ee0dbd1bb8133cd6cb7bab23146587419b" + "sha256:65cf596eccad597f46fce1d53220e5aca9a143e52cc99e11f33e429b0c4de33f", + "sha256:6d905d950dfa1db3fad6b5ef5637c221947123fd2b0e112033fecfc582318c3b" ], "index": "pypi", - "version": "==0.5.0" + "version": "==0.9.0" }, "wmctrl": { "hashes": [ diff --git a/piker/__init__.py b/piker/__init__.py index ac6e86e3..157cacd8 100644 --- a/piker/__init__.py +++ b/piker/__init__.py @@ -1,3 +1,17 @@ +# Copyright 2018 Tyler Goodlet + +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . """ -piker: trading toolz for hackerz. +piker: destroy all suits """ diff --git a/piker/brokers/core.py b/piker/brokers/core.py index f92f3e53..60f4292c 100644 --- a/piker/brokers/core.py +++ b/piker/brokers/core.py @@ -1,32 +1,32 @@ """ -Core broker-daemon tasks and API. +Broker high level API layer. """ -import time import inspect -from functools import partial -import socket from types import ModuleType -from typing import Coroutine, Callable +from typing import List, Dict, Any, Optional -import trio -import tractor - -from ..log import get_logger, get_console_log -from . import get_brokermod +from ..log import get_logger log = get_logger('broker.core') async def api(brokermod: ModuleType, methname: str, **kwargs) -> dict: - """Make (proxy through) an api call by name and return its result. + """Make (proxy through) a broker API call by name and return its result. """ async with brokermod.get_client() as client: + meth = getattr(client.api, methname, None) + if meth is None: + log.warning( + "Couldn't find API method {methname} looking up on client") + meth = getattr(client, methname, None) + if meth is None: log.error(f"No api method `{methname}` could be found?") return - elif not kwargs: + + if not kwargs: # verify kwargs requirements are met sig = inspect.signature(meth) if sig.parameters: @@ -38,7 +38,10 @@ async def api(brokermod: ModuleType, methname: str, **kwargs) -> dict: return await meth(**kwargs) -async def quote(brokermod: ModuleType, tickers: [str]) -> dict: +async def stocks_quote( + brokermod: ModuleType, + tickers: List[str] +) -> Dict[str, Dict[str, Any]]: """Return quotes dict for ``tickers``. """ async with brokermod.get_client() as client: @@ -50,296 +53,34 @@ async def quote(brokermod: ModuleType, tickers: [str]) -> dict: return results -async def wait_for_network(net_func: Callable, sleep: int = 1) -> dict: - """Wait until the network comes back up. - """ - down = False - while True: - try: - with trio.move_on_after(1) as cancel_scope: - quotes = await net_func() - if down: - log.warn("Network is back up") - return quotes - if cancel_scope.cancelled_caught: - log.warn("Quote query timed out") - continue - except socket.gaierror: - if not down: # only report/log network down once - log.warn(f"Network is down waiting for re-establishment...") - down = True - await trio.sleep(sleep) - - -async def stream_quotes( +async def option_chain( brokermod: ModuleType, - get_quotes: Coroutine, - tickers2chans: {str: tractor.Channel}, - rate: int = 5, # delay between quote requests - diff_cached: bool = True, # only deliver "new" quotes to the queue - cid: str = None, -) -> None: - """Stream quotes for a sequence of tickers at the given ``rate`` - per second. + symbol: str, + date: Optional[str] = None, +) -> Dict[str, Dict[str, Dict[str, Any]]]: + """Return option chain for ``symbol`` for ``date``. - A broker-client ``quoter`` async context manager must be provided which - returns an async quote function. + By default all expiries are returned. If ``date`` is provided + then contract quotes for that single expiry are returned. """ - broker_limit = getattr(brokermod, '_rate_limit', float('inf')) - if broker_limit < rate: - rate = broker_limit - log.warn(f"Limiting {brokermod.__name__} query rate to {rate}/sec") - - sleeptime = round(1. / rate, 3) - _cache = {} # ticker to quote caching - - while True: # use an event here to trigger exit? - prequote_start = time.time() - - if not any(tickers2chans.values()): - log.warn(f"No subs left for broker {brokermod.name}, exiting task") - break - - tickers = list(tickers2chans.keys()) - with trio.move_on_after(3) as cancel_scope: - quotes = await get_quotes(tickers) - - cancelled = cancel_scope.cancelled_caught - if cancelled: - log.warn("Quote query timed out after 3 seconds, retrying...") - # handle network outages by idling until response is received - quotes = await wait_for_network(partial(get_quotes, tickers)) - - postquote_start = time.time() - chan_payloads = {} - for symbol, quote in quotes.items(): - if diff_cached: - # if cache is enabled then only deliver "new" changes - last = _cache.setdefault(symbol, {}) - new = set(quote.items()) - set(last.items()) - if new: - log.info( - f"New quote {quote['symbol']}:\n{new}") - _cache[symbol] = quote - for chan, cid in tickers2chans.get(symbol, set()): - chan_payloads.setdefault( - chan, - {'yield': {}, 'cid': cid} - )['yield'][symbol] = quote - else: - for chan, cid in tickers2chans[symbol]: - chan_payloads.setdefault( - chan, - {'yield': {}, 'cid': cid} - )['yield'][symbol] = quote - - # deliver to each subscriber - if chan_payloads: - for chan, payload in chan_payloads.items(): - try: - await chan.send(payload) - except ( - # That's right, anything you can think of... - trio.ClosedStreamError, ConnectionResetError, - ConnectionRefusedError, - ): - log.warn(f"{chan} went down?") - for chanset in tickers2chans.values(): - chanset.discard((chan, cid)) - - req_time = round(postquote_start - prequote_start, 3) - proc_time = round(time.time() - postquote_start, 3) - tot = req_time + proc_time - log.debug(f"Request + processing took {tot}") - delay = sleeptime - tot - if delay <= 0: - log.warn( - f"Took {req_time} (request) + {proc_time} (processing) " - f"= {tot} secs (> {sleeptime}) for processing quotes?") + async with brokermod.get_client() as client: + if date: + id = int((await client.tickers2ids([symbol]))[symbol]) + # build contracts dict for single expiry + return await client.option_chains({id: {date: None}}) else: - log.debug(f"Sleeping for {delay}") - await trio.sleep(delay) - - log.info(f"Terminating stream quoter task for {brokermod.name}") + # get all contract expiries + # (takes a long-ass time on QT fwiw) + contracts = await client.get_all_contracts([symbol]) + # return chains for all dates + return await client.option_chains(contracts) -async def get_cached_client(broker, tickers): - """Get the current actor's cached broker client if available or create a - new one. +async def contracts( + brokermod: ModuleType, + symbol: str, +) -> Dict[str, Dict[str, Dict[str, Any]]]: + """Return option contracts (all expiries) for ``symbol``. """ - # check if a cached client is in the local actor's statespace - clients = tractor.current_actor().statespace.setdefault('clients', {}) - try: - return clients[broker] - except KeyError: - log.info(f"Creating new client for broker {broker}") - brokermod = get_brokermod(broker) - # TODO: move to AsyncExitStack in 3.7 - client_cntxmng = brokermod.get_client() - client = await client_cntxmng.__aenter__() - get_quotes = await brokermod.quoter(client, tickers) - clients[broker] = ( - brokermod, client, client_cntxmng, get_quotes) - - return brokermod, client, client_cntxmng, get_quotes - - -async def symbol_data(broker, tickers): - """Retrieve baseline symbol info from broker. - """ - _, client, _, get_quotes = await get_cached_client(broker, tickers) - return await client.symbol_data(tickers) - - -async def smoke_quote(get_quotes, tickers, broker): - """Do an initial "smoke" request for symbols in ``tickers`` filtering - out any symbols not supported by the broker queried in the call to - ``get_quotes()``. - """ - # TODO: trim out with #37 - ################################################# - # get a single quote filtering out any bad tickers - # NOTE: this code is always run for every new client - # subscription even when a broker quoter task is already running - # since the new client needs to know what symbols are accepted - log.warn(f"Retrieving smoke quote for symbols {tickers}") - quotes = await get_quotes(tickers) - # report any tickers that aren't returned in the first quote - invalid_tickers = set(tickers) - set(quotes) - for symbol in invalid_tickers: - tickers.remove(symbol) - log.warn( - f"Symbol `{symbol}` not found by broker `{broker}`" - ) - - # pop any tickers that return "empty" quotes - payload = {} - for symbol, quote in quotes.items(): - if quote is None: - log.warn( - f"Symbol `{symbol}` not found by broker" - f" `{broker}`") - # XXX: not this mutates the input list (for now) - tickers.remove(symbol) - continue - payload[symbol] = quote - - return payload - - # end of section to be trimmed out with #37 - ########################################### - - -def modify_quote_stream(broker, tickers, chan=None, cid=None): - """Absolute symbol subscription list for each quote stream. - """ - log.info(f"{chan} changed symbol subscription to {tickers}") - ss = tractor.current_actor().statespace - broker2tickersubs = ss['broker2tickersubs'] - tickers2chans = broker2tickersubs.get(broker) - # update map from each symbol to requesting client's chan - for ticker in tickers: - tickers2chans.setdefault(ticker, set()).add((chan, cid)) - - for ticker in filter( - lambda ticker: ticker not in tickers, tickers2chans.copy() - ): - chanset = tickers2chans.get(ticker) - # XXX: cid will be different on unsub call - for item in chanset.copy(): - if chan in item: - chanset.discard(item) - - if not chanset: - # pop empty sets which will trigger bg quoter task termination - tickers2chans.pop(ticker) - - -async def start_quote_stream( - broker: str, - tickers: [str], - chan: tractor.Channel = None, - cid: str = None, -) -> None: - """Handle per-broker quote stream subscriptions. - - Spawns new quoter tasks for each broker backend on-demand. - Since most brokers seems to support batch quote requests we - limit to one task per process for now. - """ - actor = tractor.current_actor() - # set log level after fork - get_console_log(actor.loglevel) - # pull global vars from local actor - ss = actor.statespace - broker2tickersubs = ss['broker2tickersubs'] - clients = ss['clients'] - dtasks = ss['dtasks'] - tickers = list(tickers) - log.info( - f"{chan.uid} subscribed to {broker} for tickers {tickers}") - - brokermod, client, _, get_quotes = await get_cached_client(broker, tickers) - if broker not in broker2tickersubs: - tickers2chans = broker2tickersubs.setdefault(broker, {}) - else: - log.info(f"Subscribing with existing `{broker}` daemon") - tickers2chans = broker2tickersubs[broker] - - # do a smoke quote (not this mutates the input list and filters out bad - # symbols for now) - payload = await smoke_quote(get_quotes, tickers, broker) - # push initial smoke quote response for client initialization - await chan.send({'yield': payload, 'cid': cid}) - - # update map from each symbol to requesting client's chan - modify_quote_stream(broker, tickers, chan=chan, cid=cid) - - try: - if broker not in dtasks: # no quoter task yet - # task should begin on the next checkpoint/iteration - # with trio.open_cancel_scope(shield=True): - log.info(f"Spawning quoter task for {brokermod.name}") - # await actor._root_nursery.start(partial( - async with trio.open_nursery() as nursery: - nursery.start_soon(partial( - stream_quotes, brokermod, get_quotes, tickers2chans, - cid=cid) - ) - dtasks.add(broker) - - # unblocks when no more symbols subscriptions exist and the - # quote streamer task terminates (usually because another call - # was made to `modify_quoter` to unsubscribe from streaming - # symbols) - log.info(f"Terminated quoter task for {brokermod.name}") - - # TODO: move to AsyncExitStack in 3.7 - for _, _, cntxmng, _ in clients.values(): - # FIXME: yes I know there's no error handling.. - await cntxmng.__aexit__(None, None, None) - finally: - # if there are truly no more subscriptions with this broker - # drop from broker subs dict - if not any(tickers2chans.values()): - log.info(f"No more subscriptions for {broker}") - broker2tickersubs.pop(broker, None) - dtasks.discard(broker) - - -async def _test_price_stream(broker, symbols, *, chan=None, cid=None): - """Test function for initial tractor draft. - """ - brokermod = get_brokermod(broker) - client_cntxmng = brokermod.get_client() - client = await client_cntxmng.__aenter__() - get_quotes = await brokermod.quoter(client, symbols) - log.info(f"Spawning quoter task for {brokermod.name}") - assert chan - tickers2chans = {}.fromkeys(symbols, {(chan, cid), }) - - async with trio.open_nursery() as nursery: - nursery.start_soon( - partial( - stream_quotes, brokermod, get_quotes, tickers2chans, cid=cid) - ) + async with brokermod.get_client() as client: + return await client.get_all_contracts([symbol]) diff --git a/piker/brokers/data.py b/piker/brokers/data.py new file mode 100644 index 00000000..b1427cab --- /dev/null +++ b/piker/brokers/data.py @@ -0,0 +1,353 @@ +""" +Live data feed machinery +""" +import time +from functools import partial +from itertools import cycle +import socket +import json +from types import ModuleType +from typing import Coroutine, Callable, Dict, List + +import trio +import tractor + +from ..log import get_logger, get_console_log +from . import get_brokermod + + +log = get_logger('broker.data') + + +async def wait_for_network(net_func: Callable, sleep: int = 1) -> dict: + """Wait until the network comes back up. + """ + down = False + while True: + try: + with trio.move_on_after(1) as cancel_scope: + quotes = await net_func() + if down: + log.warn("Network is back up") + return quotes + if cancel_scope.cancelled_caught: + log.warn("Quote query timed out") + continue + except socket.gaierror: + if not down: # only report/log network down once + log.warn(f"Network is down waiting for re-establishment...") + down = True + await trio.sleep(sleep) + + +async def stream_quotes( + brokermod: ModuleType, + request_quotes: Coroutine, + rate: int = 5, # delay between quote requests + diff_cached: bool = True, # only deliver "new" quotes to the queue +) -> None: + """Stream quotes for a sequence of tickers at the given ``rate`` + per second. + + A stock-broker client ``get_quotes()`` async context manager must be + provided which returns an async quote retrieval function. + """ + sleeptime = round(1. / rate, 3) + _cache = {} # ticker to quote caching + + while True: # use an event here to trigger exit? + prequote_start = time.time() + + # tickers = list(tickers2chans.keys()) + with trio.move_on_after(3) as cancel_scope: + quotes = await request_quotes() + + cancelled = cancel_scope.cancelled_caught + if cancelled: + log.warn("Quote query timed out after 3 seconds, retrying...") + # handle network outages by idling until response is received + # quotes = await wait_for_network(partial(get_quotes, tickers)) + quotes = await wait_for_network(request_quotes) + + postquote_start = time.time() + new_quotes = {} + if diff_cached: + # if cache is enabled then only deliver "new" changes + for symbol, quote in quotes.items(): + last = _cache.setdefault(symbol, {}) + new = set(quote.items()) - set(last.items()) + if new: + log.info( + f"New quote {quote['symbol']}:\n{new}") + _cache[symbol] = quote + new_quotes[symbol] = quote + else: + new_quotes = quotes + + yield new_quotes + + # latency monitoring + req_time = round(postquote_start - prequote_start, 3) + proc_time = round(time.time() - postquote_start, 3) + tot = req_time + proc_time + log.debug(f"Request + processing took {tot}") + delay = sleeptime - tot + if delay <= 0: + log.warn( + f"Took {req_time} (request) + {proc_time} (processing) " + f"= {tot} secs (> {sleeptime}) for processing quotes?") + else: + log.debug(f"Sleeping for {delay}") + await trio.sleep(delay) + + +async def fan_out_to_chans( + brokermod: ModuleType, + get_quotes: Coroutine, + tickers2chans: Dict[str, tractor.Channel], + rate: int = 5, # delay between quote requests + diff_cached: bool = True, # only deliver "new" quotes to the queue + cid: str = None, +) -> None: + """Request and fan out quotes to each subscribed actor channel. + """ + broker_limit = getattr(brokermod, '_rate_limit', float('inf')) + if broker_limit < rate: + rate = broker_limit + log.warn(f"Limiting {brokermod.__name__} query rate to {rate}/sec") + + async def request(): + """Get quotes for current symbol subscription set. + """ + return await get_quotes(list(tickers2chans.keys())) + + async for quotes in stream_quotes(brokermod, request, rate): + chan_payloads = {} + for symbol, quote in quotes.items(): + # set symbol quotes for each subscriber + for chan, cid in tickers2chans.get(symbol, set()): + chan_payloads.setdefault( + chan, + {'yield': {}, 'cid': cid} + )['yield'][symbol] = quote + + # deliver to each subscriber (fan out) + if chan_payloads: + for chan, payload in chan_payloads.items(): + try: + await chan.send(payload) + except ( + # That's right, anything you can think of... + trio.ClosedStreamError, ConnectionResetError, + ConnectionRefusedError, + ): + log.warn(f"{chan} went down?") + for chanset in tickers2chans.values(): + chanset.discard((chan, cid)) + + if not any(tickers2chans.values()): + log.warn(f"No subs left for broker {brokermod.name}, exiting task") + break + + log.info(f"Terminating stream quoter task for {brokermod.name}") + + +async def get_cached_client(broker, tickers): + """Get or create the current actor's cached broker client. + """ + # check if a cached client is in the local actor's statespace + clients = tractor.current_actor().statespace.setdefault('clients', {}) + try: + return clients[broker] + except KeyError: + log.info(f"Creating new client for broker {broker}") + brokermod = get_brokermod(broker) + # TODO: move to AsyncExitStack in 3.7 + client_cntxmng = brokermod.get_client() + client = await client_cntxmng.__aenter__() + get_quotes = await brokermod.quoter(client, tickers) + clients[broker] = ( + brokermod, client, client_cntxmng, get_quotes) + + return brokermod, client, client_cntxmng, get_quotes + + +async def symbol_data(broker, tickers): + """Retrieve baseline symbol info from broker. + """ + _, client, _, get_quotes = await get_cached_client(broker, tickers) + return await client.symbol_data(tickers) + + +async def smoke_quote(get_quotes, tickers, broker): + """Do an initial "smoke" request for symbols in ``tickers`` filtering + out any symbols not supported by the broker queried in the call to + ``get_quotes()``. + """ + # TODO: trim out with #37 + ################################################# + # get a single quote filtering out any bad tickers + # NOTE: this code is always run for every new client + # subscription even when a broker quoter task is already running + # since the new client needs to know what symbols are accepted + log.warn(f"Retrieving smoke quote for symbols {tickers}") + quotes = await get_quotes(tickers) + # report any tickers that aren't returned in the first quote + invalid_tickers = set(tickers) - set(quotes) + for symbol in invalid_tickers: + tickers.remove(symbol) + log.warn( + f"Symbol `{symbol}` not found by broker `{broker}`" + ) + + # pop any tickers that return "empty" quotes + payload = {} + for symbol, quote in quotes.items(): + if quote is None: + log.warn( + f"Symbol `{symbol}` not found by broker" + f" `{broker}`") + # XXX: not this mutates the input list (for now) + tickers.remove(symbol) + continue + payload[symbol] = quote + + return payload + + # end of section to be trimmed out with #37 + ########################################### + + +def modify_quote_stream(broker, tickers, chan=None, cid=None): + """Absolute symbol subscription list for each quote stream. + + Effectively a consumer subscription api. + """ + log.info(f"{chan} changed symbol subscription to {tickers}") + ss = tractor.current_actor().statespace + broker2tickersubs = ss['broker2tickersubs'] + tickers2chans = broker2tickersubs.get(broker) + # update map from each symbol to requesting client's chan + for ticker in tickers: + tickers2chans.setdefault(ticker, set()).add((chan, cid)) + + for ticker in filter( + lambda ticker: ticker not in tickers, tickers2chans.copy() + ): + chanset = tickers2chans.get(ticker) + # XXX: cid will be different on unsub call + for item in chanset.copy(): + if chan in item: + chanset.discard(item) + + if not chanset: + # pop empty sets which will trigger bg quoter task termination + tickers2chans.pop(ticker) + + +async def start_quote_stream( + broker: str, + tickers: List[str], + chan: tractor.Channel = None, + cid: str = None, +) -> None: + """Handle per-broker quote stream subscriptions using a "lazy" pub-sub + pattern. + + Spawns new quoter tasks for each broker backend on-demand. + Since most brokers seems to support batch quote requests we + limit to one task per process for now. + """ + actor = tractor.current_actor() + # set log level after fork + get_console_log(actor.loglevel) + # pull global vars from local actor + ss = actor.statespace + broker2tickersubs = ss['broker2tickersubs'] + clients = ss['clients'] + dtasks = ss['dtasks'] + tickers = list(tickers) + log.info( + f"{chan.uid} subscribed to {broker} for tickers {tickers}") + + brokermod, client, _, get_quotes = await get_cached_client(broker, tickers) + if broker not in broker2tickersubs: + tickers2chans = broker2tickersubs.setdefault(broker, {}) + else: + log.info(f"Subscribing with existing `{broker}` daemon") + tickers2chans = broker2tickersubs[broker] + + # do a smoke quote (note this mutates the input list and filters + # out bad symbols for now) + payload = await smoke_quote(get_quotes, tickers, broker) + # push initial smoke quote response for client initialization + await chan.send({'yield': payload, 'cid': cid}) + + # update map from each symbol to requesting client's chan + modify_quote_stream(broker, tickers, chan=chan, cid=cid) + + try: + if broker not in dtasks: + # no quoter task yet so start a daemon task + log.info(f"Spawning quoter task for {brokermod.name}") + async with trio.open_nursery() as nursery: + nursery.start_soon(partial( + fan_out_to_chans, brokermod, get_quotes, tickers2chans, + cid=cid) + ) + dtasks.add(broker) + + # unblocks when no more symbols subscriptions exist and the + # quote streamer task terminates (usually because another call + # was made to `modify_quoter` to unsubscribe from streaming + # symbols) + log.info(f"Terminated quoter task for {brokermod.name}") + + # TODO: move to AsyncExitStack in 3.7 + for _, _, cntxmng, _ in clients.values(): + # FIXME: yes I know there's no error handling.. + await cntxmng.__aexit__(None, None, None) + finally: + # if there are truly no more subscriptions with this broker + # drop from broker subs dict + if not any(tickers2chans.values()): + log.info(f"No more subscriptions for {broker}") + broker2tickersubs.pop(broker, None) + dtasks.discard(broker) + + +async def stream_to_file( + watchlist_name: str, + filename: str, + portal: tractor._portal.Portal, + tickers: List[str], + brokermod: ModuleType, + rate: int, +): + """Record client side received quotes to file ``filename``. + """ + # an async generator instance + agen = await portal.run( + "piker.brokers.data", 'start_quote_stream', + broker=brokermod.name, tickers=tickers) + + fname = filename or f'{watchlist_name}.jsonstream' + with open(fname, 'a') as f: + async for quotes in agen: + f.write(json.dumps(quotes)) + f.write('\n--\n') + + return fname + + +async def stream_from_file( + filename: str, +): + with open(filename, 'r') as quotes_file: + content = quotes_file.read() + + pkts = content.split('--')[:-1] # simulate 2 separate quote packets + payloads = [json.loads(pkt) for pkt in pkts] + for payload in cycle(payloads): + yield payload + await trio.sleep(0.3) diff --git a/piker/brokers/questrade.py b/piker/brokers/questrade.py index 746f23df..0f8738a5 100644 --- a/piker/brokers/questrade.py +++ b/piker/brokers/questrade.py @@ -2,9 +2,10 @@ Questrade API backend. """ import time -import datetime +from datetime import datetime from functools import partial import configparser +from typing import List, Tuple, Dict, Any import trio from async_generator import asynccontextmanager @@ -29,6 +30,75 @@ class QuestradeError(Exception): "Non-200 OK response code" +class _API: + """Questrade API endpoints exposed as methods and wrapped with an + http session. + """ + def __init__(self, session: asks.Session): + self._sess = session + + async def _request(self, path: str, params=None) -> dict: + resp = await self._sess.get(path=f'/{path}', params=params) + return resproc(resp, log) + + async def accounts(self) -> dict: + return await self._request('accounts') + + async def time(self) -> dict: + return await self._request('time') + + async def markets(self) -> dict: + return await self._request('markets') + + async def search(self, prefix: str) -> dict: + return await self._request( + 'symbols/search', params={'prefix': prefix}) + + async def symbols(self, ids: str = '', names: str = '') -> dict: + log.debug(f"Symbol lookup for {ids or names}") + return await self._request( + 'symbols', params={'ids': ids, 'names': names}) + + async def quotes(self, ids: str) -> dict: + return await self._request('markets/quotes', params={'ids': ids}) + + async def candles(self, id: str, start: str, end, interval) -> dict: + return await self._request(f'markets/candles/{id}', params={}) + + async def balances(self, id: str) -> dict: + return await self._request(f'accounts/{id}/balances') + + async def postions(self, id: str) -> dict: + return await self._request(f'accounts/{id}/positions') + + async def option_contracts(self, symbol_id: str) -> dict: + "Retrieve all option contract API ids with expiry -> strike prices." + contracts = await self._request(f'symbols/{symbol_id}/options') + return contracts['optionChain'] + + async def option_quotes( + self, + contracts: Dict[int, Dict[str, dict]], + option_ids: List[int] = [], # if you don't want them all + ) -> dict: + "Retrieve option chain quotes for all option ids or by filter(s)." + filters = [ + { + "underlyingId": int(symbol_id), + "expiryDate": str(expiry), + } + # every expiry per symbol id + for symbol_id, expiries in contracts.items() + for expiry in expiries + ] + + resp = await self._sess.post( + path=f'/markets/quotes/options', + json={'filters': filters, 'optionIds': option_ids} + ) + return resproc(resp, log)['optionQuotes'] + + class Client: """API client suitable for use as a long running broker daemon or single api requests. @@ -100,7 +170,7 @@ class Client: """ access_token = self.access_data.get('access_token') expires = float(self.access_data.get('expires_at', 0)) - expires_stamp = datetime.datetime.fromtimestamp( + expires_stamp = datetime.fromtimestamp( expires).strftime('%Y-%m-%d %H:%M:%S') if not access_token or (expires < time.time()) or force_refresh: log.debug( @@ -147,15 +217,26 @@ class Client: data = await self.api.symbols(names=','.join(tickers)) symbols2ids = {} for ticker, symbol in zip(tickers, data['symbols']): - symbols2ids[symbol['symbol']] = symbol['symbolId'] + symbols2ids[symbol['symbol']] = str(symbol['symbolId']) return symbols2ids - async def quote(self, tickers: [str]): - """Return quotes for each ticker in ``tickers``. + async def symbol_data(self, tickers: List[str]): + """Return symbol data for ``tickers``. """ t2ids = await self.tickers2ids(tickers) - ids = ','.join(map(str, t2ids.values())) + ids = ','.join(t2ids.values()) + symbols = {} + for pkt in (await self.api.symbols(ids=ids))['symbols']: + symbols[pkt['symbol']] = pkt + + return symbols + + async def quote(self, tickers: [str]): + """Return stock quotes for each ticker in ``tickers``. + """ + t2ids = await self.tickers2ids(tickers) + ids = ','.join(t2ids.values()) results = (await self.api.quotes(ids=ids))['quotes'] quotes = {quote['symbol']: quote for quote in results} @@ -167,58 +248,67 @@ class Client: return quotes - async def symbol_data(self, tickers: [str]): - """Return symbol data for ``tickers``. + async def symbol2contracts( + self, + symbol: str + ) -> Tuple[int, Dict[datetime, dict]]: + """Return option contract for the given symbol. + + The most useful part is the expiries which can be passed to the option + chain endpoint but specifc contract ids can be pulled here as well. """ - t2ids = await self.tickers2ids(tickers) - ids = ','.join(map(str, t2ids.values())) - symbols = {} - for pkt in (await self.api.symbols(ids=ids))['symbols']: - symbols[pkt['symbol']] = pkt + id = int((await self.tickers2ids([symbol]))[symbol]) + contracts = await self.api.option_contracts(id) + return id, { + # convert to native datetime objs for sorting + datetime.fromisoformat(item['expiryDate']): + item for item in contracts + } - return symbols + async def get_all_contracts( + self, + symbols: List[str], + # {symbol_id: {dt_iso_contract: {strike_price: {contract_id: id}}}} + ) -> Dict[int, Dict[str, Dict[int, Any]]]: + """Look up all contracts for each symbol in ``symbols`` and return the + of symbol ids to contracts by further organized by expiry and strike + price. + This routine is a bit slow doing all the contract lookups (a request + per symbol) and thus the return values should be cached for use with + ``option_chains()``. + """ + by_id = {} + for symbol in symbols: + id, contracts = await self.symbol2contracts(symbol) + by_id[id] = { + dt.isoformat(timespec='microseconds'): { + item['strikePrice']: item for item in + byroot['chainPerRoot'][0]['chainPerStrikePrice'] + } + for dt, byroot in sorted( + # sort by datetime + contracts.items(), + key=lambda item: item[0] + ) + } + return by_id -class _API: - """Questrade API endpoints exposed as methods and wrapped with an - http session. - """ - def __init__(self, session: asks.Session): - self._sess = session + async def option_chains( + self, + # see dict output from ``get_all_contracts()`` + contracts: dict, + ) -> Dict[str, Dict[str, Dict[str, Any]]]: + """Return option chain snap quote for each ticker in ``symbols``. + """ + quotes = await self.api.option_quotes(contracts) + batch = {} + for quote in quotes: + batch.setdefault( + quote['underlying'], {} + )[quote['symbol']] = quote - async def _request(self, path: str, params=None) -> dict: - resp = await self._sess.get(path=f'/{path}', params=params) - return resproc(resp, log) - - async def accounts(self) -> dict: - return await self._request('accounts') - - async def time(self) -> dict: - return await self._request('time') - - async def markets(self) -> dict: - return await self._request('markets') - - async def search(self, prefix: str) -> dict: - return await self._request( - 'symbols/search', params={'prefix': prefix}) - - async def symbols(self, ids: str = '', names: str = '') -> dict: - log.debug(f"Symbol lookup for {ids or names}") - return await self._request( - 'symbols', params={'ids': ids, 'names': names}) - - async def quotes(self, ids: str) -> dict: - return await self._request('markets/quotes', params={'ids': ids}) - - async def candles(self, id: str, start: str, end, interval) -> dict: - return await self._request(f'markets/candles/{id}', params={}) - - async def balances(self, id: str) -> dict: - return await self._request(f'accounts/{id}/balances') - - async def postions(self, id: str) -> dict: - return await self._request(f'accounts/{id}/positions') + return batch async def token_refresher(client): @@ -286,13 +376,18 @@ async def get_client() -> Client: write_conf(client) -async def quoter(client: Client, tickers: [str]): - """Quoter context. +async def quoter(client: Client, tickers: List[str]): + """Stock Quoter context. + + Yeah so fun times..QT has this symbol to ``int`` id lookup system that you + have to use to get any quotes. That means we try to be smart and maintain + a cache of this map lazily as requests from in for new tickers/symbols. + Most of the closure variables here are to deal with that. """ t2ids = {} ids = '' - def filter_symbols(quotes_dict): + def filter_symbols(quotes_dict: dict): nonlocal t2ids for symbol, quote in quotes_dict.items(): if quote['low52w'] is None: @@ -311,19 +406,28 @@ async def quoter(client: Client, tickers: [str]): # update ticker ids cache log.debug(f"Tickers set changed {new - current}") t2ids = await client.tickers2ids(tickers) + # re-save symbol -> ids cache ids = ','.join(map(str, t2ids.values())) try: quotes_resp = await client.api.quotes(ids=ids) except (QuestradeError, BrokerError) as qterr: if "Access token is invalid" in str(qterr.args[0]): - # out-of-process piker may have renewed already + # out-of-process piker actor may have + # renewed already.. client._reload_config() try: quotes_resp = await client.api.quotes(ids=ids) except BrokerError as qterr: if "Access token is invalid" in str(qterr.args[0]): + # TODO: this will crash when run from a sub-actor since + # STDIN can't be acquired. The right way to handle this + # is to make a request to the parent actor (i.e. + # spawner of this) to call this + # `client.ensure_access()` locally thus blocking until + # the user provides an API key on the "client side" await client.ensure_access(force_refresh=True) + quotes_resp = await client.api.quotes(ids=ids) else: raise @@ -337,10 +441,10 @@ async def quoter(client: Client, tickers: [str]): return quotes + # strip out unknown/invalid symbols first_quotes_dict = await get_quote(tickers) filter_symbols(first_quotes_dict) - - # re-save symbol ids cache + # re-save symbol -> ids cache ids = ','.join(map(str, t2ids.values())) return get_quote @@ -350,7 +454,7 @@ async def quoter(client: Client, tickers: [str]): # XXX: keys-values in this map define the final column values which will # be "displayable" but not necessarily used for "data processing" # (i.e. comparisons for sorting purposes or other calculations). -_qt_keys = { +_qt_stock_keys = { 'symbol': 'symbol', # done manually in qtconvert '%': '%', 'lastTradePrice': 'last', @@ -370,26 +474,29 @@ _qt_keys = { # 'low52w': 'low52w', # put in info widget # 'high52w': 'high52w', # "lastTradePriceTrHrs": 7.99, + # 'lastTradeTime': ('time', datetime.fromisoformat), # "lastTradeTick": "Equal", - # "lastTradeTime": "2018-01-30T18:28:23.434000-05:00", # "symbolId": 3575753, # "tier": "", # 'isHalted': 'halted', # as subscript 'h' # 'delay': 'delay', # as subscript 'p' } +# BidAskLayout columns which will contain three cells the first stacked on top +# of the other 2 _bidasks = { 'last': ['bid', 'ask'], 'size': ['bsize', 'asize'], 'VWAP': ['low', 'high'], + 'mktcap': ['vol', '$ vol'], } def format_quote( quote: dict, symbol_data: dict, - keymap: dict = _qt_keys, -) -> (dict, dict): + keymap: dict = _qt_stock_keys, +) -> Tuple[dict, dict]: """Remap a list of quote dicts ``quotes`` using the mapping of old keys -> new keys ``keymap`` returning 2 dicts: one with raw data and the other for display. diff --git a/piker/brokers/robinhood.py b/piker/brokers/robinhood.py index bd70c108..63cd8af7 100644 --- a/piker/brokers/robinhood.py +++ b/piker/brokers/robinhood.py @@ -59,7 +59,7 @@ class Client: return self._zip_in_order(symbols, resp['results']) async def symbol_data(self, symbols: [str]): - """Retrieve symbol data via the ``fundmentals`` endpoint. + """Retrieve symbol data via the ``fundamentals`` endpoint. """ return self._zip_in_order( symbols, diff --git a/piker/calc.py b/piker/calc.py index c4847696..679e2782 100644 --- a/piker/calc.py +++ b/piker/calc.py @@ -5,7 +5,7 @@ import math import itertools -def humanize(number): +def humanize(number, digits=1): """Convert large numbers to something with at most 3 digits and a letter suffix (eg. k: thousand, M: million, B: billion). """ @@ -20,7 +20,8 @@ def humanize(number): if mag < 3: return number maxmag = max(itertools.takewhile(lambda key: mag >= key, mag2suffix)) - return "{:.2f}{}".format(number/10**maxmag, mag2suffix[maxmag]) + return "{:.{digits}f}{}".format( + number/10**maxmag, mag2suffix[maxmag], digits=digits) def percent_change(init, new): diff --git a/piker/cli.py b/piker/cli.py index 717d2ef6..3ea0eaac 100644 --- a/piker/cli.py +++ b/piker/cli.py @@ -9,9 +9,10 @@ import click import pandas as pd import trio import tractor +from async_generator import asynccontextmanager from . import watchlists as wl -from .brokers import core, get_brokermod +from .brokers import core, get_brokermod, data from .log import get_console_log, colorize_json, get_logger log = get_logger('cli') @@ -23,20 +24,21 @@ _watchlists_data_path = os.path.join(_config_dir, 'watchlists.json') @click.command() @click.option('--loglevel', '-l', default='warning', help='Logging level') +@click.option('--tl', is_flag=True, help='Enable tractor logging') @click.option('--host', '-h', default='127.0.0.1', help='Host address to bind') -def pikerd(loglevel, host): - """Spawn the piker daemon. +def pikerd(loglevel, host, tl): + """Spawn the piker broker-daemon. """ get_console_log(loglevel) tractor.run_daemon( - rpc_module_paths=['piker.brokers.core'], + rpc_module_paths=['piker.brokers.data'], statespace={ 'broker2tickersubs': {}, 'clients': {}, 'dtasks': set(), }, name='brokerd', - loglevel=loglevel, + loglevel=loglevel if tl else None, ) @@ -90,7 +92,7 @@ def api(meth, kwargs, loglevel, broker, keys): help='Broker backend to use') @click.option('--loglevel', '-l', default='warning', help='Logging level') @click.option('--df-output', '-df', flag_value=True, - help='Ouput in `pandas.DataFrame` format') + help='Output in `pandas.DataFrame` format') @click.argument('tickers', nargs=-1, required=True) def quote(loglevel, broker, tickers, df_output): """Retreive symbol quotes on the console in either json or dataframe @@ -98,7 +100,7 @@ def quote(loglevel, broker, tickers, df_output): """ brokermod = get_brokermod(broker) get_console_log(loglevel) - quotes = trio.run(partial(core.quote, brokermod, tickers)) + quotes = trio.run(partial(core.stocks_quote, brokermod, tickers)) if not quotes: log.error(f"No quotes could be found for {tickers}?") return @@ -116,15 +118,40 @@ def quote(loglevel, broker, tickers, df_output): click.echo(colorize_json(quotes)) +@asynccontextmanager +async def maybe_spawn_brokerd_as_subactor(sleep=0.5, tries=10, loglevel=None): + """If no ``brokerd`` daemon-actor can be found spawn one in a + local subactor. + """ + async with tractor.open_nursery() as nursery: + async with tractor.find_actor('brokerd') as portal: + if not portal: + log.info( + "No broker daemon could be found, spawning brokerd..") + portal = await nursery.start_actor( + 'brokerd', + statespace={ + 'broker2tickersubs': {}, + 'clients': {}, + 'dtasks': set(), + }, + rpc_module_paths=['piker.brokers.data'], + loglevel=loglevel, + ) + yield portal + + @cli.command() @click.option('--broker', '-b', default=DEFAULT_BROKER, help='Broker backend to use') @click.option('--loglevel', '-l', default='warning', help='Logging level') -@click.option('--rate', '-r', default=5, help='Logging level') +@click.option('--tl', is_flag=True, help='Enable tractor logging') +@click.option('--rate', '-r', default=5, help='Quote rate limit') +@click.option('--test', '-t', help='Test quote stream file') @click.option('--dhost', '-dh', default='127.0.0.1', help='Daemon host address to connect to') @click.argument('name', nargs=1, required=True) -def monitor(loglevel, broker, rate, name, dhost): +def monitor(loglevel, broker, rate, name, dhost, test, tl): """Spawn a real-time watchlist. """ from .ui.monitor import _async_main @@ -137,28 +164,71 @@ def monitor(loglevel, broker, rate, name, dhost): log.error(f"No symbols found for watchlist `{name}`?") return - async def launch_client(sleep=0.5, tries=10): + async def main(tries): + async with maybe_spawn_brokerd_as_subactor( + tries=tries, loglevel=loglevel + ) as portal: + if test: + # stream from a local test file + agen = await portal.run( + "piker.brokers.data", 'stream_from_file', + filename=test + ) + # agen = data.stream_from_file(test) + else: + # start live streaming from broker daemon + agen = await portal.run( + "piker.brokers.data", 'start_quote_stream', + broker=brokermod.name, tickers=tickers) - async with tractor.open_nursery() as nursery: - async with tractor.find_actor('brokerd') as portal: - if not portal: - log.warn("No broker daemon could be found") - log.warning("Spawning local brokerd..") - portal = await nursery.start_actor( - 'brokerd', - statespace={ - 'broker2tickersubs': {}, - 'clients': {}, - 'dtasks': set(), - }, - rpc_module_paths=['piker.brokers.core'], - loglevel=loglevel, - ) + # run app "main" + await _async_main( + name, portal, tickers, + brokermod, rate, agen, + ) - # run kivy app - await _async_main(name, portal, tickers, brokermod, rate) + tractor.run( + partial(main, tries=1), + name='kivy-monitor', + loglevel=loglevel if tl else None, + ) - tractor.run(partial(launch_client, tries=1), name='kivy-watchlist') + +@cli.command() +@click.option('--broker', '-b', default=DEFAULT_BROKER, + help='Broker backend to use') +@click.option('--loglevel', '-l', default='warning', help='Logging level') +@click.option('--rate', '-r', default=5, help='Logging level') +@click.option('--filename', '-f', default='quotestream.jsonstream', + help='Logging level') +@click.option('--dhost', '-dh', default='127.0.0.1', + help='Daemon host address to connect to') +@click.argument('name', nargs=1, required=True) +def record(loglevel, broker, rate, name, dhost, filename): + """Record client side quotes to file + """ + log = get_console_log(loglevel) # activate console logging + brokermod = get_brokermod(broker) + watchlist_from_file = wl.ensure_watchlists(_watchlists_data_path) + watchlists = wl.merge_watchlist(watchlist_from_file, wl._builtins) + tickers = watchlists[name] + if not tickers: + log.error(f"No symbols found for watchlist `{name}`?") + return + + async def main(tries): + async with maybe_spawn_brokerd_as_subactor( + tries=tries, loglevel=loglevel + ) as portal: + # run app "main" + return await data.stream_to_file( + name, filename, + portal, tickers, + brokermod, rate, + ) + + filename = tractor.run(partial(main, tries=1), name='data-feed-recorder') + click.echo(f"Data feed recording saved to {filename}") @cli.group() @@ -247,3 +317,59 @@ def merge(ctx, watchlist_to_merge): @click.pass_context def dump(ctx, name): click.echo(json.dumps(ctx.obj['watchlist'])) + + +# options utils + +@cli.command() +@click.option('--broker', '-b', default=DEFAULT_BROKER, + help='Broker backend to use') +@click.option('--loglevel', '-l', default='warning', help='Logging level') +@click.option('--ids', flag_value=True, help='Include numeric ids in output') +@click.argument('symbol', required=True) +def contracts(loglevel, broker, symbol, ids): + brokermod = get_brokermod(broker) + get_console_log(loglevel) + quotes = trio.run(partial(core.contracts, brokermod, symbol)) + if not ids: + # just print out expiry dates which can be used with + # the option_chain_quote cmd + id, contracts = next(iter(quotes.items())) + quotes = list(contracts) + + click.echo(colorize_json(quotes)) + + +@cli.command() +@click.option('--broker', '-b', default=DEFAULT_BROKER, + help='Broker backend to use') +@click.option('--loglevel', '-l', default='warning', help='Logging level') +@click.option('--df-output', '-df', flag_value=True, + help='Output in `pandas.DataFrame` format') +@click.option('--date', '-d', help='Contracts expiry date') +@click.argument('symbol', required=True) +def optsquote(loglevel, broker, symbol, df_output, date): + """Retreive symbol quotes on the console in either + json or dataframe format. + """ + brokermod = get_brokermod(broker) + get_console_log(loglevel) + quotes = trio.run( + partial( + core.option_chain, brokermod, symbol, date + ) + )[symbol] + if not quotes: + log.error(f"No quotes could be found for {symbol}?") + return + + if df_output: + cols = next(filter(bool, quotes.values())).copy() + df = pd.DataFrame( + (quote.values() for contract, quote in quotes.items()), + index=quotes.keys(), + columns=cols.keys(), + ) + click.echo(df) + else: + click.echo(colorize_json(quotes)) diff --git a/piker/log.py b/piker/log.py index b12aeae2..d3f6d769 100644 --- a/piker/log.py +++ b/piker/log.py @@ -72,21 +72,21 @@ def get_console_log(level: str = None, name: str = None) -> logging.Logger: if level: log.setLevel(level.upper() if not isinstance(level, int) else level) - if not any( - handler.stream == sys.stderr for handler in log.handlers - if getattr(handler, 'stream', None) - ): + for handler in log.handlers: + if getattr(handler, 'stream', None) and handler.stream == sys.stderr: + break + else: handler = logging.StreamHandler() - formatter = colorlog.ColoredFormatter( - LOG_FORMAT, - datefmt=DATE_FORMAT, - log_colors=STD_PALETTE, - secondary_log_colors=BOLD_PALETTE, - style='{', - ) - handler.setFormatter(formatter) - log.addHandler(handler) + formatter = colorlog.ColoredFormatter( + LOG_FORMAT, + datefmt=DATE_FORMAT, + log_colors=STD_PALETTE, + secondary_log_colors=BOLD_PALETTE, + style='{', + ) + handler.setFormatter(formatter) + log.addHandler(handler) return log diff --git a/piker/ui/monitor.py b/piker/ui/monitor.py index 55b5923a..cc1fc2a8 100644 --- a/piker/ui/monitor.py +++ b/piker/ui/monitor.py @@ -41,7 +41,7 @@ def colorcode(name): return _colors[name if name else 'gray'] -_bs = 3 # border size +_bs = 4 # border size _color = [0.13]*3 # nice shade of gray _kv = (f''' #:kivy 1.10.0 @@ -74,7 +74,7 @@ _kv = (f''' spacing: '{_bs}dp' row_force_default: True - row_default_height: 75 + row_default_height: 63 cols: 1 @@ -143,7 +143,7 @@ class BidAskLayout(StackLayout): cell_type = HeaderCell if header else Cell top_size = cell_type().font_size small_size = top_size - 2 - top_prop = 0.7 # proportion of size used by top cell + top_prop = 0.55 # proportion of size used by top cell bottom_prop = 1 - top_prop for (key, size_hint, font_size), value in zip( [('last', (1, top_prop), top_size), @@ -175,6 +175,7 @@ class BidAskLayout(StackLayout): @row.setter def row(self, row): + # so hideous for cell in self.cells: cell.row = row @@ -338,7 +339,11 @@ async def update_quotes( else: color = colorcode('gray') + # row header and % cell color chngcell.color = hdrcell.color = color + # bgcolor = color.copy() + # bgcolor[-1] = 0.25 + # chngcell.background_color = bgcolor # if the cell has been "highlighted" make sure to change its color if hdrcell.background_color != [0]*4: @@ -356,9 +361,10 @@ async def update_quotes( color_row(row, record) cache[sym] = (record, row) + # render all rows once up front grid.render_rows(cache) - # core cell update loop + # real-time cell update loop async for quotes in agen: # new quotes data only for symbol, quote in quotes.items(): record, displayable = brokermod.format_quote( @@ -378,7 +384,7 @@ async def update_quotes( async def _async_main(name, portal, tickers, brokermod, rate): '''Launch kivy app + all other related tasks. - This is started with cli command `piker watch`. + This is started with cli cmd `piker monitor`. ''' # subscribe for tickers (this performs a possible filtering # where invalid symbols are discarded) diff --git a/setup.py b/setup.py index 3ba37c91..ac34c9c1 100755 --- a/setup.py +++ b/setup.py @@ -1,10 +1,21 @@ #!/usr/bin/env python -# + +# piker: destroy all suits # Copyright 2018 Tyler Goodlet -# -# This Source Code Form is subject to the terms of the Mozilla Public -# License, v. 2.0. If a copy of the MPL was not distributed with this -# file, You can obtain one at http://mozilla.org/MPL/2.0/. + +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. + +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. + +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . + from setuptools import setup with open('README.rst', encoding='utf-8') as f: @@ -43,7 +54,7 @@ setup( 'questrade': ['asks'], }, tests_require=['pytest'], - python_requires=">=3.6", + python_requires=">=3.7", # literally for ``datetime.datetime.fromisoformat``... keywords=["async", "trading", "finance", "quant", "charting"], classifiers=[ 'Development Status :: 3 - Alpha', diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 00000000..f7688a9d --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,22 @@ +import pytest + + +@pytest.fixture +def brokerconf(): + from piker.brokers import config + return config.load()[0] + + +@pytest.fixture +def us_symbols(): + return ['TSLA', 'AAPL', 'CGC', 'CRON'] + + +@pytest.fixture +def tmx_symbols(): + return ['APHA.TO', 'WEED.TO', 'ACB.TO'] + + +@pytest.fixture +def cse_symbols(): + return ['TRUL.CN', 'CWEB.CN', 'SNN.CN'] diff --git a/tests/test_questrade.py b/tests/test_questrade.py new file mode 100644 index 00000000..897ba531 --- /dev/null +++ b/tests/test_questrade.py @@ -0,0 +1,173 @@ +""" +Questrade broker testing +""" +import time + +import trio +from trio.testing import trio_test +from piker.brokers import questrade as qt +import pytest + + +@pytest.fixture(autouse=True) +def check_qt_conf_section(brokerconf): + """Skip this module's tests if we have not quetrade API creds. + """ + if not brokerconf.has_section('questrade'): + pytest.skip("No questrade API credentials available") + + +# stock quote +_ex_quote = { + "VWAP": 7.383792, + "askPrice": 7.56, + "askSize": 2, + "bidPrice": 6.1, + "bidSize": 2, + "delay": 0, + "high52w": 9.68, + "highPrice": 8, + "isHalted": 'false', + "lastTradePrice": 6.96, + "lastTradePriceTrHrs": 6.97, + "lastTradeSize": 2000, + "lastTradeTick": "Down", + "lastTradeTime": "2018-02-07T15:59:59.259000-05:00", + "low52w": 1.03, + "lowPrice": 6.88, + "openPrice": 7.64, + "symbol": "EMH.VN", + "symbolId": 10164524, + "tier": "", + "volume": 5357805 +} + + +# option quote +_ex_contract = { + 'VWAP': 0, + 'askPrice': None, + 'askSize': 0, + 'bidPrice': None, + 'bidSize': 0, + 'delay': 0, + 'delta': -0.212857, + 'gamma': 0.003524, + 'highPrice': 0, + 'isHalted': False, + 'lastTradePrice': 22, + 'lastTradePriceTrHrs': None, + 'lastTradeSize': 0, + 'lastTradeTick': 'Equal', + 'lastTradeTime': '2018-10-23T00:00:00.000000-04:00', + 'lowPrice': 0, + 'openInterest': 1, + 'openPrice': 0, + 'rho': -0.891868, + 'symbol': 'WEED15Jan21P54.00.MX', + 'symbolId': 22739148, + 'theta': -0.012911, + 'underlying': 'WEED.TO', + 'underlyingId': 16529510, + 'vega': 0.220885, + 'volatility': 75.514171, + 'volume': 0 +} + + +def match_packet(symbols, quotes): + """Verify target ``symbols`` match keys in ``quotes`` packet. + """ + assert len(quotes) == len(symbols) + for ticker in symbols: + quote = quotes.pop(ticker) + + # verify the quote packet format hasn't changed + for key in _ex_quote: + quote.pop(key) + + # no additional fields either + assert not quote + + # not more quotes then in target set + assert not quotes + + +@trio_test +async def test_batched_stock_quote(us_symbols): + """Use the client stock quote api and verify quote response format. + """ + async with qt.get_client() as client: + quotes = await client.quote(us_symbols) + assert len(quotes) == len(us_symbols) + match_packet(us_symbols, quotes) + + +@trio_test +async def test_quoter_context(us_symbols): + """Test that a quoter "context" used by the data feed daemon. + """ + async with qt.get_client() as client: + quoter = await qt.quoter(client, us_symbols) + quotes = await quoter(us_symbols) + match_packet(us_symbols, quotes) + + +@trio_test +async def test_option_contracts(tmx_symbols): + """Verify we can retrieve contracts by expiry. + """ + async with qt.get_client() as client: + for symbol in tmx_symbols: + id, contracts = await client.symbol2contracts(symbol) + assert isinstance(id, int) + assert isinstance(contracts, dict) + for dt in contracts: + assert dt.isoformat( + timespec='microseconds') == contracts[dt]['expiryDate'] + + +@trio_test +async def test_option_chain(tmx_symbols): + """Verify we can retrieve all option chains for a list of symbols. + """ + async with qt.get_client() as client: + # contract lookup - should be cached + contracts = await client.get_all_contracts(tmx_symbols) + # chains quote for all symbols + quotes = await client.option_chains(contracts) + for key in tmx_symbols: + contracts = quotes.pop(key) + for key, quote in contracts.items(): + for key in _ex_contract: + quote.pop(key) + assert not quote + # chains for each symbol were retreived + assert not quotes + + +@trio_test +async def test_option_quote_latency(tmx_symbols): + """Audit option quote latencies. + """ + async with qt.get_client() as client: + # all contracts lookup - should be cached + contracts = await client.get_all_contracts(['WEED.TO']) + + # build single expriry contract + id, by_expiry = next(iter(contracts.items())) + dt, by_strike = next(iter(by_expiry.items())) + single = {id: {dt: None}} + + for expected_latency, contract in [ + # NOTE: request latency is usually 2x faster that these + (5, contracts), (0.5, single) + ]: + for _ in range(10): + # chains quote for all symbols + start = time.time() + await client.option_chains(contract) + took = time.time() - start + print(f"Request took {took}") + assert took <= expected_latency + await trio.sleep(0.1) diff --git a/tests/test_tractor.py b/tests/test_tractor.py index 91d10214..7e63e3a7 100644 --- a/tests/test_tractor.py +++ b/tests/test_tractor.py @@ -5,11 +5,6 @@ import pytest import tractor -@pytest.fixture -def us_symbols(): - return ['TSLA', 'AAPL', 'CGC', 'CRON'] - - async def rx_price_quotes_from_brokerd(us_symbols): """Verify we can spawn a daemon actor and retrieve streamed price data. """ @@ -20,9 +15,9 @@ async def rx_price_quotes_from_brokerd(us_symbols): # no brokerd actor found portal = await nursery.start_actor( 'brokerd', - rpc_module_paths=['piker.brokers.core'], + rpc_module_paths=['piker.brokers.data'], statespace={ - 'brokers2tickersubs': {}, + 'broker2tickersubs': {}, 'clients': {}, 'dtasks': set() }, @@ -31,14 +26,14 @@ async def rx_price_quotes_from_brokerd(us_symbols): # gotta expose in a broker agnostic way... # retrieve initial symbol data # sd = await portal.run( - # 'piker.brokers.core', 'symbol_data', symbols=us_symbols) + # 'piker.brokers.data', 'symbol_data', symbols=us_symbols) # assert list(sd.keys()) == us_symbols gen = await portal.run( - 'piker.brokers.core', - '_test_price_stream', + 'piker.brokers.data', + 'start_quote_stream', broker='robinhood', - symbols=us_symbols, + tickers=us_symbols, ) # it'd sure be nice to have an asyncitertools here... async for quotes in gen: diff --git a/tests/test_watchlists.py b/tests/test_watchlists.py index 31511034..f35ee9d4 100644 --- a/tests/test_watchlists.py +++ b/tests/test_watchlists.py @@ -1,7 +1,6 @@ """ Watchlists testing. """ -import json import pytest import tempfile import os.path