Add initial Backtesting.py (squashed dev branch)

This commit is contained in:
Kernc
2018-01-21 11:25:28 +01:00
commit b1066f16fb
35 changed files with 14531 additions and 0 deletions

10
.codecov.yml Normal file
View File

@@ -0,0 +1,10 @@
coverage:
range: 75..95
precision: 0
status:
patch:
default:
target: '95'
project:
default:
target: auto

15
.coveragerc Normal file
View File

@@ -0,0 +1,15 @@
[run]
parallel = 1
concurrency =
multiprocessing
source =
backtesting
doc/examples
omit =
[report]
exclude_lines =
return
raise
except
warnings.warn

18
.gitignore vendored Normal file
View File

@@ -0,0 +1,18 @@
*.py[cod]
*.html
*.png
_version.py
*.egg-info
__pycache__/*
dist/*
.coverage
.coverage.*
htmlcov/*
doc/build/*
.idea/*
**/.ipynb_checkpoints
*~*

40
.travis.yml Normal file
View File

@@ -0,0 +1,40 @@
language: python
dist: trusty
sudo: false
cache:
pip: true
matrix:
fast_finish: true
include:
- python: '3.5'
- python: '3.7'
- python: '3.6'
name: 'Lint, Test w/ Coverage'
before_script:
- pip install flake8 coverage
script:
- flake8 --max-line-length=120 --exclude doc/examples .
- BOKEH_BROWSER=none catchsegv coverage run setup.py test
after_success:
- bash <(curl -s https://codecov.io/bash)
- python: '3.6'
name: 'Docs'
stage: deploy
install:
- pip install .[doc]
script:
- doc/build.sh
after_success:
- if [ "$TRAVIS_BRANCH" = "$TRAVIS_TAG" ]; then bash doc/deploy.sh; fi
before_install:
- set -eu
install:
- pip install .
script:
- time catchsegv python setup.py test

660
LICENSE.md Normal file
View File

@@ -0,0 +1,660 @@
### GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
### Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are 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.
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.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing
under this license.
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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your
version supports such interaction) an opportunity to receive the
Corresponding Source of your version by providing access to the
Corresponding Source from a network server at no charge, through some
standard or customary means of facilitating copying of software. This
Corresponding Source shall include the Corresponding Source for any
work covered by version 3 of the GNU General Public License that is
incorporated pursuant to the following paragraph.
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 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 work with which it is combined will remain governed by version
3 of the GNU General Public License.
#### 14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Affero 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 Affero 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 Affero 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 Affero 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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper
mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for
the specific requirements.
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 AGPL, see <https://www.gnu.org/licenses/>.

19
README.md Normal file
View File

@@ -0,0 +1,19 @@
Backtesting.py
==============
Backtest trading strategies with Python.
[![Build Status](https://travis-ci.org/kernc/backtesting.py.svg?branch=master)](https://travis-ci.org/kernc/backtesting.py)
[![Code Coverage](https://codecov.io/gh/kernc/backtesting.py/branch/master/graph/badge.svg)](https://codecov.io/gh/kernc/backtesting.py)
[![Backtesting on PyPI](https://img.shields.io/pypi/pyversions/backtesting.svg)](https://pypi.org/project/backtesting/)
[**Project website**](https://kernc.github.io/backtesting.py/)
[Documentation](https://kernc.github.io/backtesting.py/doc/backtesting/)
Development
-----------
Fork the project. Then:
git clone git@github.com:YOUR_USERNAME/backtesting.py
cd backtesting.py
pip3 install -e .[doc]

40
backtesting/__init__.py Normal file
View File

@@ -0,0 +1,40 @@
"""
# Backtesting.py Documentation
## Manuals
* [Quick Start User Guide](../examples/Quick Start User Guide.html)
## Tutorials
* [Library of Utilities and Composable Base Strategies](../examples/Strategies Library.html)
* [Multiple Time Frames](../examples/Multiple Time Frames.html)
* [Parameter Heatmap](../examples/Parameter Heatmap.html)
You can also [try these out] live.
[try these out]: https://mybinder.org/v2/gh/kernc/backtesting.py/master?urlpath=lab%2Ftree%2Fdoc%2Fexamples
## Example Strategies
* (contributions welcome)
## License
This software is licensed under the terms of [AGPL 3.0],
meaning you can use it for any reasonable purpose and remain in
complete ownership of all the excellent trading strategies you produce,
but you are also encouraged to make sure any upgrades to `backtesting`
itself find their way back to the community.
[AGPL 3.0]: https://www.gnu.org/licenses/agpl-3.0.html
# API Reference Documentation
"""
try:
from ._version import version as __version__ # noqa: F401
except ImportError:
pass # Package not installed
from .backtesting import Backtest, Strategy, Orders, Position # noqa: F401
from . import lib # noqa: F401

599
backtesting/_plotting.py Normal file
View File

@@ -0,0 +1,599 @@
import os
import warnings
from itertools import cycle, combinations
from functools import partial
import numpy as np
import pandas as pd
from bokeh.plotting import figure as _figure
from bokeh.models import (
CustomJS,
ColumnDataSource,
NumeralTickFormatter,
Span,
HoverTool,
Range1d,
DatetimeTickFormatter,
FuncTickFormatter,
WheelZoomTool,
LinearColorMapper,
)
from bokeh.io import output_notebook, output_file, show
from bokeh.io.state import curstate
from bokeh.layouts import gridplot
from bokeh.palettes import Category10
from bokeh.transform import factor_cmap
from backtesting._util import _data_period
IS_JUPYTER_NOTEBOOK = 'JPY_PARENT_PID' in os.environ
if IS_JUPYTER_NOTEBOOK:
warnings.warn('Jupyter Notebook detected. '
'Setting Bokeh output to notebook. '
'This may not work in Jupyter clients without JavaScript '
'support (e.g. PyCharm, Spyder IDE). '
'Reset with `bokeh.io.reset_output()`.')
output_notebook()
with open(os.path.join(os.path.dirname(__file__), 'autoscale_cb.js'),
encoding='utf-8') as _f:
_AUTOSCALE_JS_CALLBACK = _f.read()
def _bokeh_reset(filename=None):
curstate().reset()
# Test if we are in Jupyter notebook
if IS_JUPYTER_NOTEBOOK:
curstate().output_notebook()
elif filename:
if not filename.endswith('.html'):
filename += '.html'
output_file(filename, title=filename)
def colorgen():
yield from cycle(Category10[10])
def plot(*, results, df, indicators, filename='', plot_width=1200,
plot_equity=True, plot_pl=True,
plot_volume=True, plot_drawdown=False,
smooth_equity=False, relative_equity=True, omit_missing=True,
superimpose=True, show_legend=True, open_browser=True):
"""
Like much of GUI code everywhere, this is a mess.
"""
# We need to reset global Bokeh state, otherwise subsequent runs of
# plot() contain some previous run's cruft data (was noticed when
# TestPlot.test_file_size() test was failing).
_bokeh_reset(filename)
COLORS = ['tomato', 'lime']
COLORS_LIGHT = ['#ffe3e3', '#e3ffe3']
orig_trade_data = trade_data = results._trade_data.copy(False)
orig_df = df = df.copy(False)
df.index.name = None # Provides source name @index
index = df.index
time_resolution = getattr(index, 'resolution', None)
is_datetime_index = index.is_all_dates
# If all Volume is NaN, don't plot volume
plot_volume = plot_volume and not df.Volume.isnull().all()
# OHLC vbar width in msec.
# +1 will work in case of non-datetime index where vbar width should just be =1
width = 1 + dict(day=86400,
hour=3600,
minute=60,
second=1).get(time_resolution, 0) * 1000 * .85
if is_datetime_index:
# Add index as a separate data source column because true .index is offset to align vbars
df['datetime'] = index
df.index = df.index + pd.Timedelta(width / 2, unit='ms')
if omit_missing:
width = .8
df = df.reset_index(drop=True)
trade_data = trade_data.reset_index(drop=True)
index = df.index
new_bokeh_figure = partial(
_figure,
x_axis_type='datetime' if is_datetime_index and not omit_missing else 'linear',
plot_width=plot_width,
plot_height=400,
tools="xpan,xwheel_zoom,box_zoom,undo,redo,reset,crosshair,save",
active_drag='xpan',
active_scroll='xwheel_zoom')
pad = (index[-1] - index[0]) / 20
fig_ohlc = new_bokeh_figure(
x_range=Range1d(index[0], index[-1],
bounds=(index[0] - pad,
index[-1] + pad)) if index.size > 1 else None)
figs_above_ohlc, figs_below_ohlc = [], []
source = ColumnDataSource(df)
source.add((df.Close >= df.Open).values.astype(np.uint8).astype(str), 'inc')
returns = trade_data['Returns'].dropna()
trade_source = ColumnDataSource(dict(
index=returns.index,
datetime=orig_trade_data['Returns'].dropna().index,
exit_price=trade_data['Exit Price'].dropna(),
returns_pos=(returns > 0).astype(np.int8).astype(str),
))
inc_cmap = factor_cmap('inc', COLORS, ['0', '1'])
cmap = factor_cmap('returns_pos', COLORS, ['0', '1'])
if is_datetime_index and omit_missing:
fig_ohlc.xaxis.formatter = FuncTickFormatter(
args=dict(axis=fig_ohlc.xaxis[0],
formatter=DatetimeTickFormatter(days=['%d %b', '%a %d'],
months=['%m/%Y', "%b'%y"]),
source=source),
code='''
this.labels = this.labels || formatter.doFormat(ticks
.map(i => source.data.datetime[i])
.filter(t => t !== undefined));
return this.labels[index] || "";
''')
NBSP = '&nbsp;' * 4
ohlc_extreme_values = df[['High', 'Low']].copy(False)
ohlc_tooltips = [
('x, y', NBSP.join(('$index',
'$y{0,0.0[0000]}'))),
('OHLC', NBSP.join(('@Open{0,0.0[0000]}',
'@High{0,0.0[0000]}',
'@Low{0,0.0[0000]}',
'@Close{0,0.0[0000]}'))),
('Volume', '@Volume{0,0}')]
def new_indicator_figure(**kwargs):
kwargs.setdefault('plot_height', 90)
fig = new_bokeh_figure(x_range=fig_ohlc.x_range,
active_scroll='xwheel_zoom',
active_drag='xpan',
**kwargs)
fig.xaxis.visible = False
fig.yaxis.minor_tick_line_color = None
return fig
def set_tooltips(fig, tooltips=(), vline=True, renderers=(), show_arrow=True):
tooltips = list(tooltips)
renderers = list(renderers)
if is_datetime_index:
formatters = dict(datetime='datetime')
tooltips = [("Date", "@datetime{%c}")] + tooltips
else:
formatters = {}
tooltips = [("#", "@index")] + tooltips
fig.add_tools(HoverTool(
point_policy='follow_mouse',
renderers=renderers, formatters=formatters, show_arrow=show_arrow,
tooltips=tooltips, mode='vline' if vline else 'mouse'))
def _plot_equity_section():
"""Equity section"""
# Max DD Dur. line
equity = trade_data['Equity']
argmax = trade_data['Drawdown Duration'].idxmax()
try:
dd_start = equity[:argmax].idxmax()
except Exception: # ValueError: attempt to get argmax of an empty sequence
dd_start = dd_end = equity.index[0]
timedelta = 0
else:
dd_end = (equity[argmax:] > equity[dd_start]).idxmax()
if dd_end == argmax:
dd_end = index[-1]
if is_datetime_index and omit_missing:
# "Calendar" duration
timedelta = df.datetime.iloc[dd_end] - df.datetime.iloc[dd_start]
else:
timedelta = dd_end - dd_start
# Get point intersection
if dd_end != index[-1]:
x1, x2 = index.get_loc(dd_end) - 1, index.get_loc(dd_end)
y, y1, y2 = equity[dd_start], equity[x1], equity[x2]
dd_end -= (1 - (y - y1) / (y2 - y1)) * (dd_end - index[x1]) # y = a x + b
if smooth_equity:
select = (trade_data[['Entry Price',
'Exit Price']].dropna(how='all').index |
# Include beginning
equity.index[:1] |
# Include max dd end points. Otherwise, the MaxDD line looks amiss.
pd.Index([dd_start, dd_end]))
equity = equity[select].reindex(equity.index)
equity.interpolate(inplace=True)
if relative_equity:
equity /= equity.iloc[0]
source.add(equity, 'equity')
fig = new_indicator_figure(
y_axis_label="Equity",
**({} if plot_drawdown else dict(plot_height=110)))
# High-watermark drawdown dents
fig.patch('index', 'equity_dd',
source=ColumnDataSource(dict(
index=np.r_[index, index[::-1]],
equity_dd=np.r_[equity, equity.cummax()[::-1]]
)),
fill_color='#ffffea', line_color='#ffcb66')
# Equity line
r = fig.line('index', 'equity', source=source, line_width=1.5, line_alpha=1)
if relative_equity:
tooltip_format = '@equity{+0,0.[000]%}'
tick_format = '0,0.[00]%'
legend_format = '{:,.0f}%'
else:
tooltip_format = '@equity{$ 0,0}'
tick_format = '$ 0.0 a'
legend_format = '${:,.0f}'
set_tooltips(fig, [('Equity', tooltip_format)], renderers=[r])
fig.yaxis.formatter = NumeralTickFormatter(format=tick_format)
# Peaks
argmax = equity.idxmax()
fig.scatter(argmax, equity[argmax],
legend='Peak ({})'.format(
legend_format.format(equity[argmax] * (100 if relative_equity else 1))),
color='cyan', size=8)
fig.scatter(index[-1], equity.values[-1],
legend='Final ({})'.format(
legend_format.format(equity.iloc[-1] * (100 if relative_equity else 1))),
color='blue', size=8)
if not plot_drawdown:
drawdown = trade_data['Drawdown']
argmax = drawdown.idxmax()
fig.scatter(argmax, equity[argmax],
legend='Max Drawdown (-{:.1f}%)'.format(100 * drawdown[argmax]),
color='red', size=8)
fig.line([dd_start, dd_end], equity[dd_start],
line_color='red', line_width=2,
legend='Max Dd Dur. ({})'.format(timedelta)
.replace(' 00:00:00', '')
.replace('(0 days ', '('))
figs_above_ohlc.append(fig)
def _plot_drawdown_section():
"""Drawdown section"""
fig = new_indicator_figure(y_axis_label="Drawdown")
drawdown = trade_data['Drawdown']
argmax = drawdown.idxmax()
source.add(drawdown, 'drawdown')
r = fig.line('index', 'drawdown', source=source, line_width=1.3)
fig.scatter(argmax, drawdown[argmax],
legend='Peak (-{:.1f}%)'.format(100 * drawdown[argmax]),
color='red', size=8)
set_tooltips(fig, [('Drawdown', '@drawdown{-0.[0]%}')], renderers=[r])
fig.yaxis.formatter = NumeralTickFormatter(format="-0.[0]%")
return fig
def _plot_pl_section():
"""Profit/Loss markers section"""
fig = new_indicator_figure(y_axis_label="Profit / Loss")
fig.add_layout(Span(location=0, dimension='width', line_color='#666666',
line_dash='dashed', line_width=1))
position = trade_data['Exit Position'].dropna()
returns_long = returns.copy()
returns_short = returns.copy()
returns_long[position < 0] = np.nan
returns_short[position > 0] = np.nan
trade_source.add(returns_long, 'returns_long')
trade_source.add(returns_short, 'returns_short')
MARKER_SIZE = 13
r1 = fig.scatter('index', 'returns_long', source=trade_source, fill_color=cmap,
marker='triangle', line_color='black', size=MARKER_SIZE)
r2 = fig.scatter('index', 'returns_short', source=trade_source, fill_color=cmap,
marker='inverted_triangle', line_color='black', size=MARKER_SIZE)
set_tooltips(fig, [("P/L", "@returns_long{+0.[000]%}")], vline=False, renderers=[r1])
set_tooltips(fig, [("P/L", "@returns_short{+0.[000]%}")], vline=False, renderers=[r2])
fig.yaxis.formatter = NumeralTickFormatter(format="0.[00]%")
return fig
def _plot_volume_section():
"""Volume section"""
fig = new_indicator_figure(y_axis_label="Volume")
fig.xaxis.formatter = fig_ohlc.xaxis[0].formatter
fig.xaxis.visible = True
fig_ohlc.xaxis.visible = False # Show only Volume's xaxis
r = fig.vbar('index', width, 'Volume', source=source, color=inc_cmap)
set_tooltips(fig, [('Volume', '@Volume{0.00 a}')], renderers=[r])
fig.yaxis.formatter = NumeralTickFormatter(format="0 a")
return fig
def _plot_superimposed_ohlc():
"""Superimposed, downsampled vbars"""
resample_rule = (superimpose if isinstance(superimpose, str) else
dict(day='W',
hour='D',
minute='H',
second='T',
millisecond='S').get(time_resolution))
if not resample_rule:
warnings.warn(
"'Can't superimpose OHLC data with rule '{}' (index datetime resolution: '{}'). "
"Skipping.".format(resample_rule, time_resolution),
stacklevel=4)
return
orig_df['_width'] = 1
from .lib import OHLCV_AGG
df2 = orig_df.resample(resample_rule, label='left').agg(dict(OHLCV_AGG, _width='count'))
# Check if resampling was downsampling; error on upsampling
orig_freq = _data_period(orig_df)
resample_freq = _data_period(df2)
if resample_freq < orig_freq:
raise ValueError('Invalid value for `superimpose`: Upsampling not supported.')
if resample_freq == orig_freq:
warnings.warn('Superimposed OHLC plot matches the original plot. Skipping.',
stacklevel=4)
return
if omit_missing:
width2 = '_width'
df2.index = df2['_width'].cumsum().shift(1).fillna(0)
df2.index += df2['_width'] / 2 - .5
df2['_width'] -= .1 # Candles don't touch
else:
del df['_width']
width2 = dict(day=86400 * 5,
hour=86400,
minute=3600,
second=60)[time_resolution] * 1000
df2.index += pd.Timedelta(
width2 / 2 +
(width2 / 5 if resample_rule == 'W' else 0), # Sunday week start
unit='ms')
df2['inc'] = (df2.Close >= df2.Open).astype(np.uint8).astype(str)
df2.index.name = None
source2 = ColumnDataSource(df2)
fig_ohlc.segment('index', 'High', 'index', 'Low', source=source2, color='#bbbbbb')
fig_ohlc.vbar('index', width2, 'Open', 'Close', source=source2, line_color=None,
fill_color=factor_cmap('inc', COLORS_LIGHT, ['0', '1']))
def _plot_ohlc():
"""Main OHLC bars"""
fig_ohlc.segment('index', 'High', 'index', 'Low', source=source, color="black")
r = fig_ohlc.vbar('index', width, 'Open', 'Close', source=source,
line_color="black", fill_color=inc_cmap)
return r
def _plot_ohlc_orders():
"""Order entry / exit markers on OHLC plot"""
exit_price = trade_data['Exit Price'].dropna()
entry_price = trade_data['Entry Price'].dropna().iloc[:exit_price.size] # entry can be one more at the end # noqa: E501
trade_source.add(np.column_stack((entry_price.index, exit_price.index)).tolist(),
'position_lines_xs')
trade_source.add(np.column_stack((entry_price, exit_price)).tolist(),
'position_lines_ys')
fig_ohlc.multi_line(xs='position_lines_xs', ys='position_lines_ys',
source=trade_source, line_color=cmap,
legend='Trades',
line_width=8, line_alpha=1, line_dash='dotted')
def _plot_indicators():
"""Strategy indicators"""
def _too_many_dims(value):
assert value.ndim >= 2
if value.ndim > 2:
warnings.warn("Can't plot indicators with >2D ('{}')".format(value.name),
stacklevel=5)
return True
return False
class LegendStr(str):
# The legend string is such a string that only matches
# itself if it's the exact same object. This ensures
# legend items are listed separately even when they have the
# same string contents. Otherwise, Bokeh would always consider
# equal strings as one and the same legend item.
# This also prevents legend items named the same as some
# ColumnDataSource's column to be replaced with that column's
# values.
def __eq__(self, other):
return self is other
ohlc_colors = colorgen()
for value in indicators:
value = np.atleast_2d(value)
# Use .get()! A user might have assigned a Strategy.data-evolved
# _Array without Strategy.I()
if not value._opts.get('plot') or _too_many_dims(value):
continue
color = value._opts['color']
tooltips = []
# Overlay indicators on the OHLC figure
if value._opts['overlay']:
color = color or next(ohlc_colors)
legend = LegendStr(value.name)
for i, arr in enumerate(value):
source_name = '{}_{}'.format(value.name, i)
source.add(arr, source_name)
fig_ohlc.line('index', source_name, source=source,
line_width=1.3, line_color=color, legend=legend)
ohlc_extreme_values[source_name] = arr
tooltips.append('@{{{}}}{{0,0.0[0000]}}'.format(source_name))
ohlc_tooltips.append((value.name, NBSP.join(tooltips)))
else:
# Standalone indicator sections at the bottom
color = color or colorgen()
fig = new_indicator_figure()
for i, arr in enumerate(value, 1):
legend = '{}-{}'.format(value.name, i) if len(value) > 1 else value.name
name = legend + '_' # Otherwise fig.line(legend=) is interpreted as col of source # noqa: E501
tooltips.append('@{{{}}}'.format(name))
source.add(arr.astype(int if arr.dtype == bool else float), name)
r = fig.line('index', name, source=source,
line_color=next(color), line_width=1.3, legend=LegendStr(legend))
# Add dashed centerline just because
mean = float(pd.Series(arr).mean())
if not np.isnan(mean) and (abs(mean) < .1 or
round(abs(mean), -1) in (50, 100, 200)):
fig.add_layout(Span(location=float(mean), dimension='width',
line_color='#666666', line_dash='dashed',
line_width=.5))
set_tooltips(fig, [(value.name, NBSP.join(tooltips))], vline=True, renderers=[r])
# If the sole indicator line on this figure,
# have the legend only contain text without the glyph
if len(value) == 1:
fig.legend.glyph_width = 0
figs_below_ohlc.append(fig)
# Construct figure ...
if plot_equity:
_plot_equity_section()
if plot_drawdown:
figs_above_ohlc.append(_plot_drawdown_section())
if plot_pl:
figs_above_ohlc.append(_plot_pl_section())
if plot_volume:
fig_volume = _plot_volume_section()
figs_below_ohlc.append(fig_volume)
if superimpose and is_datetime_index:
_plot_superimposed_ohlc()
ohlc_bars = _plot_ohlc()
_plot_ohlc_orders()
_plot_indicators()
set_tooltips(fig_ohlc, ohlc_tooltips, vline=True, renderers=[ohlc_bars])
source.add(ohlc_extreme_values.min(1), 'ohlc_low')
source.add(ohlc_extreme_values.max(1), 'ohlc_high')
custom_js_args = dict(ohlc_range=fig_ohlc.y_range,
source=source)
if plot_volume:
custom_js_args.update(volume_range=fig_volume.y_range)
fig_ohlc.x_range.callback = CustomJS(args=custom_js_args,
code=_AUTOSCALE_JS_CALLBACK)
plots = figs_above_ohlc + [fig_ohlc] + figs_below_ohlc
for f in plots:
if f.legend:
f.legend.location = 'top_left' if show_legend else None
f.legend.border_line_width = 1
f.legend.border_line_color = '#333333'
f.legend.padding = 5
f.legend.spacing = 0
f.legend.margin = 0
f.legend.label_text_font_size = '8pt'
f.min_border_left = 0
f.min_border_top = 3
f.min_border_bottom = 6
f.min_border_right = 10
f.outline_line_color = '#666666'
wheelzoom_tool = next(wz for wz in f.tools if isinstance(wz, WheelZoomTool))
wheelzoom_tool.maintain_focus = False
fig = gridplot(
plots,
ncols=1,
toolbar_location='right',
# sizing_mode='stretch_width',
toolbar_options=dict(logo=None),
merge_tools=True,
)
show(fig, browser=None if open_browser else 'none')
return fig
def plot_heatmaps(heatmap: pd.Series, agg: str, ncols: int,
filename: str = '', plot_width: int = 1200, open_browser: bool = True):
if not (isinstance(heatmap, pd.Series) and
isinstance(heatmap.index, pd.MultiIndex)):
raise ValueError('heatmap must be heatmap Series as returned by '
'`Backtest.optimize(..., return_heatmap=True)`')
_bokeh_reset()
if filename:
output_file(filename)
param_combinations = combinations(heatmap.index.names, 2)
dfs = [heatmap.groupby(list(dims)).agg(agg).to_frame(name='_Value')
for dims in param_combinations]
plots = []
cmap = LinearColorMapper(palette='Viridis256',
low=min(df.min().min() for df in dfs),
high=max(df.max().max() for df in dfs),
nan_color='white')
for df in dfs:
name1, name2 = df.index.names
level1 = df.index.levels[0].astype(str).tolist()
level2 = df.index.levels[1].astype(str).tolist()
df = df.reset_index()
df[name1] = df[name1].astype('str')
df[name2] = df[name2].astype('str')
fig = _figure(x_range=level1,
y_range=level2,
x_axis_label=name1,
y_axis_label=name2,
plot_width=plot_width // ncols,
plot_height=plot_width // ncols,
tools='box_zoom,reset,save',
tooltips=[(name1, '@' + name1),
(name2, '@' + name2),
('Value', '@_Value{0.[000]}')])
fig.grid.grid_line_color = None
fig.axis.axis_line_color = None
fig.axis.major_tick_line_color = None
fig.axis.major_label_standoff = 0
fig.rect(x=name1,
y=name2,
width=1,
height=1,
source=df,
line_color=None,
fill_color=dict(field='_Value',
transform=cmap))
plots.append(fig)
fig = gridplot(
plots,
ncols=ncols,
toolbar_options=dict(logo=None),
toolbar_location='above',
merge_tools=True,
)
show(fig, browser=None if open_browser else 'none')
return fig

135
backtesting/_util.py Normal file
View File

@@ -0,0 +1,135 @@
from numbers import Number
import numpy as np
def _as_str(value):
if isinstance(value, (Number, str)):
return str(value)
name = str(getattr(value, 'name', '') or '')
if callable(value):
name = value.__name__.replace('<lambda>', '')
if name in ('Open', 'High', 'Low', 'Close'):
name = name[:1]
if len(name) > 10:
name = name[:9] + ''
return name
def _data_period(df):
"""Return data index period as pd.Timedelta"""
return df.index[:100].to_series().diff().median()
class _Array(np.ndarray):
"""
ndarray extended to supply .name and other arbitrary properties
in ._opts dict.
"""
def __new__(cls, array, name=None, write=False, **kwargs):
obj = np.asarray(array).view(cls)
obj.name = name or array.name
obj._opts = kwargs
if not write:
obj.setflags(write=False)
return obj
def __array_finalize__(self, obj):
if obj is not None:
self.name = getattr(obj, 'name', '')
self._opts = getattr(obj, '_opts', {})
def __bool__(self):
try:
return bool(self[-1])
except IndexError:
return super().__bool__()
def __float__(self):
try:
return float(self[-1])
except IndexError:
return super().__float__()
class _Indicator(_Array):
pass
class _Data:
"""
A data array accessor. Provides access to OHLCV "columns"
as a standard `pd.DataFrame` would, except it's not a DataFrame
and the returned "series" are _not_ `pd.Series` but `np.ndarray`
for performance reasons.
"""
def __init__(self, df):
self.__i = len(df)
self.__pip = None
self.__cache = {}
self.__arrays = {col: _Array(arr, data=self)
for col, arr in df.items()}
# Leave index as Series because pd.Timestamp nicer API to work with
self.__arrays['__index'] = df.index.copy()
def __getitem__(self, item):
return getattr(self, item)
def __getattr__(self, item):
try:
return self.__get_array(item)
except KeyError:
raise KeyError("Column '{}' not in data".format(item)) from None
def _set_length(self, i):
self.__i = i
self.__cache.clear()
def __len__(self):
return self.__i
@property
def pip(self):
if self.__pip is None:
self.__pip = 10**-np.median([len(s.partition('.')[-1])
for s in self.__arrays['Close'].astype(str)])
return self.__pip
def __get_array(self, key):
arr = self.__cache.get(key)
if arr is None:
arr = self.__cache[key] = self.__arrays[key][:self.__i]
return arr
@property
def Open(self):
return self.__get_array('Open')
@property
def High(self):
return self.__get_array('High')
@property
def Low(self):
return self.__get_array('Low')
@property
def Close(self):
return self.__get_array('Close')
@property
def Volume(self):
return self.__get_array('Volume')
@property
def index(self):
return self.__get_array('__index')
# Make pickling in Backtest.optimize() work with our catch-all __getattr__
def __getstate__(self):
return self.__dict__
def __setstate__(self, state):
self.__dict__ = state

View File

@@ -0,0 +1,64 @@
if (!window._bt_extremes)
window._bt_extremes = function (arr, initial, agg_func) {
const CHUNK = 32768;
let extreme = initial;
for (let i = 0, len = arr.length; i < len; i += CHUNK) {
const subarr = CHUNK >= len ? arr : arr.slice(i, i + CHUNK);
extreme = agg_func(extreme, agg_func.apply(null, subarr));
}
return extreme;
};
if (!window._bt_bin_search)
window._bt_bin_search = function (index, value) {
let mid,
min = 0,
max = index.length - 1;
while (min < max) {
mid = (min + max) / 2 | 0;
if (index[mid] < value)
min = mid + 1;
else
max = mid - 1;
}
return min;
};
if (!window._bt_scale_range)
window._bt_scale_range = function (range, highs, lows) {
const max = _bt_extremes(highs, -Infinity, Math.max),
min = lows && _bt_extremes(lows, Infinity, Math.min);
if (min !== Infinity && max !== -Infinity) {
const pad = (max - min) * .03;
range.start = min - pad;
range.end = max + pad;
}
};
clearTimeout(window._bt_autoscale_timeout);
window._bt_autoscale_timeout = setTimeout(function () {
/**
* @variable cb_obj `fig_ohlc.x_range`.
* @variable source `ColumnDataSource`
* @variable ohlc_range `fig_ohlc.y_range`.
* @variable volume_range `fig_volume.y_range`.
*/
let index = source.data['index'],
i = Math.max(_bt_bin_search(index, cb_obj.start) - 1, 0),
j = Math.min(_bt_bin_search(index, cb_obj.end) + 1, index.length);
_bt_scale_range(
ohlc_range,
source.data['ohlc_high'].slice(i, j),
source.data['ohlc_low'].slice(i, j));
try {
_bt_scale_range(
volume_range,
source.data['Volume'].slice(i, j),
0);
} catch (e) {} // volume_range may be undefined
}, 50);

987
backtesting/backtesting.py Normal file
View File

@@ -0,0 +1,987 @@
"""
Core backtesting data structures.
Stuff from this module can be imported from the top-level
module directly, e.g.
from backtesting import Backtest, Strategy
"""
import os
import re
import sys
import warnings
from abc import abstractmethod, ABCMeta
from collections import Sequence
from concurrent.futures import ProcessPoolExecutor, as_completed
from functools import partial
from itertools import repeat, product, chain
from numbers import Number
from typing import Callable, Union, Tuple
import numpy as np
import pandas as pd
from ._plotting import plot
from ._util import _as_str, _Indicator, _Data, _data_period
__pdoc__ = {
'Strategy.__init__': None,
'Orders.__init__': None,
'Position.__init__': None,
}
_MARKET_PRICE = 'market'
class Strategy(metaclass=ABCMeta):
"""
A trading strategy base class. Extend this class and
override methods
`backtesting.backtesting.Strategy.init` and
`backtesting.backtesting.Strategy.next` to define
your own strategy.
"""
def __init__(self, broker, data):
self._indicators = []
self._broker = broker # type: _Broker
self._data = data # type: _Data
self._params = {}
def __repr__(self):
return '<Strategy ' + str(self) + '>'
def __str__(self):
params = ','.join('{}={}'.format(*p) for p in zip(self._params.keys(),
map(_as_str, self._params.values())))
if params:
params = '(' + params + ')'
return '{}{}'.format(self.__class__.__name__, params)
def _set_params(self, **kwargs):
for k, v in kwargs.items():
if not hasattr(self, k):
raise AttributeError(
"Strategy '{}' is missing parameter '{}'. Strategy class "
"should define parameters as class variables before they "
"can be optimized or run with.".format(self.__class__.__name__, k))
setattr(self, k, v)
self._params = kwargs
def I(self, # noqa: E743
func: Callable, *args,
name=None, plot=True, overlay=None, color=None,
**kwargs) -> np.ndarray:
"""
Declare indicator. An indicator is just an array of values,
but one that is revealed gradually in
`backtesting.backtesting.Strategy.next` much like
`backtesting.backtesting.Strategy.data` is.
Returns `np.ndarray` of indicator values.
`func` is a function that returns the indicator array of
same length as `backtesting.backtesting.Strategy.data`.
In the plot legend, the indicator is labeled with
function name, unless `name` overrides it.
If `plot` is `True`, the indicator is plotted on the resulting
`backtesting.backtesting.Backtest.plot`.
If `overlay` is `True`, the indicator is plotted overlaying the
price candlestick chart (suitable e.g. for moving averages).
If `False`, the indicator is plotted standalone below the
candlestick chart. By default, a heuristic is used which decides
correctly most of the time.
`color` can be string hex RGB triplet. By default, the next
available color is assigned.
Additional `*args` and `**kwargs` are passed to `func` and can
be used for parameters.
For example, using simple moving average function from TA-Lib:
def init():
self.sma = self.I(ta.SMA, self.data.Close, self.n_sma)
"""
if name is None:
params = ','.join(filter(None, map(_as_str, chain(args, kwargs.values()))))
func_name = func.__name__.replace('<lambda>', 'λ')
name = ('{}({})' if params else '{}').format(func_name, params)
else:
name = name.format(*map(_as_str, args),
**dict(zip(kwargs.keys(), map(_as_str, kwargs.values()))))
value = func(*args, **kwargs)
try:
value = np.asarray(value)
except Exception:
raise ValueError('Indicators must return array-like sequences of values')
if value.shape[-1] != len(self._data.Close):
raise ValueError('Indicators must be arrays of same length as `data`')
if plot and overlay is None:
x = value / self._data.Close
# By default, overlay if strong majority of indicator values
# is within 30% of Close
with np.errstate(invalid='ignore'):
overlay = ((x < 1.4) & (x > .6)).mean() > .6
value = _Indicator(value, name, plot=plot, overlay=overlay, color=color,
# lib.resample_apply() uses this:
data=self.data)
self._indicators.append(value)
return value
@abstractmethod
def init(self):
"""
Initialize the strategy.
Override this method.
Declare indicators (with `backtesting.backtesting.Strategy.I`).
Precompute what needs to be precomputed or can be precomputed
in a vectorized fashion before the strategy starts.
If you extend composable strategies from `backtesting.lib`,
make sure to call:
super().init()
"""
@abstractmethod
def next(self):
"""
Main strategy runtime method, called as each new
`backtesting.backtesting.Strategy.data`
instance (row; full candlestick bar) becomes available.
This is the main method where strategy decisions
upon data precomputed in `backtesting.backtesting.Strategy.init`
take place.
If you extend composable strategies from `backtesting.lib`,
make sure to call:
super().next()
"""
def buy(self, price=None, *, sl=None, tp=None):
"""
Let the strategy close any current position and
use _all available funds_ to
buy the asset for `price`,
optionally entering two other orders:
one at stop-loss price (`sl`; stop-limit order) and
one at take-profit price (`tp`; limit order).
If `price` is not set, market price is assumed.
"""
self._broker.buy(price and float(price),
sl and float(sl),
tp and float(tp))
def sell(self, price=None, *, sl=None, tp=None):
"""
Let the strategy close any current position and
use _all available funds_ to
short sell the asset for `price`,
optionally entering two other orders:
one at stop-loss price (`sl`; stop-limit order) and
one at take-profit price (`tp`; limit order).
If `price` is not set, market price is assumed.
"""
self._broker.sell(price and float(price),
sl and float(sl),
tp and float(tp))
@property
def equity(self):
"""Current account equity (cash plus assets)."""
return self._broker.equity
@property
def data(self) -> _Data:
"""
Price data, roughly as passed into
`backtesting.backtesting.Backtest.__init__`,
but with two significant exceptions:
* `data` is _not_ a DataFrame, but a custom structure
that serves customized numpy arrays for reasons of performance
and convenience. Besides OHLCV columns, `.index` and length,
it offers `.pip` property, the smallest price unit of change.
* Within `backtesting.backtesting.Strategy.init`, `data` arrays
are available in full length, as passed into
`backtesting.backtesting.Backtest.__init__`
(for precomputing indicators and such). However, within
`backtesting.backtesting.Strategy.next`, `data` arrays are
only as long as the current iteration, simulating gradual
price point revelation. In each call of
`backtesting.backtesting.Strategy.next` (iteratively called by
`backtesting.backtesting.Backtest` internally),
the last array value (e.g. `data.Close[-1]`)
is always the _most recent_ value.
"""
return self._data
@property
def position(self):
"""Instance of `backtesting.backtesting.Position`."""
return self._broker.position
@property
def orders(self):
"""Instance of `backtesting.backtesting.Orders`."""
return self._broker.orders
class Orders:
"""
Orders waiting for execution, available as
`backtesting.backtesting.Strategy.orders` within
`backtesting.backtesting.Strategy.next`.
Implied limit and stop-limit orders (taking profits and stopping loss)
are always present; set the limit price with
`backtesting.backtesting.Orders.set_sl` and
`backtesting.backtesting.Orders.set_tp`.
"""
def __init__(self, broker):
self._broker = broker
self._entry = self._sl = self._tp = self._close = self._is_long = None
def _update(self, entry, sl, tp, is_long=True):
self._entry = entry and float(entry) or _MARKET_PRICE
self._sl = sl and float(sl) or None
self._tp = tp and float(tp) or None
self._close = False
self._is_long = is_long
@property
def is_long(self):
"""True if the waiting entry order is long."""
return self._is_long
@property
def is_short(self):
"""True if the waiting entry order is short."""
return not self._is_long
@property
def entry(self):
"""Price at which to enter the position if hit."""
return self._entry
@property
def sl(self):
"""Stop-loss (stop-limit) price at which to exit the position if hit."""
return self._sl
@property
def tp(self):
"""Take-profit (limit) price at which to exit the position if hit."""
return self._tp
def __is_price_ok(self, price, is_limit_order):
assert price is None or price > 0
if not price:
return
market_price = self._broker.last_close
# Entry (market/limit) or TP are limit orders, SL is stop order
if (is_limit_order and (self._is_long and price < market_price or
not self._is_long and price > market_price) or
not is_limit_order and (self._is_long and price > market_price or
not self._is_long and price < market_price)):
raise ValueError("Setting the target price as sepcified would trigger "
"the order immediately -- this is forbidden. "
"Use `position.close()` to close the position, or similar.")
def set_entry(self, price):
"""Set new entry price of the implied limit order)."""
if self._entry is None and price is not None:
raise RuntimeError("Can't reset order for position entry. "
"The order has been already executed or no "
"buy/sell order was put in place.")
self.__is_price_ok(price, True)
self._entry = price and float(price)
def set_sl(self, price):
"""Set new stop-loss price (of the implied stop-limit order)."""
if self._entry is None and not self._broker._position:
raise RuntimeError("You don't currently hold a position to set "
"stop-loss for.")
self.__is_price_ok(price, False)
self._sl = price and float(price)
def set_tp(self, price):
"""Set new take-profit price (of the implied limit order)."""
if self._entry is None and not self._broker._position:
raise RuntimeError("You don't currently hold a position to set "
"take-profit limit for.")
self.__is_price_ok(price, True)
self._tp = price and float(price)
def cancel(self):
"""Cancel all implied orders."""
self._entry = self._sl = self._tp = self._close = self._is_long = None
def __bool__(self):
return bool(self._entry or self._sl or self._tp or self._close)
def __repr__(self):
return '<Orders: %.6f %.6f %.6f %d>' % (self._entry or np.nan,
self._sl or np.nan,
self._tp or np.nan,
self._close or 0)
__str__ = __repr__
class Position:
"""
Currently held asset position, available as
`backtesting.backtesting.Strategy.position` within
`backtesting.backtesting.Strategy.next`.
Can be used in boolean contexts, e.g.
if self.position:
... # we have a position, either long or short
"""
def __init__(self, broker):
self._broker = broker
def __bool__(self):
return self.size != 0
@property
def size(self):
"""Position size in units of asset. Negative if position is short."""
return self._broker._position
@property
def open_price(self):
"""Price at which the position was opened."""
return self._broker._position_open_price
@property
def open_time(self):
"""Data index value at which the position was opened."""
i = self._broker._position_open_i
return i if i is None else self._broker._data.index[i]
def _pl(self, price):
open, size = self.open_price, self.size
pl = (price - open) * size
pl -= open * self._broker._commission * abs(size)
return pl
@property
def pl(self):
"""Profit (positive) or loss (negative) of current position."""
return self._pl(self._broker._data.Close[-1])
@property
def pl_pct(self):
"""
Profit (positive) or loss (negative) of current position,
in percent of position open price.
"""
return self.pl / (self.open_price * abs(self.size))
@property
def is_long(self):
"""True if the position is long (position size is positive)."""
return self.size > 0
@property
def is_short(self):
"""True if the position is short (position size is negative)."""
return self.size < 0
def close(self):
"""Close the position at current market price."""
self._broker.close()
def __repr__(self):
return '<Position: %d>' % self.size
class _OutOfMoneyError(Exception):
pass
class _Broker:
class _Log:
def __init__(self, length):
self.equity = np.tile(np.nan, length)
self.exit_entry = np.tile(np.nan, length)
self.exit_position = np.tile(np.nan, length)
self.entry_price = np.tile(np.nan, length)
self.exit_price = np.tile(np.nan, length)
self.pl = np.tile(np.nan, length)
def __init__(self, *, data, cash, commission, margin, trade_on_close, length):
assert 0 < cash, "cash shosuld be >0, is {}".format(cash)
assert 0 <= commission < .1, "commission should be between 0-10%, is {}".format(commission)
assert 0 < margin <= 1, "margin should be between 0 and 1, is {}".format(margin)
self._data = data # type: _Data
self._cash = cash
self._commission = commission
self._leverage = 1 / margin
self._trade_on_close = trade_on_close
self._position = 0
self._position_open_price = 0
self._position_open_i = None
self.log = self._Log(length)
self.position = Position(self)
self.orders = Orders(self)
def __repr__(self):
return '<Broker: {:.0f}{:+.1f}>'.format(self._cash, self.position.pl)
def buy(self, price=None, sl=None, tp=None):
assert (sl or -np.inf) <= (price or self.last_close) <= (tp or np.inf), (sl, price or self.last_close, tp) # noqa: E501
self.orders._update(price, sl, tp)
def sell(self, price=None, sl=None, tp=None):
assert (tp or -np.inf) <= (price or self.last_close) <= (sl or np.inf), (tp, price or self.last_close, sl) # noqa: E501
self.orders._update(price, sl, tp, is_long=False)
def close(self):
self.orders.cancel()
self.orders._close = True
def _get_market_price(self, price):
i = self._i
if price in (_MARKET_PRICE, None):
price = self._data.Open[-1]
if self._trade_on_close:
price = self._data.Close[-2]
i -= 1
return i, price
@property
def last_close(self):
"""Return price at the last (current) close.
Used e.g. in `Orders._is_price_ok()` to see if the set price is reasonable.
"""
return self._data.Close[-1]
def _open_position(self, price, is_long):
assert not self._position
self.orders.set_entry(None)
i, price = self._get_market_price(price)
position = float(self._cash * self._leverage / (price * (1 + self._commission)))
self._position = position if is_long else -position
self._position_open_price = price
self._position_open_i = i
self.log.entry_price[i] = price
def _close_position(self, price=None):
if not self._position:
return
i, price = self._get_market_price(price)
pl = self.position._pl(price)
self.log.pl[i] = pl
self.log.exit_entry[i] = self._position_open_i
self.log.exit_price[i] = price
self.log.exit_position[i] = self._position
self._cash += pl
self._position = 0
@property
def equity(self):
return self._cash + self.position.pl
def next(self):
data = self._data
i = self._i = len(data) - 1
if self.orders:
orders = self.orders
is_long = orders._is_long
entry, sl, tp = orders._entry, orders._sl, orders._tp
open, high, low = data.Open[-1], data.High[-1], data.Low[-1]
if entry or orders._close:
self._close_position()
orders._close = False
# First make the entry order, if hit
if entry:
if entry is _MARKET_PRICE or high > orders._entry > low:
self._open_position(entry, is_long)
# Check if stop-loss threshold was hit
if sl and self._position:
price = (sl if low <= sl <= high else # hit
open if (is_long and open < sl or # gapped hit
not is_long and open > sl) else
None) # not hit
if price is not None:
self._close_position(price)
self.orders.cancel()
# Check if take-profit threshold was hit
if tp and self._position:
price = (tp if low < tp < high else
open if (is_long and open > tp or
not is_long and open > sl) else
None)
if price is not None:
self._close_position(price)
self.orders.cancel()
# Log account equity for the equity curve
equity = self.equity
self.log.equity[i] = equity
# Hovever, if negative, set all to 0 and stop the simulation
if equity < 0:
self._close_position()
self._cash = 0
self.log.equity[i:] = 0
raise _OutOfMoneyError
class Backtest:
"""
Backtest a particular (parameterized) strategy
on particular data.
Upon initialization, call method
`backtesting.backtesting.Backtest.run` to run a backtest
instance, or `backtesting.backtesting.Backtest.optimize` to
optimize it.
"""
def __init__(self,
data: pd.DataFrame,
strategy: type(Strategy),
*,
cash: float = 10000,
commission: float = .0,
margin: float = 1.,
trade_on_close=False
):
"""
Initialize a backtest. Requires data and a strategy to test.
`data` is a `pd.DataFrame` with columns:
`Open`, `High`, `Low`, `Close`, and (optionally) `Volume`.
If any columns are missing, set them to what you have available,
e.g.
df['Open'] = df['High'] = df['Low'] = df['Close']
DataFrame index can be either datetime index (timestamps)
or a monotonic range index (i.e. a sequence of periods).
`strategy` is a `backtesting.backtesting.Strategy`
_subclass_ (not instance).
`cash` is the initial cash to start with.
`commission` is the commision ratio. E.g. if your broker's commission
is 1% of trade value, set commission to `0.01`. Note, if you wish to
account for bid-ask spread, you approximate doing so by increasing
the commission, e.g. set it to `0.0002` for commission-less forex
trading where average spread is roughly 0.2‰ of asking price.
`margin` is the required margin (ratio) of a leveraged account.
No difference is made between initial and maintenance margins.
To run the backtest using e.g. 50:1 leverge your broker allows,
set margin to `0.02`.
If `trade_on_close` is `True`, market orders will be executed
with respect to the current bar's closing price instead of the
next bar's open.
"""
if not (isinstance(strategy, type) and issubclass(strategy, Strategy)):
raise TypeError('`strategy` must be a Strategy sub-type')
if not isinstance(commission, Number):
raise TypeError('`commission` must be a float value, percent of '
'entry order price')
data = data.copy(False)
# Convert index to datetime index
if (not data.index.is_all_dates and
not isinstance(data.index, pd.RangeIndex) and
# Numeric index with most large numbers
(data.index.is_numeric() and
(data.index > pd.Timestamp('1975').timestamp()).mean() > .8)):
try:
data.index = pd.to_datetime(data.index, infer_datetime_format=True)
except ValueError:
pass
if 'Volume' not in data:
data['Volume'] = np.nan
if len(data.columns & {'Open', 'High', 'Low', 'Close', 'Volume'}) != 5:
raise ValueError("`data` must be a pandas.DataFrame with columns "
"'Open', 'High', 'Low', 'Close', and (optionally) 'Volume'") from None
if data[['Open', 'High', 'Low', 'Close']].max().isnull().any():
raise ValueError('Some OHLC values are missing (NaN). '
'Please strip those lines with `df.dropna()` or '
'fill them in with `df.interpolate()` or whatever.')
if not data.index.is_monotonic_increasing:
warnings.warn('Data index is not sorted in ascending order. Sorting.',
stacklevel=2)
data = data.sort_index()
if not data.index.is_all_dates:
warnings.warn('Data index is not datetime. Assuming simple periods.',
stacklevel=2)
self._data = data # type: pd.DataFrame
self._broker = partial(
_Broker, cash=cash, commission=commission, margin=margin,
trade_on_close=trade_on_close, length=len(data)
)
self._strategy = strategy
self._results = None
def run(self, **kwargs) -> pd.Series:
"""
Run the backtest. Returns `pd.Series` with results and statistics.
Keyword arguments are interpreted as strategy parameters.
"""
data = _Data(self._data)
broker = self._broker(data=data) # type: _Broker
strategy = self._strategy(broker, data) # type: Strategy
strategy._set_params(**kwargs)
strategy.init()
indicator_attrs = {attr: indicator
for attr, indicator in strategy.__dict__.items()
if isinstance(indicator, _Indicator)}.items()
# Skip first few candles where indicators are still "warming up"
# +1 to have at least two entries available
start = 1 + max((np.isnan(indicator).argmin()
for _, indicator in indicator_attrs), default=0)
# Disable "invalid value encountered in ..." warnings. Comparison
# np.nan >= 3 is not invalid; it's False.
with np.errstate(invalid='ignore'):
for i in range(start, len(self._data)):
# Prepare data and indicators for `next` call
data._set_length(i + 1)
for attr, indicator in indicator_attrs:
# Slice indicator on the last dimension (case of 2d indicator)
setattr(strategy, attr, indicator[..., :i + 1])
# Handle orders processing and broker stuff
try:
broker.next()
except _OutOfMoneyError:
break
# Next tick, a moment before bar close
strategy.next()
self._results = self._compute_stats(broker, strategy)
return self._results
def optimize(self,
maximize: Union[str, Callable[[pd.Series], float]] = 'SQN',
constraint: Callable[[dict], bool] = None,
return_heatmap: bool = False,
**kwargs) -> Union[pd.Series, Tuple[pd.Series, pd.Series]]:
"""
Optimize strategy parameters to an optimal combination using
parallel exhaustive search. Returns result `pd.Series` of
the best run.
`maximize` is a string key from the
`backtesting.backtesting.Backtest.run`-returned results series,
or a function that accepts this series object and returns a number;
the higher the better. By default, the method maximizes
Van Tharp's [System Quality Number](https://google.com/search?q=System+Quality+Number).
`constraint` is a function that accepts a dict-like object of
parameters (with values) and returns `True` when the combination
is admissible to test with. By default, any parameters combination
is considered admissible.
If `return_heatmap` is `True`, besides returning the result
series, an additional `pd.Series` is returned with a multiindex
of all admissible parameter combinations, which can be further
inspected or projected onto 2D to plot a heatmap.
Additional keyword arguments represent strategy arguments with
list-like collections of possible values. For example:
backtest.optimize(sma1=[5, 10, 15], sma2=[10, 20, 40],
constraint=lambda p: p.sma1 < p.sma2)
finds and returns the "best" of the 7 admissible (of the
9 possible) parameter combinations.
"""
if not kwargs:
raise ValueError('Need some strategy parameters to optimize')
if isinstance(maximize, str):
stats = self._results if self._results is not None else self.run()
if maximize not in stats:
raise ValueError('`maximize`, if str, must match a key in pd.Series '
'result of backtest.run()')
def maximize(stats: pd.Series, _key=maximize):
return stats[_key]
elif not callable(maximize):
raise TypeError('`maximize` must be str (a field of backtest.run() result '
'Series) or a function that accepts result Series '
'and returns a number; the higher the better')
if constraint is None:
def constraint(_):
return True
elif not callable(constraint):
raise TypeError("`constraint` must be a function that accepts a dict "
"of strategy parameters and returns a bool whether "
"the combination of parameters is admissible or not")
def _tuple(x):
return x if isinstance(x, Sequence) and not isinstance(x, str) else (x,)
class AttrDict(dict):
def __getattr__(self, item):
return self[item]
param_combos = tuple(map(dict, # back to dict so it pickles
filter(constraint, # constraints applied on our fancy dict
map(AttrDict,
product(*(zip(repeat(k), _tuple(v))
for k, v in kwargs.items()))))))
if not param_combos:
raise ValueError('No admissible parameter combinations to test')
if len(param_combos) > 300:
warnings.warn('Searching best of {} configurations.'.format(len(param_combos)),
stacklevel=2)
heatmap = pd.Series(np.nan,
index=pd.MultiIndex.from_tuples([p.values() for p in param_combos],
names=next(iter(param_combos)).keys()))
# TODO: add parameter `max_tries:Union[int, float]=None` which switches
# exhaustive grid search to random search. This might need to avoid
# returning NaNs in stats on runs with no trades to differentiate those
# from non-tested parameter combos in heatmap.
def _batch(seq):
n = np.clip(len(param_combos) // (os.cpu_count() or 1), 5, 300)
for i in range(0, len(seq), n):
yield seq[i:i + n]
with ProcessPoolExecutor() as executor:
for future in as_completed(executor.submit(self._mp_task, params)
for params in _batch(param_combos)):
for params, stats in future.result():
heatmap[tuple(params.values())] = maximize(stats)
best_params = heatmap.idxmax()
if pd.isnull(best_params):
# No trade was made in any of the runs. Just make a random
# run so we get some, if empty, results
self.run(**param_combos[0])
else:
# Re-run best strategy so that the next .plot() call will render it
self.run(**dict(zip(heatmap.index.names, best_params)))
if return_heatmap:
return self._results, heatmap
return self._results
def _mp_task(self, param_combos):
return [(params, stats) for params, stats in ((params, self.run(**params))
for params in param_combos)
if stats['# Trades']]
def _compute_stats(self, broker: _Broker, strategy: Strategy) -> pd.Series:
data = self._data
def _drawdown_duration_peaks(dd, index):
# XXX: possible to vectorize any of this?
durations = [np.nan] * len(dd)
peaks = [np.nan] * len(dd)
i = 0
for j in range(1, len(dd)):
if dd[j] == 0:
if dd[j - 1] != 0:
durations[j - 1] = index[j] - index[i]
peaks[j - 1] = dd[i:j].max()
i = j
return pd.Series(durations), pd.Series(peaks)
df = pd.DataFrame()
df['Equity'] = pd.Series(broker.log.equity).bfill().fillna(broker._cash)
equity = df.Equity.values
df['Exit Entry'] = broker.log.exit_entry
exits = df['Exit Entry']
df['Exit Position'] = broker.log.exit_position
df['Entry Price'] = broker.log.entry_price
df['Exit Price'] = broker.log.exit_price
df['P/L'] = broker.log.pl
pl = df['P/L']
df['Returns'] = returns = pl.dropna() / equity[exits.dropna().values.astype(int)]
df['Drawdown'] = dd = 1 - equity / np.maximum.accumulate(equity)
dd_dur, dd_peaks = _drawdown_duration_peaks(dd, data.index)
df['Drawdown Duration'] = dd_dur
dd_dur = df['Drawdown Duration']
df.index = data.index
def _round_timedelta(value, _period=_data_period(df)):
return value.ceil(_period.resolution) if isinstance(value, pd.Timedelta) else value
s = pd.Series()
s['Start'] = df.index[0]
s['End'] = df.index[-1]
# Assigning Timedeltas needs the key to exist beforehand,
# otherwise the value is interpreted as nanosec *int*. See:
# https://github.com/pandas-dev/pandas/issues/22717
s['Duration'] = 0
s['Duration'] = s.End - s.Start
exits = df['Exit Entry'] # After reindexed
durations = (exits.dropna().index - df.index[exits.dropna().values.astype(int)]).to_series()
s['Exposure [%]'] = np.nan_to_num(durations.sum() / (s['Duration'] or np.nan) * 100)
s['Equity Final [$]'] = equity[-1]
s['Equity Peak [$]'] = equity.max()
s['Return [%]'] = (equity[-1] - equity[0]) / equity[0] * 100
c = data.Close.values
s['Buy & Hold Return [%]'] = abs(c[-1] - c[0]) / c[0] * 100 # long OR short
s['Max. Drawdown [%]'] = max_dd = -np.nan_to_num(dd.max()) * 100
s['Avg. Drawdown [%]'] = -dd_peaks.mean() * 100
s['Max. Drawdown Duration'] = 0
s['Max. Drawdown Duration'] = _round_timedelta(dd_dur.max())
s['Avg. Drawdown Duration'] = 0
s['Avg. Drawdown Duration'] = _round_timedelta(dd_dur.mean())
s['# Trades'] = n_trades = pl.count()
s['Win Rate [%]'] = win_rate = np.nan if not n_trades else (pl > 0).sum() / n_trades * 100
s['Best Trade [%]'] = returns.max() * 100
s['Worst Trade [%]'] = returns.min() * 100
mean_return = returns.mean()
s['Avg. Trade [%]'] = mean_return * 100
s['Max. Trade Duration'] = 0
s['Max. Trade Duration'] = _round_timedelta(durations.max())
s['Avg. Trade Duration'] = 0
s['Avg. Trade Duration'] = _round_timedelta(durations.mean())
s['Expectancy [%]'] = ((returns[returns > 0].mean() * win_rate -
returns[returns < 0].mean() * (100 - win_rate)))
pl = pl.dropna()
s['SQN'] = np.sqrt(n_trades) * pl.mean() / pl.std()
s['Sharpe Ratio'] = mean_return / (returns.std() or np.nan)
s['Sortino Ratio'] = mean_return / (returns[returns < 0].std() or np.nan)
s['Calmar Ratio'] = mean_return / ((-max_dd / 100) or np.nan)
s['_strategy'] = strategy
s._trade_data = df # Private API
return s
def plot(self, *, results: pd.Series = None, filename=None, plot_width=1200,
plot_equity=True, plot_pl=True,
plot_volume=True, plot_drawdown=False,
smooth_equity=False, relative_equity=True,
omit_missing=True, superimpose: Union[bool, str] = True,
show_legend=True, open_browser=True):
"""
Plot the progression of the last backtest run.
If `results` is proided, it should be a particular result
`pd.Series` such as returned by
`backtesting.backtesting.Backtest.run` or
`backtesting.backtesting.Backtest.optimize`.
`filename` is the path to save the interactive HTML plot to.
By default, a strategy/parameter-dependent file is created in the
current working directory.
`plot_width` is the width of the plot in pixels. The height is
currently non-adjustable. FIXME: If someone can make the Bokeh
plot span 100% browser width by default, a contribution would
be appreciated.
If `plot_equity` is `True`, the resulting plot will contain
an equity (cash plus assets) graph section.
If `plot_pl` is `True`, the resulting plot will contain
a profit/loss (P/L) indicator section.
If `plot_volume` is `True`, the resulting plot will contain
a trade volume section.
If `plot_drawdown` is `True`, the resulting plot will contain
a separate drawdown graph section.
If `smooth_equity` is `True`, the equity graph will be
interpolated between points of cash-only positions,
unaffected by any interim asset volatility.
If `relative_equity` is `True`, scale and label equity graph axis
with return percent, not absolute cash-equivalent values.
If `omit_missing` is `True`, skip missing candlestick bars on the
datetime axis.
If `superimpose` is `True`, superimpose downsampled candlesticks
over the original candlestick chart. Default downsampling is:
weekly for daily data, daily for hourly data, hourly for minute data,
and minute for second and sub-second data.
`superimpose` can also be a string, in which case it is a valid
[Pandas offset string], such as `'5T'` or `'5min'`.
Note, this only works for data with a datetime index.
[Pandas offset string]: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases
If `show_legend` is `True`, the resulting plot graphs will contain
labeled legends.
If `open_browser` is `True`, the resulting `filename` will be
opened in the default web browser.
"""
if results is None:
if self._results is None:
raise RuntimeError('First issue `backtest.run()` to obtain results.')
results = self._results
def _windos_safe_filename(filename):
if sys.platform.startswith('win'):
return re.sub(r'[^a-zA-Z0-9,_-]', '_', filename.replace('=', '-'))
return filename
plot(
results=results,
df=self._data,
indicators=results._strategy._indicators,
filename=filename or _windos_safe_filename(str(results._strategy)),
plot_width=plot_width,
plot_equity=plot_equity,
plot_pl=plot_pl,
plot_volume=plot_volume,
omit_missing=omit_missing,
plot_drawdown=plot_drawdown,
smooth_equity=smooth_equity,
relative_equity=relative_equity,
superimpose=superimpose,
show_legend=show_legend,
open_browser=open_browser)

309
backtesting/lib.py Normal file
View File

@@ -0,0 +1,309 @@
"""
Collection of common building blocks, helper auxiliary functions and
composable strategy classes for reuse.
Intended for simple missing-link procedures, not reinventing
of better-suited, state-of-the-art, fast libraries,
such as TA-Lib, Tulipy, PyAlgoTrade, NumPy, SciPy ...
Please raise ideas for additions to this collection on the [issue tracker].
[issue tracker]: https://github.com/kernc/backtesting.py
"""
from collections import OrderedDict
from itertools import compress
from numbers import Number
from inspect import currentframe
from typing import Sequence, Optional, Union, Callable
import numpy as np
import pandas as pd
from .backtesting import Strategy
from ._plotting import plot_heatmaps as _plot_heatmaps
from ._util import _Indicator, _as_str
OHLCV_AGG = OrderedDict((
('Open', 'first'),
('High', 'max'),
('Low', 'min'),
('Close', 'last'),
('Volume', 'sum'),
))
"""Dictionary of rules for aggregating resampled OHLCV data frames,
e.g.
df.resample('4H', label='right').agg(OHLCV_AGG)
"""
def barssince(condition: Sequence[bool], default=np.inf) -> int:
"""
Return the number of bars since `condition` sequence was last `True`,
or if never, return `default`.
>>> barssince(self.data.Close > self.data.Open)
3
"""
return next(compress(range(len(condition)), reversed(condition)), default)
def cross(series1, series2) -> bool:
"""
Return `True` if `series1` and `series2` just crossed (either
direction).
>>> cross(self.data.Close, self.sma)
True
"""
return crossover(series1, series2) or crossover(series2, series1)
def crossover(series1, series2) -> bool:
"""
Return `True` if `series1` just crossed over
`series2`.
>>> crossover(self.data.Close, self.sma)
True
"""
series1 = (
series1.values if isinstance(series1, pd.Series) else
(series1, series1) if isinstance(series1, Number) else
series1)
series2 = (
series2.values if isinstance(series2, pd.Series) else
(series2, series2) if isinstance(series2, Number) else
series2)
try:
return series1[-2] < series2[-2] and series1[-1] > series2[-1]
except IndexError:
return False
def plot_heatmaps(heatmap: pd.Series,
agg: Union[str, Callable] = 'max',
*,
ncols: int = 3,
plot_width: int = 1200,
filename: str = '',
open_browser: bool = True):
"""
Plots a grid of heatmaps, one for every pair of parameters in `heatmap`.
`heatmap` is a Series as returned by
`backtesting.backtesting.Backtest.optimize` when its parameter
`return_heatmap=True`.
When projecting the n-dimensional heatmap onto 2D, the values are
aggregated by 'max' function by default. This can be tweaked
with `agg` parameter, which accepts any argument pandas knows
how to aggregate by.
"""
return _plot_heatmaps(heatmap, agg, ncols, filename, plot_width, open_browser)
def quantile(series, quantile=None):
"""
If `quantile` is `None`, return the quantile _rank_ of the last
value of `series` wrt former series values.
If `quantile` is a value between 0 and 1, return the _value_ of
`series` at this quantile. If used to working with percentiles, just
divide your percentile amount with 100 to obtain quantiles.
>>> quantile(self.data.Close[-20:], .1)
162.130
>>> quantile(self.data.Close)
0.13
"""
if quantile is None:
try:
last, series = series[-1], series[:-1]
return np.mean(series < last)
except IndexError:
return np.nan
assert 0 <= quantile <= 1, "quantile must be within [0, 1]"
return np.nanpercentile(series, quantile * 100)
def resample_apply(rule: str,
func: Callable,
series,
*args, **kwargs):
"""
Apply `func` (such as an indicator) to `series`, resampled to
a time frame specified by `rule`. When called from inside
`backtesting.backtesting.Strategy.init`,
the result (returned) series will be automatically wrapped in
`backtesting.backtesting.Strategy.I`
wrapper method.
`rule` is a valid [Pandas offset string] indicating
a time frame to resample `series` to.
[Pandas offset string]: http://pandas.pydata.org/pandas-docs/stable/timeseries.html#offset-aliases
`func` is the indicator function to apply on the resampled series.
`series` is a data series (or array), such as any of the
`backtesting.backtesting.Strategy.data` series. Due to pandas
resampling limitations, this only works when input series
has a datetime index.
Finally, any `*args` and `**kwargs` that are not already eaten by
implicit `backtesting.backtesting.Strategy.I` call
are passed to `func`.
For example, if we have a typical moving average function
`SMA(values, lookback_period)`, _hourly_ data source, and need to
apply the moving average MA(10) on a _daily_ time frame,
but don't want to plot the resulting indicator, we can do:
class System(Strategy):
def init(self):
self.sma = resample_apply(
'D', SMA, self.data.Close, 10, plot=False)
"""
if not isinstance(series, pd.Series):
series = pd.Series(series,
index=series._opts['data'].index,
name=series.name)
resampled = series.resample(rule, label='right').agg('last').dropna()
resampled.name = _as_str(series) + '[' + rule + ']'
# Check first few stack frames if we are being called from
# inside Strategy.init, and if so, extract Strategy.I wrapper.
frame, level = currentframe(), 0
while frame and level <= 3:
frame = frame.f_back
level += 1
if isinstance(frame.f_locals.get('self'), Strategy):
strategy_I = frame.f_locals['self'].I
break
else:
def strategy_I(func, *args, **kwargs):
return func(*args, **kwargs)
# Resample back to data index
def wrap_func(resampled, *args, **kwargs):
ind = func(resampled, *args, **kwargs)
ind = ind.reindex(index=series.index | ind.index,
method='ffill').reindex(series.index)
return ind
wrap_func.__name__ = func.__name__
array = strategy_I(wrap_func, resampled, *args, **kwargs)
return array
class SignalStrategy(Strategy):
"""
A simple helper strategy that operates on position entry/exit signals.
To use this helper strategy, subclass it, override its
`backtesting.backtesting.Strategy.init` method,
and set the signal vector by calling
`backtesting.lib.SignalStrategy.set_signal` method from within it.
class ExampleStrategy(SignalStrategy):
def init(self):
super().init()
self.set_signal(sma1 > sma2, sma1 < sma2)
Remember to call `super().init()` and `super().next()` in your
overridden methods.
"""
__entry_signal = (0,)
__exit_signal = (False,)
def set_signal(self, entry: Sequence[int], exit: Optional[Sequence[bool]] = None,
plot: bool = True):
"""
Set entry/exit signal vectors (arrays). An long entry signal is considered
present wherever `entry` is greater than zero. A short entry signal
is considered present wherever `entry` is less than zero. If `exit`
is provided, a nonzero value closes the position, if any; otherwise
the position is held until a reverse signal in `entry`.
If `plot` is `True`, the signal entry/exit indicators are plotted when
`backtesting.backtesting.Backtest.plot` is called.
"""
self.__entry_signal = _Indicator(pd.Series(entry, dtype=float).fillna(0),
name='entry', plot=plot, overlay=False)
if exit is not None:
self.__exit_signal = _Indicator(pd.Series(exit, dtype=float).fillna(0),
name='exit', plot=plot, overlay=False)
def next(self):
super().next()
if self.position and self.__exit_signal[-1]:
self.position.close()
signal = self.__entry_signal[-1]
if signal > 0:
self.buy()
elif signal < 0:
self.sell()
class TrailingStrategy(Strategy):
"""
A strategy with automatic trailing stop-loss, trailing the current
price at distance of some multiple of average true range (ATR). Call
`TrailingStrategy.set_trailing_sl()` to set said multiple
(`6` by default).
Remember to call `super().init()` and `super().next()` in your
overridden methods.
"""
__n_atr = 6
__atr = None
def init(self):
super().init()
self.set_atr_periods()
def set_atr_periods(self, periods: int = 100):
"""
Set the lookback period for computing ATR. The default value
of 100 ensures a _stable_ ATR.
"""
h, l, c_prev = self.data.High, self.data.Low, pd.Series(self.data.Close).shift(1)
tr = np.max([h - l, (c_prev - h).abs(), (c_prev - l).abs()], axis=0)
atr = pd.Series(tr).rolling(periods).mean().bfill().values
self.__atr = atr
def set_trailing_sl(self, n_atr: float = 6):
"""
Sets the future trailing stop-loss as some multiple (`n_atr`)
average true bar ranges away from the current price.
"""
self.__n_atr = n_atr
def next(self):
super().next()
if self.__n_atr and self.position:
if self.position.is_long:
self.orders.set_sl(self.data.Close[-1] - self.__atr[-1] * self.__n_atr)
else:
self.orders.set_sl(self.data.Close[-1] + self.__atr[-1] * self.__n_atr)
# NOTE: Don't put anything below this __all__ list
__all__ = [getattr(v, '__name__', k)
for k, v in globals().items() # export
if ((callable(v) and v.__module__ == __name__ or # callables from this module
k.isupper()) and # or CONSTANTS
not getattr(v, '__name__', k).startswith('_'))] # neither marked internal
# NOTE: Don't put anything below here. See above.

5001
backtesting/test/EURUSD.csv Normal file

File diff suppressed because it is too large Load Diff

2149
backtesting/test/GOOG.csv Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,23 @@
"""Data and utilities for testing."""
import pandas as pd
def _read_file(filename):
from os.path import dirname, join
return pd.read_csv(join(dirname(__file__), filename),
index_col=0, parse_dates=True, infer_datetime_format=True)
GOOG = _read_file('GOOG.csv')
"""DataFrame of daily NASDAQ:GOOG (Google/Alphabet) stock price data from 2004 to 2013."""
EURUSD = _read_file('EURUSD.csv')
"""DataFrame of hourly EUR/USD forex data from April 2017 to February 2018."""
def SMA(arr: pd.Series, n: int) -> pd.Series:
"""
Returns `n`-period simple moving average of array `arr`.
"""
return pd.Series(arr).rolling(n).mean()

512
backtesting/test/_test.py Normal file
View File

@@ -0,0 +1,512 @@
import os
import time
import unittest
import warnings
from contextlib import contextmanager
from glob import glob
from runpy import run_path
from tempfile import NamedTemporaryFile, gettempdir
from unittest import TestCase
import numpy as np
import pandas as pd
from backtesting import Backtest, Strategy
from backtesting.lib import (
OHLCV_AGG,
barssince,
cross,
crossover,
quantile,
SignalStrategy,
TrailingStrategy,
resample_apply,
plot_heatmaps
)
from backtesting.test import GOOG, EURUSD, SMA
from backtesting._util import _Indicator, _as_str, _Array
@contextmanager
def _tempfile():
with NamedTemporaryFile(suffix='.html') as f:
yield f.name
@contextmanager
def chdir(path):
cwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(cwd)
class SmaCross(Strategy):
# NOTE: These values are also used on the website!
fast = 10
slow = 30
def init(self):
self.sma1 = self.I(SMA, self.data.Close, self.fast)
self.sma2 = self.I(SMA, self.data.Close, self.slow)
def next(self):
if crossover(self.sma1, self.sma2):
self.buy()
elif crossover(self.sma2, self.sma1):
self.sell()
class TestBacktest(TestCase):
def test_run(self):
bt = Backtest(EURUSD, SmaCross)
bt.run()
def test_run_invalid_param(self):
bt = Backtest(GOOG, SmaCross)
self.assertRaises(AttributeError, bt.run, foo=3)
def test_run_speed(self):
bt = Backtest(GOOG, SmaCross)
start = time.process_time()
bt.run()
end = time.process_time()
self.assertLess(end - start, .2)
def test_data_missing_columns(self):
df = GOOG.copy()
del df['Open']
with self.assertRaises(ValueError):
Backtest(df, SmaCross).run()
def test_data_nan_columns(self):
df = GOOG.copy()
df['Open'] = np.nan
with self.assertRaises(ValueError):
Backtest(df, SmaCross).run()
def test_data_extra_columns(self):
df = GOOG.copy()
df['P/E'] = np.arange(len(df))
df['MCap'] = np.arange(len(df))
class S(Strategy):
def init(self):
assert len(self.data.MCap) == len(self.data.Close)
assert len(self.data['P/E']) == len(self.data.Close)
def next(self):
assert len(self.data.MCap) == len(self.data.Close)
assert len(self.data['P/E']) == len(self.data.Close)
Backtest(df, S).run()
def test_assertions(self):
class Assertive(Strategy):
def init(self):
self.sma = self.I(SMA, self.data.Close, 10)
self.remains_indicator = np.r_[2] * np.cumsum(self.sma * 5 + 1) * np.r_[2]
resampled = resample_apply('W', SMA, self.data.Close, 3)
resampled_ind = resample_apply('W', SMA, self.sma, 3)
assert np.unique(resampled[-5:]).size == 1
assert np.unique(resampled[-6:]).size == 2
assert resampled in self._indicators, "Strategy.I not called"
assert resampled_ind in self._indicators, "Strategy.I not called"
try:
self.data.X
except KeyError:
pass
else:
assert False
assert self.data.pip == .01
assert float(self.data.Close) == self.data.Close[-1]
def next(self, FIVE_DAYS=pd.Timedelta('3 days')):
assert self.equity >= 0
assert isinstance(self.sma, _Indicator)
assert isinstance(self.remains_indicator, _Indicator)
assert self.remains_indicator.name
assert isinstance(self.remains_indicator._opts, dict)
assert not np.isnan(self.data.Open[-1])
assert not np.isnan(self.data.High[-1])
assert not np.isnan(self.data.Low[-1])
assert not np.isnan(self.data.Close[-1])
assert not np.isnan(self.data.Volume[-1])
assert not np.isnan(self.sma[-1])
assert self.data.index[-1]
self.orders.is_long
self.orders.is_short
self.orders.entry
self.orders.sl
self.orders.tp
self.position
self.position.size
self.position.pl
self.position.pl_pct
self.position.open_price
self.position.open_time
self.position.is_long
if crossover(self.sma, self.data.Close):
self.orders.cancel()
self.sell()
assert not self.orders.is_long
assert self.orders.is_short
assert self.orders.entry
assert not self.orders.sl
assert not self.orders.tp
price = self.data.Close[-1]
sl, tp = 1.05 * price, .9 * price
self.sell(price, sl=sl, tp=tp)
self.orders.set_entry(price)
self.orders.set_sl(sl)
self.orders.set_tp(tp)
assert self.orders.entry == price
assert self.orders.sl == sl
assert self.orders.tp == tp
elif self.position:
assert not self.orders.entry
assert not self.position.is_long
assert not not self.position.is_short
assert self.position.open_price
assert self.position.pl
assert self.position.pl_pct
assert self.position.size < 0
if self.data.index[-1] - self.position.open_time > FIVE_DAYS:
self.position.close()
bt = Backtest(GOOG, Assertive)
stats = bt.run()
self.assertEqual(stats['# Trades'], 144)
def test_broker_params(self):
bt = Backtest(GOOG.iloc[:100], SmaCross,
cash=1000, commission=.01, margin=.1, trade_on_close=True)
bt.run()
def test_dont_overwrite_data(self):
df = EURUSD.copy()
bt = Backtest(df, SmaCross)
bt.run()
bt.optimize(fast=4, slow=[6, 8])
bt.plot(plot_drawdown=True, open_browser=False)
self.assertTrue(df.equals(EURUSD))
def test_strategy_abstract(self):
class MyStrategy(Strategy):
pass
self.assertRaises(TypeError, MyStrategy, None, None)
def test_strategy_str(self):
bt = Backtest(GOOG.iloc[:100], SmaCross)
self.assertEqual(str(bt.run()._strategy), SmaCross.__name__)
self.assertEqual(str(bt.run(fast=11)._strategy), SmaCross.__name__ + '(fast=11)')
def test_compute_stats(self):
stats = Backtest(GOOG, SmaCross).run()
self.assertEqual(
stats.filter(regex='^[^_]').to_dict(),
{
# NOTE: These values are also used on the website!
'# Trades': 65,
'Avg. Drawdown Duration': pd.Timedelta('33 days 00:00:00'),
'Avg. Drawdown [%]': -5.494714447812327,
'Avg. Trade Duration': pd.Timedelta('46 days 00:00:00'),
'Avg. Trade [%]': 3.0404430275631444,
'Best Trade [%]': 54.05363186670138,
'Buy & Hold Return [%]': 703.4582419772772,
'Calmar Ratio': 0.0631443286380662,
'Duration': pd.Timedelta('3116 days 00:00:00'),
'End': pd.Timestamp('2013-03-01 00:00:00'),
'Equity Final [$]': 52624.29346696951,
'Equity Peak [$]': 76908.27001642012,
'Expectancy [%]': 8.774692825628644,
'Exposure [%]': 93.93453145057767,
'Max. Drawdown Duration': pd.Timedelta('477 days 00:00:00'),
'Max. Drawdown [%]': -48.15069053929621,
'Max. Trade Duration': pd.Timedelta('183 days 00:00:00'),
'Return [%]': 426.2429346696951,
'SQN': 0.91553210127173,
'Sharpe Ratio': 0.23169782960690408,
'Sortino Ratio': 0.7096713270577958,
'Start': pd.Timestamp('2004-08-19 00:00:00'),
'Win Rate [%]': 46.15384615384615,
'Worst Trade [%]': -18.85561318387153}
)
self.assertTrue(
stats._trade_data.columns.equals(
pd.Index(['Equity', 'Exit Entry', 'Exit Position',
'Entry Price', 'Exit Price', 'P/L', 'Returns',
'Drawdown', 'Drawdown Duration'])))
def test_compute_stats_bordercase(self):
class SingleTrade(Strategy):
def init(self):
self._done = False
def next(self):
if not self._done:
self.buy()
self._done = True
if self.position:
self.position.close()
class SinglePosition(Strategy):
def init(self):
pass
def next(self):
if not self.position:
self.buy()
class NoTrade(Strategy):
def init(self):
pass
def next(self):
pass
for strategy in (SmaCross,
SingleTrade,
SinglePosition,
NoTrade):
with self.subTest(strategy=strategy.__name__):
stats = Backtest(GOOG.iloc[:100], strategy).run()
self.assertFalse(np.isnan(stats['Equity Final [$]']))
self.assertFalse(stats._trade_data['Equity'].isnull().any())
self.assertEqual(stats['_strategy'].__class__, strategy)
class TestOptimize(TestCase):
def test_optimize(self):
bt = Backtest(GOOG.iloc[:100], SmaCross)
OPT_PARAMS = dict(fast=range(2, 5, 2), slow=[2, 5, 7, 9])
self.assertRaises(ValueError, bt.optimize)
self.assertRaises(ValueError, bt.optimize, maximize='missing key', **OPT_PARAMS)
self.assertRaises(ValueError, bt.optimize, maximize='missing key', **OPT_PARAMS)
self.assertRaises(TypeError, bt.optimize, maximize=15, **OPT_PARAMS)
self.assertRaises(TypeError, bt.optimize, constraint=15, **OPT_PARAMS)
self.assertRaises(ValueError, bt.optimize, constraint=lambda d: False, **OPT_PARAMS)
res = bt.optimize(**OPT_PARAMS)
self.assertIsInstance(res, pd.Series)
res2 = bt.optimize(**OPT_PARAMS, maximize=lambda s: s['SQN'])
self.assertSequenceEqual(res.filter(regex='^[^_]').to_dict(),
res2.filter(regex='^[^_]').to_dict())
res3, heatmap = bt.optimize(**OPT_PARAMS, return_heatmap=True,
constraint=lambda d: d.slow > 2 * d.fast)
self.assertIsInstance(heatmap, pd.Series)
self.assertEqual(len(heatmap), 4)
with _tempfile() as f:
bt.plot(filename=f, open_browser=False)
def test_optimize_invalid_param(self):
bt = Backtest(GOOG.iloc[:100], SmaCross)
self.assertRaises(AttributeError, bt.optimize, foo=range(3))
def test_optimize_no_trades(self):
bt = Backtest(GOOG, SmaCross)
stats = bt.optimize(fast=[3], slow=[3])
self.assertTrue(stats.isnull().any())
def test_optimize_speed(self):
bt = Backtest(GOOG.iloc[:100], SmaCross)
start = time.process_time()
bt.optimize(fast=(2, 5, 7), slow=[10, 15, 20, 30])
end = time.process_time()
self.assertLess(end - start, .2)
class TestPlot(TestCase):
def test_plot_before_run(self):
bt = Backtest(GOOG, SmaCross)
self.assertRaises(RuntimeError, bt.plot)
def test_file_size(self):
bt = Backtest(GOOG, SmaCross)
bt.run()
with _tempfile() as f:
bt.plot(filename=f[:-len('.html')], open_browser=False)
self.assertLess(os.path.getsize(f), 500000)
def test_params(self):
bt = Backtest(GOOG.iloc[:100], SmaCross)
bt.run()
with _tempfile() as f:
for p in dict(plot_volume=False,
plot_equity=False,
plot_pl=False,
plot_drawdown=True,
superimpose=False,
omit_missing=False,
smooth_equity=False,
relative_equity=False,
show_legend=False).items():
with self.subTest(param=p[0]):
bt.plot(**dict([p]), filename=f, open_browser=False)
def test_resolutions(self):
with _tempfile() as f:
for rule in 'LSTHDWM':
with self.subTest(rule=rule):
df = EURUSD.iloc[:2].resample(rule).agg(OHLCV_AGG).iloc[:1100]
bt = Backtest(df, SmaCross)
bt.run()
bt.plot(filename=f, open_browser=False)
def test_range_axis(self):
df = GOOG.iloc[:100].reset_index(drop=True)
# Warm-up. CPython bug bpo-29620.
try:
with self.assertWarns(UserWarning):
Backtest(df, SmaCross)
except RuntimeError:
pass
with self.assertWarns(UserWarning):
bt = Backtest(df, SmaCross)
bt.run()
with _tempfile() as f:
bt.plot(filename=f, open_browser=False)
def test_preview(self):
class Strategy(SmaCross):
def init(self):
super().init()
def ok(x):
return x
self.a = self.I(SMA, self.data.Open, 5, overlay=False, name='ok')
self.b = self.I(ok, np.random.random(len(self.data.Open)))
bt = Backtest(GOOG, Strategy)
bt.run()
with _tempfile() as f:
bt.plot(filename=f, plot_drawdown=True, smooth_equity=True)
# Give browser time to open before tempfile is removed
time.sleep(5)
class TestLib(TestCase):
def test_barssince(self):
self.assertEqual(barssince(np.r_[1, 0, 0]), 2)
self.assertEqual(barssince(np.r_[0, 0, 0]), np.inf)
self.assertEqual(barssince(np.r_[0, 0, 0], 0), 0)
def test_cross(self):
self.assertTrue(cross([0, 1], [1, 0]))
self.assertTrue(cross([1, 0], [0, 1]))
self.assertFalse(cross([1, 0], [1, 0]))
def test_crossover(self):
self.assertTrue(crossover([0, 1], [1, 0]))
self.assertTrue(crossover([0, 1], .5))
self.assertTrue(crossover([0, 1], pd.Series([.5, .5], index=[5, 6])))
self.assertFalse(crossover([1, 0], [1, 0]))
self.assertFalse(crossover([0], [1]))
def test_quantile(self):
self.assertEqual(quantile(np.r_[1, 3, 2], .5), 2)
self.assertEqual(quantile(np.r_[1, 3, 2]), .5)
def test_resample_apply(self):
res = resample_apply('D', SMA, EURUSD.Close, 10)
self.assertEqual(res.name, 'C[D]')
self.assertEqual(res.count() / res.size, .9634)
self.assertEqual(res.iloc[-48:].unique().tolist(),
[1.2426429999999997, 1.2423809999999995, 1.2422749999999998])
def test_plot_heatmaps(self):
bt = Backtest(GOOG, SmaCross)
stats, heatmap = bt.optimize(fast=range(2, 7, 2),
slow=range(7, 15, 2),
return_heatmap=True)
with _tempfile() as f:
for agg in ('mean',
lambda x: np.percentile(x, 75)):
plot_heatmaps(heatmap, agg, filename=f, open_browser=False)
# Preview
plot_heatmaps(heatmap, filename=f)
time.sleep(5)
def test_SignalStrategy(self):
class S(SignalStrategy):
def init(self):
sma = pd.Series(self.data.Close).rolling(10).mean()
self.set_signal(self.data.Close > sma,
self.data.Close < sma)
stats = Backtest(GOOG, S).run()
self.assertGreater(stats['# Trades'], 1000)
def test_TrailingStrategy(self):
class S(TrailingStrategy):
def init(self):
super().init()
self.set_atr_periods(40)
self.set_trailing_sl(3)
self.sma = self.I(
lambda: pd.Series(self.data.Close,
index=self.data.index).rolling(10).mean())
def next(self):
super().next()
if not self.position and self.data.Close > self.sma:
self.buy()
stats = Backtest(GOOG, S).run()
self.assertGreater(stats['# Trades'], 6)
class TestUtil(TestCase):
def test_as_str(self):
def func():
pass
class Class:
pass
self.assertEqual(_as_str('4'), '4')
self.assertEqual(_as_str(4), '4')
self.assertEqual(_as_str(_Indicator([1, 2], name='x')), 'x')
self.assertEqual(_as_str(func), 'func')
self.assertEqual(_as_str(Class), 'Class')
self.assertEqual(_as_str(lambda x: x), '')
for s in ('Open', 'High', 'Low', 'Close'):
self.assertEqual(_as_str(_Array([1], name=s)), s[0])
class TestDocs(TestCase):
def test_examples(self):
examples = glob(os.path.join(os.path.dirname(__file__),
'..', '..', 'doc', 'examples', '*.py'))
self.assertGreaterEqual(len(examples), 4)
with chdir(gettempdir()):
for file in examples:
run_path(file)
if __name__ == '__main__':
warnings.filterwarnings('error')
unittest.main()

13
doc/README.md Normal file
View File

@@ -0,0 +1,13 @@
Backtesting.py Documentation
============================
After installing documentation dependencies:
pip install .[doc]
build HTML documentation by running:
./build.sh
When submitting pull requests that change example notebooks,
commit example _.py_ files too
(`build.sh` should tell you how to make them).

86
doc/build.sh Executable file
View File

@@ -0,0 +1,86 @@
#!/bin/bash
set -eu
IS_RELEASE=${TRAVIS_TAG+1}
die () { echo "ERROR: $*" >&2; exit 2; }
for cmd in pdoc \
jupytext ; do
command -v "$cmd" >/dev/null ||
die "Missing $cmd; \`pip install $cmd\`"
done
command -v "jupyter-nbconvert" >/dev/null ||
die "Missing jupyter-nbconvert; \`pip install nbconvert\`"
DOCROOT="$(dirname "$(readlink -f "$0")")"
BUILDROOT="$DOCROOT/build"
echo
echo 'Building API reference docs'
echo
mkdir -p "$BUILDROOT"
rm -r "$BUILDROOT" 2>/dev/null || true
pushd "$DOCROOT/.." >/dev/null
pdoc --html --html-no-source \
${IS_RELEASE+--template-dir "$DOCROOT/pdoc_template"} \
--html-dir "$BUILDROOT" \
backtesting
popd >/dev/null
echo
echo 'Ensuring example notebooks match their py counterparts'
echo
for ipynb in "$DOCROOT"/examples/*.ipynb; do
echo "Checking: '$ipynb'"
diff -q "${ipynb%.ipynb}.py" <(jupytext --to py --output - "$ipynb") ||
die "Notebook and its matching .py file differ. Maybe run: \`jupytext --to py '$ipynb'\` ?"
done
echo
echo 'Converting example notebooks → py → HTML'
echo
jupytext --test --update --to ipynb "$DOCROOT/examples"/*.py
{ mkdir -p ~/.ipython/profile_default/startup
cp -f "$DOCROOT/ipython_config.py" ~/.ipython/profile_default/startup/99-backtesting-docs.py
trap 'rm -f ~/.ipython/profile_default/startup/99-backtesting-docs.py' EXIT; }
PYTHONWARNINGS='ignore::UserWarning' \
jupyter-nbconvert --execute --to=html \
--output-dir="$BUILDROOT/examples" "$DOCROOT/examples"/*.ipynb
if [ "$IS_RELEASE" ]; then
echo -e '\nAdding GAnalytics code\n'
ANALYTICS="<script>window.dataLayer=[['js',new Date()],['config','UA-43663477-4']]</script><script async src='https://www.googletagmanager.com/gtag/js?id=UA-43663477-4'></script>"
find "$BUILDROOT" -name '*.html' -print0 |
xargs -0 -- sed -i "s#<head>#<head>$ANALYTICS#i"
fi
echo
echo 'Testing for broken links'
echo
pushd "$BUILDROOT" >/dev/null
tmpdir="$(mktemp -d)"
python3 -m http.server 51296 & sleep 1
trap '{ rm -r "$tmpdir"; kill %1; wait; } >/dev/null 2>&1' EXIT
[ ! "$(jobs -p)" ] && die 'Server not running. See above.'
find -name '*.html' -print0 |
sed --null-data 's/^/http:\/\/127.0.0.1:51296\//' |
xargs -0 -- \
wget --user-agent "Mozilla/5.0 Firefox 61" -e 'robots=off' --random-wait \
--no-verbose --recursive --span-hosts --level=1 --tries=2 \
--directory-prefix "$tmpdir" --no-clobber \
--reject-regex='\bfonts\b|\.css\b|\bjs\b|\.png\b' |&
grep -B1 'ERROR 404'
popd >/dev/null
echo
echo "All good. Docs in: $BUILDROOT"
echo
echo " file://$BUILDROOT/backtesting/index.html"
echo

20
doc/deploy.sh Normal file
View File

@@ -0,0 +1,20 @@
#!/bin/bash
set -eu
if [ ! -d doc/build ]; then
echo 'Error: invalid directory. Deploy from repo root.'
exit 1
fi
[ "$GH_PASSWORD" ] || exit 12
head=$(git rev-parse HEAD)
git clone -b gh-pages "https://kernc:$GH_PASSWORD@github.com/$TRAVIS_REPO_SLUG.git" gh-pages
mkdir -p gh-pages/doc
cp -R doc/build/* gh-pages/doc/
cd gh-pages
git add *
git diff --quiet && echo "$0: No changes to commit." && exit 0
git commit -a -m "CI: Update docs for $TRAVIS_TAG ($head)"
git push

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,172 @@
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.3'
# jupytext_version: 0.8.6
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# Multiple Time Frames
# ============
#
# The best trading strategies relying on technical analysis take into account the price action on multiple time frames.
# This tutorial will show how to do that with _backtesting.py_, offloading most of the work to
# [pandas resampling](http://pandas.pydata.org/pandas-docs/stable/timeseries.html#resampling).
# It is assumed you're already familiar with
# [basic _backtesting.py_ usage](https://kernc.github.io/backtesting.py/doc/examples/Quick Start User Guide.html).
#
# We will test this supposed long-only
# [400%-a-year trading strategy](http://jbmarwood.com/stock-trading-strategy-300/),
# which daily and weekly
# [relative strength index](https://en.wikipedia.org/wiki/Relative_strength_index)
# (RSI) values and moving averages (MA).
#
# Let's introduce the two indicators we'll be using.
# In practice, one can use functions from any indicator library, such as
# [TA-Lib](https://github.com/mrjbq7/ta-lib),
# [Tulipy](https://tulipindicators.org),
# PyAlgoTrade, ...
# +
import pandas as pd
def SMA(array, n):
"""Simple moving average"""
return pd.Series(array).rolling(n).mean()
def RSI(array, n):
"""Relative strength index"""
# Approximate; good enough
gain = pd.Series(array).diff()
loss = gain.copy()
gain[gain < 0] = 0
loss[loss > 0] = 0
rs = gain.ewm(n).mean() / loss.abs().ewm(n).mean()
return 100 - 100 / (1 + rs)
# -
# The strategy roughly goes like this:
#
# Buy a position when:
# * weekly RSI(30) $\geq$ daily RSI(30) $>$ 70
# * Close $>$ MA(10) $>$ MA(20) $>$ MA(50) $>$ MA(100)
#
# Close the position when:
# * Close more than 2% _below_ MA(10)
# * 8% fixed stop loss is hit
#
# We need to provide bars data in the _lowest time frame_ (i.e. daily) and resample it to any higher time frames (i.e. weekly) that our strategy requires.
# +
from backtesting import Strategy, Backtest
from backtesting.lib import resample_apply
class System(Strategy):
d_rsi = 30 # Daily RSI lookback periods
w_rsi = 30 # Weekly
level = 70
def init(self):
# Compute moving averages the strategy demands
self.ma10 = self.I(SMA, self.data.Close, 10)
self.ma20 = self.I(SMA, self.data.Close, 20)
self.ma50 = self.I(SMA, self.data.Close, 50)
self.ma100 = self.I(SMA, self.data.Close, 100)
# Compute daily RSI(30)
self.daily_rsi = self.I(RSI, self.data.Close, self.d_rsi)
# To construct weekly RSI, we have to resample
# the daily values.
# Strategy exposes `self.data` as raw NumPy arrays.
# Let's make closing prices back a pandas Series.
close = pd.Series(self.data.Close,
index=self.data.index,
name='Close')
# Resample to weekly resolution, ending weeks on
# fridays. Aggregate groups using their last value
# (i.e. week's closing price).
# Notice `label='right'`. If it were set to 'left' (default),
# the strategy would exhibit look-ahead bias.
weekly_close = close.resample('W-FRI', label='right').agg('last')
# We apply RSI(30) to weekly close
# prices, then reindex it back to original daily
# index, forward-filling the missing values in each
# week.
# We make a separate function that returns the final
# indicator array.
def W_RSI(series, n):
return RSI(series, n).reindex(close.index).ffill()
self.weekly_rsi = self.I(W_RSI, weekly_close, self.w_rsi)
# ... And, now that you know what goes on behind the scenes,
# we could achieve the whole *exact* same thing with simpler:
self.weekly_rsi = resample_apply(
'W-FRI', RSI, self.data.Close, self.w_rsi)
def next(self):
price = self.data.Close[-1]
# If we don't already have a position, and
# if all conditions are satisfied, enter long.
if (not self.position and
self.daily_rsi[-1] > self.level and
self.weekly_rsi[-1] > self.level and
self.weekly_rsi[-1] > self.daily_rsi[-1] and
self.ma10[-1] > self.ma20[-1] > self.ma50[-1] > self.ma100[-1] and
price > self.ma10[-1]):
# Buy at market price on next open, but do
# set 8% fixed stop loss.
self.buy(sl=.92 * price)
# If the price closes 2% or more below 10-day MA
# close the position, if any.
elif price < .98 * self.ma10[-1]:
self.position.close()
# -
# Let's see how our strategy fares replayed on nine years of Google stock data.
# +
from backtesting.test import GOOG
backtest = Backtest(GOOG, System, commission=.002)
backtest.run()
# -
# Meager four trades in a span of nine years with effectively zero return? How about if we optimize the parameters a bit?
# +
# %%time
backtest.optimize(d_rsi=range(10, 35, 5),
w_rsi=range(10, 35, 5),
level=range(30, 80, 10))
# -
backtest.plot()
# Better. While the strategy doesn't perform as well as simple buy & hold, it does so with significantly lower exposure (time in market).
#
# In conclusion, to test strategies on multiple time frames, you need to pass in data in the lowest time frame, then resample it to higher time frames, apply the indicators, then resample back to lower time frame, filling in the in-betweens.
# Or simply use [`backtesting.lib.resample_apply()`](https://kernc.github.io/backtesting.py/doc/backtesting/lib.html#backtesting.lib.resample_apply) function.

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,152 @@
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.3'
# jupytext_version: 0.8.6
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# Parameter Heatmap
# ==========
#
# This tutorial will show how to optimize strategies with multiple parameters and how to examine and reason about optimization results.
# It is assumed you're already familiar with
# [basic _backtesting.py_ usage](https://kernc.github.io/backtesting.py/doc/examples/Quick Start User Guide.html).
#
# First, let's again import a helper moving average function.
# In practice, one can use functions from any indicator library, such as
# [TA-Lib](https://github.com/mrjbq7/ta-lib),
# [Tulipy](https://tulipindicators.org),
# PyAlgoTrade, ...
from backtesting.test import SMA
# Our strategy will be a similar moving average cross-over strategy to the one in
# [Quick Start User Guide](https://kernc.github.io/backtesting.py/doc/examples/Quick Start User Guide.html),
# but there will be four moving averages in total:
# two moving averages whose relationship determines a general trend
# (we only trade long when the shorter MA is above the longer one, and vice versa),
# and two moving averages whose cross-over with Close prices determine the signal to enter or exit the position.
# +
from backtesting import Strategy
from backtesting.lib import crossover
class Sma4Cross(Strategy):
n1 = 50
n2 = 100
n_enter = 20
n_exit = 10
def init(self):
self.sma1 = self.I(SMA, self.data.Close, self.n1)
self.sma2 = self.I(SMA, self.data.Close, self.n2)
self.sma_enter = self.I(SMA, self.data.Close, self.n_enter)
self.sma_exit = self.I(SMA, self.data.Close, self.n_exit)
def next(self):
if not self.position:
# On upwards trend, if price closes above
# "entry" MA, go long
# Here, even though the operands are arrays, this
# works by implicitly comparing the two last values
if self.sma1 > self.sma2:
if crossover(self.data.Close, self.sma_enter):
self.buy()
# On downwards trend, if price closes below
# "entry" MA, go short
else:
if crossover(self.sma_enter, self.data.Close):
self.sell()
# But if we already hold a position and the price
# closes back below (above) "exit" MA, close the position
else:
if (self.position.is_long and
crossover(self.sma_exit, self.data.Close)
or
self.position.is_short and
crossover(self.data.Close, self.sma_exit)):
self.position.close()
# -
# It's not a robust strategy, but we can optimize it. Let's optimize our strategy on Google stock data.
# +
# %%time
from backtesting import Backtest
from backtesting.test import GOOG
backtest = Backtest(GOOG, Sma4Cross, commission=.002)
stats, heatmap = backtest.optimize(
n1=range(10, 110, 10),
n2=range(20, 210, 20),
n_enter=range(15, 35, 5),
n_exit=range(10, 25, 5),
constraint=lambda p: p.n_exit < p.n_enter < p.n1 < p.n2,
maximize='Equity Final [$]',
return_heatmap=True)
# -
# Notice `return_heatmap=True` parameter passed to
# [`Backtest.optimize()`](https://kernc.github.io/backtesting.py/doc/backtesting/backtesting.html#backtesting.backtesting.Backtest.optimize).
# It makes the function return a heatmap series along with the usual stats of the best run.
# `heatmap` is a pandas Series indexed with a MultiIndex, a cartesian product of all permissible parameter values.
# The series vales are from the `maximize=` field we provided.
heatmap
# This heatmap contains the results of all the runs,
# and it's very easy to obtain parameter combinations for e.g. three best runs:
heatmap.sort_values().iloc[-3:]
# But people have this enormous faculty of vision we use to make judgements on much larger data sets much faster.
# Let's plot the whole heatmap by projecting it on two chosen dimensions.
# Say we're mostly interested how parameters `n1` and `n2`, on average, affect the outcome.
hm = heatmap.groupby(['n1', 'n2']).mean().unstack()
hm
# Let's plot that using the excellent [_Seaborn_](https://seaborn.pydata.org) package:
# +
# %matplotlib inline
import seaborn as sns
sns.heatmap(hm[::-1], cmap='viridis')
# -
# We see that, on average, we obtain the highest result using trend-determining parameters `n1=40` and `n2=60`,
# and it's not like other nearby combinations work similarly well — in our particular strategy, this combination really stands out.
#
# Since our strategy contains several parameters, we might be interested in other relationships between their values.
# We can use
# [`backtesting.lib.plot_heatmaps()`](https://kernc.github.io/backtesting.py/doc/backtesting/lib.html#backtesting.lib.plot_heatmaps)
# function to plot interactive heatmaps of all parameter combinations simultaneously.
# +
from backtesting.lib import plot_heatmaps
plot_heatmaps(heatmap, agg='mean')

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,186 @@
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.3'
# jupytext_version: 0.8.6
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# _Backtesting.py_ Quick Start User Guide
# =======================
#
# This tutorial will show off some of the features of _backtesting.py_, yet another Python package for [backtesting](https://www.investopedia.com/terms/b/backtesting.asp) trading strategies.
#
# Firstly, what _backtesting.py_ is not: It is not a data source — you bring your own data. It does _not_ support strategies that rely on multiple orders, hedging, position sizing, or portfolio rebalancing. Instead, _backtesting.py_ works with a single asset at a time, a single position at a time (long or short), and the position size is (as yet) non-adjustable, corresponding to 100% of available funds. _Backtesting.py_ is not aware of order types and does not properly simulate, nor can be connected to, a broker.
#
# As a trade-off, _backtesting.py_ is a _blazing fast_, small and lightweight backtesting library that uses state-of-the-art Python data structures and procedures, and whose whole API easily fits into memory of a single human. It's best suited for optimizing position entrence and exit strategies, decisions upon values of technical indicators, and it's also a versatile interactive trading strategy visualization tool.
#
# ### Data
#
# _You bring your own data._ Backtesting ingests data as a [pandas.DataFrame](https://pandas.pydata.org/pandas-docs/stable/10min.html) with columns 'Open', 'High', 'Low', 'Close', and (optionally) 'Volume'. Such data is easily obtainable (see e.g.
# [pandas-datareader](https://pandas-datareader.readthedocs.io/en/latest/),
# [Quandl](https://www.quandl.com/tools/python),
# [findatapy](https://github.com/cuemacro/findatapy), ...).
# Your data frame can have other columns, but these are necessary.
# DataFrame should ideally be indexed with a datetime index (convert it with [`pd.to_datetime()`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.to_datetime.html)), otherwise a simple range index will do.
# Let's see it.
# +
# Example OHLC data for Google Inc.
from backtesting.test import GOOG
GOOG.tail()
# -
# ### Strategy
#
# Let's create our first strategy to backtest on these Google data, and let it be a simple [moving average (MA) cross-over strategy](https://en.wikipedia.org/wiki/Moving_average_crossover).
#
# _Backtesting.py_ doesn't contain its own set of technical indicators. In practice, one should probably use functions from their favorite indicator library, such as
# [TA-Lib](https://github.com/mrjbq7/ta-lib),
# [Tulipy](https://tulipindicators.org),
# PyAlgoTrade, ...
# But for this example, let's define a simple helper moving average function.
# +
import pandas as pd
def SMA(values, n):
"""
Return simple moving average of `values`, at
each step taking into account `n` previous values.
"""
return pd.Series(values).rolling(n).mean()
# -
# Note, this is the exact same helper function as the one used in the project unit tests.
from backtesting.test import SMA
# A custom strategy needs to extend `backtesting.Strategy` class and override two methods:
# [`init()`](https://kernc.github.io/backtesting.py/doc/backtesting/backtesting.html#backtesting.backtesting.Strategy.init) and
# [`next()`](https://kernc.github.io/backtesting.py/doc/backtesting/backtesting.html#backtesting.backtesting.Strategy.next).
#
# Method `init()` is invoked at the beginning, before the strategy is run. Within it, one ideally precomputes in efficient, vectorized fashion whatever indicators and signals the strategy depends on.
#
# Method `next()` is iteratively called by the backtest instance, once for each data point (data frame row), simulating the incremental availability of each new full candlestick bar. Note, _backtesting.py_ cannot make decisions/trade within candlesticks. If you need to trade within candlesticks, instead start with more fine-grained data.
# +
from backtesting import Strategy
from backtesting.lib import crossover
class SmaCross(Strategy):
# Define the two MA lags as *class variables*
# for later optimization
n1 = 10
n2 = 20
def init(self):
# Precompute two moving averages
self.sma1 = self.I(SMA, self.data.Close, self.n1)
self.sma2 = self.I(SMA, self.data.Close, self.n2)
def next(self):
# If sma1 crosses above sma2, buy the asset
if crossover(self.sma1, self.sma2):
self.buy()
# Else, if sma1 crosses below sma2, sell it
elif crossover(self.sma2, self.sma1):
self.sell()
# -
# In `init()` as well as in `next()`, the data we are simulating the strategy on is available as an instance variable
# [`self.data`](https://kernc.github.io/backtesting.py/doc/backtesting/backtesting.html#backtesting.backtesting.Strategy.data).
#
# In `init()`, we compute indicators indirectly by wrapping them in
# [`self.I()`](https://kernc.github.io/backtesting.py/doc/backtesting/backtesting.html#backtesting.backtesting.Strategy.I).
# We pass the wrapper a function (here, our `SMA` function) and any additional arguments to call it with (here, our _Close_ values and the MA lag). Indicators wrapped in this way will be plotted, and their names, intelligently inferred, will appear in the plot legend.
#
# In `next()`, we simply check if the faster moving average just crossed over the slower one. If it did and upwards, we go long; if it did and downwards, we sell any open long position and go short. Note, there is no position size to adjust; _Backtesting.py_ always assumes maximal possible position. We use
# [`backtesting.lib.crossover()`](https://kernc.github.io/backtesting.py/doc/backtesting/lib.html#backtesting.lib.crossover)
# function instead of writing more obscure and confusing conditions, such as:
# + {"active": ""}
# def next(self):
# if (self.sma1[-2] < self.sma2[-2] and
# self.sma1[-1] > self.sma2[-1]):
# self.buy()
#
# elif (self.sma1[-2] > self.sma2[-2] and
# self.sma1[-1] < self.sma2[-1]):
# self.sell()
# -
# Ugh!
#
# In `init()`, the whole series of points was available, whereas in `next()`, the _length of `self.data` and any indicator arrays is adjusted_ on each `next()` call so that `array[-1]` (e.g. `self.data.Close[-1]` or `self.sma1[-1]`) always contains the most recent value, `array[-2]` the previous value, etc. (ordinary Python indexing of ascending-sorted 1D arrays).
#
# **Note**: `self.data` and any indicators wrapped with `self.I` (e.g. `self.sma1`) are **NumPy arrays** for performance reasons. If you need them to be `pandas.Series`, use, e.g., `pd.Series(self.data.Close, index=self.data.index)`.
#
# Let's see now how our strategy performs on historical Google data. We'll begin with ¤10,000 in cash and set broker's commission to realistic 0.2%.
# +
from backtesting import Backtest
bt = Backtest(GOOG, SmaCross, cash=10000, commission=.002)
bt.run()
# -
# We initialize the
# [`Backtest`](https://kernc.github.io/backtesting.py/doc/backtesting/backtesting.html#backtesting.backtesting.Backtest)
# instance with data and strategy _class_ (see API reference for additional options).
#
# As we call
# [`Backtest.run()`](https://kernc.github.io/backtesting.py/doc/backtesting/backtesting.html#backtesting.backtesting.Backtest.run)
# method, we instantaneously get returned a pandas Series of results and statistics associated with our strategy. We see that this simple strategy makes 600% return in the period of 9 years, with maximal drawdown 33%, and with longest drawdown period spanning almost two years ...
#
# If we call
# [`Backtest.plot()`](https://kernc.github.io/backtesting.py/doc/backtesting/backtesting.html#backtesting.backtesting.Backtest.plot)
# method, we can review these results in a more visual form.
bt.plot()
# ### Optimization
#
# We hard-coded the two lag parameters into our strategy above, but perhaps the strategy works better with 1530 cross-over, or some other combination. We defined the two parameters as optimizable by making them [class variables](https://docs.python.org/3/tutorial/classes.html#class-and-instance-variables).
# We optimize the two parameters by calling
# [`Backtest.optimize()`](https://kernc.github.io/backtesting.py/doc/backtesting/backtesting.html#backtesting.backtesting.Backtest.optimize)
# method with each parameter a keyword argument pointing to its pool of values to test. Parameter `n1` is tested from 5 to 30, and parameter `n2` from 10 to 70. Some combinations of the two parameters are invalid, i.e. we don't ever want `n1` to be _larger than_ or equal to `n2`. We limit admissible parameter combinations with an _ad hoc_ constraint function, which returns `True` (admissible) whenever `n1` is less than `n2`. Additionally, we search for such parameter combination that maximizes final equity (we can choose any key from the returned `stats` series).
# +
# %%time
stats = bt.optimize(n1=range(5, 30, 5),
n2=range(10, 70, 5),
maximize='Equity Final [$]',
constraint=lambda p: p.n1 < p.n2)
# -
stats
# We can look into `stats._strategy` field for the Strategy instance and its optimal parameter values (10 and 15).
bt.plot()
# Optimizing the strategy, we managed to up its initial performance _on in-sample data_ by almost 70% and beat
# [buy & hold](https://en.wikipedia.org/wiki/Buy_and_hold).
# In real life, however, do take steps to avoid
# [overfitting](https://en.wikipedia.org/wiki/Overfitting)
# before putting real money at risk.
#
# Learn more by reviewing further
# [examples](https://kernc.github.io/backtesting.py/doc/backtesting/index.html#tutorials),
# or find more program options in the
# [full API documentation](https://kernc.github.io/backtesting.py/doc/backtesting/index.html#header-submodules).

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,101 @@
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.3'
# jupytext_version: 0.8.6
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# Library of Composable Base Strategies
# ======================
#
# This tutorial will show how to reuse composable base strategies that are part of this software distribution.
# It is assumed you're already familiar with
# [basic _backtesting.py_ usage](https://kernc.github.io/backtesting.py/doc/examples/Quick Start User Guide.html).
#
# We'll extend the same moving average cross-over strategy as in
# [Quick Start User Guide](https://kernc.github.io/backtesting.py/doc/examples/Quick Start User Guide.html),
# but we'll rewrite it as a vectorized signal strategy and add trailing stop-loss.
#
# We'll again use a helper moving average function.
# In practice, one can use functions from any indicator library, such as
# [TA-Lib](https://github.com/mrjbq7/ta-lib),
# [Tulipy](https://tulipindicators.org),
# PyAlgoTrade, ...
from backtesting.test import SMA
# _Backtesting.py_ package includes
# [_lib_](https://kernc.github.io/backtesting.py/doc/backtesting/lib.html)
# module that contains various reusable utilities for developing strategies.
# Some of those utilities are composable base strategies one can extend and build upon.
#
# We import and extend two of those strategies here:
# * [`SignalStrategy`](https://kernc.github.io/backtesting.py/doc/backtesting/lib.html#backtesting.lib.SignalStrategy)
# which decides upon a single signal vector whether to buy into a position, akin to
# [vectorized backtesting](https://www.google.com/search?q=vectorized+backtesting)
# engines, and
# * [`TrailingStrategy`](https://kernc.github.io/backtesting.py/doc/backtesting/lib.html#backtesting.lib.TrailingStrategy)
# which automatically trails the current price with a stop-loss order some multiple of
# [average true range](https://en.wikipedia.org/wiki/Average_true_range)
# (ATR) away.
# +
import pandas as pd
from backtesting.lib import SignalStrategy, TrailingStrategy
class SmaCross(SignalStrategy,
TrailingStrategy):
n1 = 10
n2 = 20
def init(self):
# In init() and in next() it is important to call the
# super method to properly initialize all the classes
super().init()
# Precompute the two moving averages
sma1 = self.I(SMA, self.data.Close, self.n1)
sma2 = self.I(SMA, self.data.Close, self.n2)
# Taking a first difference (`.diff()`) of a boolean
# series results in +1, 0, and -1 values. In our signal,
# as expected by SignalStrategy, +1 means buy,
# -1 means sell, and 0 means to hold whatever current
# position and wait. See the docs.
signal = (pd.Series(sma1) > sma2).astype(int).diff().fillna(0)
# Set the signal vector using the method provided
# by SignalStrategy
self.set_signal(signal)
# Set trailing stop-loss to 4x ATR
# using the method provided by TrailingStrategy
self.set_trailing_sl(4)
# -
# Note, since the strategies in _lib_ may require their own intialization and next-tick logic, be sure to **always call `super().init()` and `super().next()` in your overridden methods**.
#
# Let's see how the example strategy fares on historical Google data.
# +
from backtesting import Backtest
from backtesting.test import GOOG
bt = Backtest(GOOG, SmaCross, commission=.002)
bt.run()
bt.plot()
# -
# Notice how managing risk with a trailing stop-loss severely limits our losses.
#
# For other strategies of the sort, and other reusable utilities in general, see the
# [_lib_ module reference](https://kernc.github.io/backtesting.py/doc/backtesting/lib.html).

9
doc/ipython_config.py Normal file
View File

@@ -0,0 +1,9 @@
# In build.sh, this file is copied into (and removed from)
# ~/.ipython/profile_default/startup/
import pandas as pd
pd.set_option("display.max_rows", 30)
# This an alternative to setting display.preceision=2,
# which doesn't work well for our dtype=object Series.
pd.set_option('display.float_format', '{:.2f}'.format)
del pd

View File

@@ -0,0 +1,14 @@
<%!
html_lang = 'en'
show_inherited_members = False
extract_module_toc_into_sidebar = True
list_class_variables_in_index = True
from pdoc.html_helpers import glimpse as _glimpse
# Make visible the code block from the first paragraph of the
# `backtesting.backtesting` module
def glimpse(text, *args, **kwargs):
return _glimpse(text, max_length=180, paragraph=False)
%>

View File

@@ -0,0 +1,10 @@
<%!
from backtesting import __version__
%>
<p>
<a href="https://kernc.github.io/backtesting.py/"><cite>backtesting</cite> ${__version__}</a>
<span style="color:#ddd">&#21328;</span>
</p>
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/highlight.min.js"></script>
<script>hljs.configure({languages: ['python']}); hljs.initHighlightingOnLoad()</script>

View File

@@ -0,0 +1,28 @@
<%!
from pdoc.html_helpers import minify_css
%>
<%def name="homelink()" filter="minify_css">
.homelink {
display: block;
font-size: 2em;
font-weight: bold;
color: #555;
background: #f6f6f6;
text-align: center;
padding: .5em 0;
}
.homelink:hover {
color: inherit;
}
.homelink img {
display: block;
max-width:40%;
max-height: 5em;
margin: auto;
margin-bottom: .3em;
}
</%def>
<style>${homelink()}</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/9.12.0/styles/github.min.css">
<link rel="canonical" href="https://kernc.github.io/backtesting.py/doc/${module.url(link_prefix=link_prefix)}">

View File

@@ -0,0 +1,5 @@
<header>
<a class="homelink" rel="home" title="Backtesting.py Home" href="https://kernc.github.io/backtesting.py/">
<img src="https://kernc.github.io/backtesting.py/logo.png" alt=""> Backtesting.py
</a>
</header>

BIN
logo.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.9 KiB

29
logo.py Normal file
View File

@@ -0,0 +1,29 @@
from bokeh.io import show, output_file
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
output_file("backtesting_logo.html")
source = ColumnDataSource(data=dict(
colors=[['#00a618', '#d0d000', 'tomato'][i]
for i in [0, 0, 1, 0, 1, 0, 0, 1, 0, 2]],
x=list(range(10)),
bottom=[1, 3, 4, 3, 2, 3, 5, 5, 7, 6.5],
top= [4, 7, 6, 5, 4, 6, 8, 7, 9, 8])) # noqa: E222,E251
p = figure(plot_height=800, plot_width=1200, tools='wheel_zoom,save')
p.vbar('x', .6, 'bottom', 'top', source=source,
line_color='black', line_width=2,
fill_color='colors')
p.xgrid.grid_line_color = None
p.ygrid.grid_line_color = None
p.y_range.start = -2
p.y_range.end = 12
p.x_range.start = -2
p.x_range.end = 11
p.background_fill_color = None
p.border_fill_color = None
show(p)

112
setup.py Normal file
View File

@@ -0,0 +1,112 @@
import os
import sys
if sys.version_info < (3, 4):
sys.exit('ERROR: Backtesting.py requires Python 3.4+')
def _discover_tests():
import unittest
return unittest.defaultTestLoader.discover('backtesting.test',
pattern='*test*.py',
top_level_dir='.')
if __name__ == '__main__':
from setuptools import setup
setup(
name='Backtesting',
description="Backtest trading strategies in Python",
license='AGPL-3.0',
url="https://github.com/kernc/backtesting.py",
long_description=open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
long_description_content_type='text/markdown',
setup_requires=[
'setuptools_git',
'setuptools_scm',
],
use_scm_version={
'write_to': os.path.join('backtesting', '_version.py'),
},
install_requires=[
'typing ; python_version < "3.5"',
'numpy',
'pandas',
'bokeh >= 0.12.15',
],
extras_require={
'doc': [
'pdoc3',
'jupytext >= 0.7.0',
'nbconvert',
],
},
test_suite="setup._discover_tests",
python_requires='>=3.4',
author='Zach Lûster',
classifiers=[
'Intended Audience :: Financial and Insurance Industry',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: GNU Affero General Public License v3 or later (AGPLv3+)',
'Operating System :: OS Independent',
'Programming Language :: Python :: 3 :: Only',
'Topic :: Office/Business :: Financial :: Investment',
'Topic :: Scientific/Engineering :: Visualization',
],
keywords=(
'algo',
'algorithmic',
'ashi',
'backtest',
'backtesting',
'bitcoin',
'bokeh',
'bonds',
'candles',
'candlestick',
'cboe',
'chart',
'cme',
'commodities',
'crash',
'crypto',
'currency',
'drawdown',
'equity',
'ethereum',
'exchange',
'finance',
'financial',
'forex',
'fund',
'futures',
'fx',
'fxpro',
'gold',
'heiken',
'historical',
'indicator',
'invest',
'investing',
'investment',
'macd',
'market',
'mechanical',
'money',
'oanda',
'ohlc',
'ohlcv',
'order',
'profit',
'quant',
'quantitative',
'silver',
'stocks',
'strategy',
'ticker',
'trader',
'trading',
'tradingview',
'usd',
),
)