├── .gitignore
├── LICENSE
├── README.md
├── backtrader_rl
├── __init__.py
├── adapters
│ ├── __init__.py
│ ├── gymAdapter.py
│ └── tensorforceAdapter.py
├── engines.py
├── strategys.py
└── utils.py
├── examples
├── BNB_USDT_5m.csv
├── BTC_USDT_1h.csv
├── BTC_USDT_5m.csv
├── downloader.py
├── gym_env_example.py
├── raylib_example.py
└── tensorforce_example.py
└── setup.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | build/
12 | develop-eggs/
13 | dist/
14 | downloads/
15 | eggs/
16 | .eggs/
17 | lib/
18 | lib64/
19 | parts/
20 | sdist/
21 | var/
22 | wheels/
23 | pip-wheel-metadata/
24 | share/python-wheels/
25 | *.egg-info/
26 | .installed.cfg
27 | *.egg
28 | MANIFEST
29 |
30 | # PyInstaller
31 | # Usually these files are written by a python script from a template
32 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
33 | *.manifest
34 | *.spec
35 |
36 | # Installer logs
37 | pip-log.txt
38 | pip-delete-this-directory.txt
39 |
40 | # Unit test / coverage reports
41 | htmlcov/
42 | .tox/
43 | .nox/
44 | .coverage
45 | .coverage.*
46 | .cache
47 | nosetests.xml
48 | coverage.xml
49 | *.cover
50 | *.py,cover
51 | .hypothesis/
52 | .pytest_cache/
53 |
54 | # Translations
55 | *.mo
56 | *.pot
57 |
58 | # Django stuff:
59 | *.log
60 | local_settings.py
61 | db.sqlite3
62 | db.sqlite3-journal
63 |
64 | # Flask stuff:
65 | instance/
66 | .webassets-cache
67 |
68 | # Scrapy stuff:
69 | .scrapy
70 |
71 | # Sphinx documentation
72 | docs/_build/
73 |
74 | # PyBuilder
75 | target/
76 |
77 | # Jupyter Notebook
78 | .ipynb_checkpoints
79 |
80 | # IPython
81 | profile_default/
82 | ipython_config.py
83 |
84 | # pyenv
85 | .python-version
86 |
87 | # pipenv
88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies
90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not
91 | # install all needed dependencies.
92 | #Pipfile.lock
93 |
94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow
95 | __pypackages__/
96 |
97 | # Celery stuff
98 | celerybeat-schedule
99 | celerybeat.pid
100 |
101 | # SageMath parsed files
102 | *.sage.py
103 |
104 | # Environments
105 | .env
106 | .venv
107 | env/
108 | venv/
109 | ENV/
110 | env.bak/
111 | venv.bak/
112 |
113 | # Spyder project settings
114 | .spyderproject
115 | .spyproject
116 |
117 | # Rope project settings
118 | .ropeproject
119 |
120 | # mkdocs documentation
121 | /site
122 |
123 | # mypy
124 | .mypy_cache/
125 | .dmypy.json
126 | dmypy.json
127 |
128 | # Pyre type checker
129 | .pyre/
130 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Backtrader-RL
2 |
3 | Reinforcemenet Learning Environment build upon the backtrader ecosystem
4 |
5 | # TODO
6 |
7 | * [X] Environment Wrapper to instead step through a cerebro.run call
8 |
--------------------------------------------------------------------------------
/backtrader_rl/__init__.py:
--------------------------------------------------------------------------------
1 | name = "btrl"
--------------------------------------------------------------------------------
/backtrader_rl/adapters/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/MaxLoedige/Backtrader-RL/028e227aa7e653e1159c5029fad1dc1bd3255664/backtrader_rl/adapters/__init__.py
--------------------------------------------------------------------------------
/backtrader_rl/adapters/gymAdapter.py:
--------------------------------------------------------------------------------
1 | import gym
2 | from gym import spaces
3 | from numpy import infty
4 |
5 | class gymAdapter(gym.Env):
6 |
7 | def __init__(self,engine,**kwargs):
8 | super().__init__(**kwargs)
9 | self.engine = engine
10 | self.action_space = spaces.Discrete(3)
11 | self.engine.action_mapping = {"buy" : 2, "sell" : 0, "hold":1}
12 | self.observation_space = spaces.Box(low = 0,high = infty, shape = self.engine.state_shape)
13 |
14 | def step(self,action):
15 | observation, reward, self.terminated = self.engine.step(action)
16 | truncated = False
17 | info = {}
18 | return observation, reward, self.terminated, truncated, info
19 |
20 | def reset(self,seed = None, options = {}):
21 | observation = self.engine.reset(seed = seed,**options)
22 | info = {}
23 | return observation, info
24 |
25 | def render(self):
26 | if self.terminated:
27 | self.engine.plot()
28 |
29 | def close(self):
30 | self.engine.close()
31 |
--------------------------------------------------------------------------------
/backtrader_rl/adapters/tensorforceAdapter.py:
--------------------------------------------------------------------------------
1 | from tensorforce import Environment
2 | from numpy import infty
3 |
4 | class tensorforceAdapter(Environment):
5 |
6 | def __init__(self,engine,**kwargs):
7 | super().__init__(**kwargs)
8 | self.engine = engine
9 |
10 | def states(self):
11 | return dict(type='float', min_value = 0, shape=self.engine.state_shape)
12 |
13 | def actions(self):
14 | return dict(type='int', num_values=len(self.engine.actions_mapping))
15 |
16 | def close(self):
17 | self.engine.close()
18 |
19 | def reset(self,options = {}):
20 | observation = self.engine.reset(seed = None,**options)
21 | return observation
22 |
23 | def execute(self, actions):
24 | observation, reward, self.terminated = self.engine.step(actions)
25 | return observation, self.terminated, reward
26 |
27 | def plot(self):
28 | return self.engine.plot()
--------------------------------------------------------------------------------
/backtrader_rl/engines.py:
--------------------------------------------------------------------------------
1 | import backtrader as bt
2 | from backtrader.utils import num2date, date2num
3 | import datetime
4 | import numpy as np
5 |
6 | class BTEngine(bt.Cerebro):
7 |
8 | params = (
9 | ('preload', False),
10 | ('runonce', False),
11 | ('maxcpus', None),
12 | ('stdstats', False),
13 | ('oldbuysell', False),
14 | ('oldtrades', False),
15 | ('lookahead', 0),
16 | ('exactbars', False),
17 | ('optdatas', True),
18 | ('optreturn', True),
19 | ('objcache', False),
20 | ('live', False),
21 | ('writer', False),
22 | ('tradehistory', False),
23 | ('oldsync', False),
24 | ('tz', None),
25 | ('cheat_on_open', False),
26 | ('broker_coo', True),
27 | ('quicknotify', False),
28 | )
29 |
30 | def __init__(self,lookback,state_rows = ("close",),action_mapping = None, normalize = True, canhold = True):
31 | super().__init__()
32 |
33 | if len(state_rows) == 1:
34 |
35 | if state_rows[0] == "ohlc":
36 | state_rows = ("open" , "high" , "close" , "low")
37 |
38 | elif state_rows[0] == "ohlcv":
39 | state_rows = ("open" , "high" , "close" , "low", "volume")
40 |
41 | if type(state_rows) == str:
42 |
43 | if state_rows == "ohlc":
44 | state_rows = ("open" , "high" , "close" , "low")
45 |
46 | elif state_rows == "ohlcv":
47 | state_rows = ("open" , "high" , "close" , "low", "volume")
48 |
49 | elif state_rows in ("open" , "high" , "close" , "low", "volume"):
50 | state_rows = (state_rows,)
51 |
52 | assert type(state_rows) == tuple
53 |
54 |
55 | self.state_shape = (len(state_rows),lookback)
56 | self.lookback = lookback
57 |
58 | self.state_rows = state_rows
59 |
60 | if canhold:
61 | self.num_actions = 3
62 | mapping ={"buy" : 2, "sell" : 0, "hold":1}
63 | else:
64 | self.num_actions = 2
65 | mapping ={"buy" : 1, "sell" : 0}
66 |
67 | if action_mapping:
68 | self.actions_mapping = action_mapping
69 | else:
70 | self.actions_mapping = mapping
71 |
72 | self.canhold = canhold
73 |
74 | self.possible_actions = [self.actions_mapping[key] for key in self.actions_mapping]
75 | self.possible_actions.append(-1)
76 |
77 | self.normalize = normalize
78 |
79 | self.broker.set_shortcash(False)
80 |
81 | ## ==============================
82 | ## Default Interface Methods
83 | ## ==============================
84 |
85 | def step(self,action = None):
86 | if action is None:
87 | # TODO define dault action
88 | action = -1
89 |
90 | assert action in self.possible_actions
91 |
92 | observation = None
93 | reward = 0
94 | #print(self.strats[0][0][0])
95 | # self.strats[0][0][0]._setAction(action = action)
96 |
97 | for strat in self.runstrats_container:
98 | strat._setAction(action)
99 |
100 | self.terminated = self._step(self.runstrats_container,**self.bt_state_container)
101 | self.step_count += 1
102 |
103 | observation = self._get_observations()
104 |
105 | for strat in self.runstrats_container:
106 | reward = strat._computeReward()
107 | print(reward)
108 |
109 | return observation, reward, self.terminated
110 |
111 | def reset(self,**kwargs):
112 | self.step_count = 0
113 | self.terminated = False
114 | self.run(**kwargs)
115 |
116 | assert len(self.runstrats_container) == 1
117 | self.runstrats_container[0]._set_action_mapping(self.actions_mapping)
118 |
119 | observation = None
120 |
121 | # TODO fix starting period
122 | # kinda hacky skipping the first lookback
123 | for _ in range(self.lookback):
124 | observation = self.step()[0]
125 | if len(self.state_rows) == 1:
126 | if self.lookback == len(observation):
127 | break
128 | else:
129 | if self.lookback == observation.shape[1]:
130 | break
131 |
132 | return observation
133 |
134 | def close(self):
135 | # Last notification chance before stopping
136 | self._datanotify()
137 | if self._event_stop: # stop if requested
138 | return
139 | self._storenotify()
140 | if self._event_stop: # stop if requested
141 | return
142 |
143 | ## ==============================
144 | ## Cerebro Dissection Methods
145 | ## ==============================
146 |
147 | # Makes Cerebro Stapable in Backtests (not in live moe yet)
148 | # Disects the _runnext method into a stepable function
149 | # the reset method has to call the cerebro run method
150 |
151 | def _runnext(self, runstrats):
152 | '''
153 | Actual implementation of run in full next mode. All objects have its
154 | ``next`` method invoke on each data arrival
155 | '''
156 | self.runstrats_container = runstrats
157 | self._init_run()
158 |
159 | def _init_run(self):
160 | datas = sorted(self.datas,
161 | key=lambda x: (x._timeframe, x._compression))
162 | datas1 = datas[1:]
163 | data0 = datas[0]
164 | d0ret = True
165 | rsonly = [i for i, x in enumerate(datas)
166 | if x.resampling and not x.replaying]
167 | onlyresample = len(datas) == len(rsonly)
168 | noresample = not rsonly
169 |
170 | clonecount = sum(d._clone for d in datas)
171 | ldatas = len(datas)
172 | ldatas_noclones = ldatas - clonecount
173 | dt0 = date2num(datetime.datetime.max) - 2 # default at max
174 |
175 | self.bt_state_container = { "datas" : datas,
176 | "datas1" : datas1,
177 | "data0" : data0,
178 | "d0ret" : d0ret,
179 | "rsonly" : rsonly,
180 | "onlyresample" : onlyresample,
181 | "noresample" : noresample,
182 | "ldatas_noclones" : ldatas_noclones,
183 | "dt0" : dt0,
184 | }
185 |
186 | def _step(self,runstrats,datas,datas1,data0,d0ret,rsonly,
187 | onlyresample,noresample,ldatas_noclones,dt0):
188 |
189 | # if any has live data in the buffer, no data will wait anything
190 | newqcheck = not any(d.haslivedata() for d in datas)
191 | if not newqcheck:
192 | # If no data has reached the live status or all, wait for
193 | # the next incoming data
194 | livecount = sum(d._laststatus == d.LIVE for d in datas)
195 | newqcheck = not livecount or livecount == ldatas_noclones
196 |
197 | lastret = False
198 | # Notify anything from the store even before moving datas
199 | # because datas may not move due to an error reported by the store
200 | self._storenotify()
201 | if self._event_stop: # stop if requested
202 | return True
203 | self._datanotify()
204 | if self._event_stop: # stop if requested
205 | return True
206 |
207 | # record starting time and tell feeds to discount the elapsed time
208 | # from the qcheck value
209 | drets = []
210 | qstart = datetime.datetime.utcnow()
211 | for d in datas:
212 | qlapse = datetime.datetime.utcnow() - qstart
213 | d.do_qcheck(newqcheck, qlapse.total_seconds())
214 | drets.append(d.next(ticks=False))
215 |
216 | d0ret = any((dret for dret in drets))
217 | if not d0ret and any((dret is None for dret in drets)):
218 | d0ret = None
219 |
220 | if d0ret:
221 | dts = []
222 | for i, ret in enumerate(drets):
223 | dts.append(datas[i].datetime[0] if ret else None)
224 |
225 | # Get index to minimum datetime
226 | if onlyresample or noresample:
227 | dt0 = min((d for d in dts if d is not None))
228 | else:
229 | dt0 = min((d for i, d in enumerate(dts)
230 | if d is not None and i not in rsonly))
231 |
232 | dmaster = datas[dts.index(dt0)] # and timemaster
233 | self._dtmaster = dmaster.num2date(dt0)
234 | self._udtmaster = num2date(dt0)
235 |
236 | # slen = len(runstrats[0])
237 | # Try to get something for those that didn't return
238 | for i, ret in enumerate(drets):
239 | if ret: # dts already contains a valid datetime for this i
240 | continue
241 |
242 | # try to get a data by checking with a master
243 | d = datas[i]
244 | d._check(forcedata=dmaster) # check to force output
245 | if d.next(datamaster=dmaster, ticks=False): # retry
246 | dts[i] = d.datetime[0] # good -> store
247 | # self._plotfillers2[i].append(slen) # mark as fill
248 | else:
249 | # self._plotfillers[i].append(slen) # mark as empty
250 | pass
251 |
252 | # make sure only those at dmaster level end up delivering
253 | for i, dti in enumerate(dts):
254 | if dti is not None:
255 | di = datas[i]
256 | rpi = False and di.replaying # to check behavior
257 | if dti > dt0:
258 | if not rpi: # must see all ticks ...
259 | di.rewind() # cannot deliver yet
260 | # self._plotfillers[i].append(slen)
261 | elif not di.replaying:
262 | # Replay forces tick fill, else force here
263 | di._tick_fill(force=True)
264 |
265 | # self._plotfillers2[i].append(slen) # mark as fill
266 |
267 | elif d0ret is None:
268 | # meant for things like live feeds which may not produce a bar
269 | # at the moment but need the loop to run for notifications and
270 | # getting resample and others to produce timely bars
271 | for data in datas:
272 | data._check()
273 | else:
274 | lastret = data0._last()
275 | for data in datas1:
276 | lastret += data._last(datamaster=data0)
277 |
278 | if not lastret:
279 | # Only go extra round if something was changed by "lasts"
280 | return True # return somethin signaling the end
281 |
282 | # Datas may have generated a new notification after next
283 | self._datanotify()
284 | if self._event_stop: # stop if requested
285 | return True
286 |
287 | if d0ret or lastret: # if any bar, check timers before broker
288 | self._check_timers(runstrats, dt0, cheat=True)
289 | if self.p.cheat_on_open:
290 | for strat in runstrats:
291 | strat._next_open()
292 | if self._event_stop: # stop if requested
293 | return True
294 |
295 | self._brokernotify()
296 | if self._event_stop: # stop if requested
297 | return True
298 |
299 | if d0ret or lastret: # bars produced by data or filters
300 | self._check_timers(runstrats, dt0, cheat=False)
301 | for strat in runstrats:
302 | strat._next()
303 | if self._event_stop: # stop if requested
304 | return True
305 |
306 | self._next_writers(runstrats)
307 |
308 | self.bt_state_container = { "datas" : datas,
309 | "datas1" : datas1,
310 | "data0" : data0,
311 | "d0ret" : d0ret,
312 | "rsonly" : rsonly,
313 | "onlyresample" : onlyresample,
314 | "noresample" : noresample,
315 | "ldatas_noclones" : ldatas_noclones,
316 | "dt0" : dt0,
317 | }
318 |
319 | return False
320 |
321 | def _norm(self,data):
322 | return data/np.linalg.norm(data)
323 |
324 | def _get_observations(self):
325 |
326 | if len(self.state_rows) == 1 and self.state_rows not in ["ohlc" , "ohlcv"]:
327 | line = getattr(self.bt_state_container["data0"],self.state_rows[0])
328 | obs = np.array(list(line.get(size=self.lookback,ago=0)))
329 | if self.normalize:
330 | obs = self._norm(obs)
331 | return np.reshape(obs, (1,len(obs)))
332 |
333 | states = []
334 | for row in self.state_rows:
335 | line = getattr(self.bt_state_container["data0"],row)
336 |
337 | obs = np.array(list(line.get(size=self.lookback,ago=0)))
338 |
339 | if self.normalize:
340 | obs = self._norm(obs)
341 |
342 | states.append(obs.tolist())
343 |
344 | return np.array(states)
345 |
--------------------------------------------------------------------------------
/backtrader_rl/strategys.py:
--------------------------------------------------------------------------------
1 | import backtrader as bt
2 | import numpy as np
3 |
4 | class BaseStrategy(bt.Strategy):
5 |
6 | def __init__(self):
7 | self.action = 1
8 | self.reward = 0
9 | self._mapping = {"buy" : 2, "sell" : 0, "hold":1}
10 |
11 | def _set_action_mapping(self,mapping):
12 | self._mapping = mapping
13 |
14 | def _setAction(self,action):
15 | self.action = action
16 |
17 | def next(self):
18 | if len(self._mapping) == 2:
19 | if self.action == self._mapping["buy"]:
20 | # if current position is sell
21 | # then we are reversing the trade
22 | if self.position.size < 0:
23 | self.buy(size = 2 * abs(self.position.size))
24 | elif self.position.size == 0:
25 | self.buy()
26 | elif self.action == self._mapping["sell"]:
27 | # if current position is buy
28 | # then we are closing a trade
29 | if self.position.size > 0:
30 | self.sell(size = 2 * abs(self.position.size))
31 | elif self.position.size == 0:
32 | self.sell()
33 | elif self.action == -1:
34 | pass
35 |
36 | else:
37 |
38 | if self.action == self._mapping["buy"]:
39 | # if current position is sell
40 | # then we are closing a trade
41 | if self.position.size < 0:
42 | self.close()
43 | elif self.position.size == 0:
44 | self.buy()
45 | elif self.action == self._mapping["sell"]:
46 | # if current position is buy
47 | # then we are closing a trade
48 | if self.position.size > 0:
49 | self.close()
50 | elif self.position.size == 0:
51 | self.sell()
52 | elif self.action == -1:
53 | pass
54 |
55 | def _computeReward(self):
56 | try:
57 | reward = self.computeReward()
58 | except:
59 | reward = 0
60 | self.reward = reward
61 | return self.reward
62 |
63 | class PositionBasedStrategy(BaseStrategy):
64 |
65 | def computeReward(self):
66 | if self.position.size == 0:
67 | return 0
68 |
69 | a = self.position.price
70 | b = self.datas[0].close[0]
71 | d = (b-a)/((b+a)/2)
72 | return d * 100 * (self.position.size/abs(self.position.size))
73 |
74 | class returnBasedStrategy(BaseStrategy):
75 |
76 | def start(self):
77 | self.start_value = self.broker.get_value()
78 |
79 | def computeReward(self):
80 |
81 | return (self.broker.get_value()-self.start_value)/self.start_value * 100
82 |
83 | class SharpRatioStrategy(BaseStrategy):
84 |
85 | params = (("riskfree_rate" , 0),)
86 |
87 | def computeReward(self):
88 | trades = list(list(self._trades.copy().values())[0].values())[0]
89 | filterd_trades = list(filter(lambda x : x.isclosed, trades))
90 |
91 | if len(filterd_trades) < 1:
92 | return 0
93 |
94 | ret = list(map(lambda x : ((x.pnl/x.price) * 100) - self.p.riskfree_rate, filterd_trades))
95 |
96 | if np.std(ret) == 0:
97 | return 0
98 |
99 | sharp_ratio = np.mean(ret)/np.std(ret)
100 |
101 | return sharp_ratio
102 |
103 | class SortinoRatioStrategy(BaseStrategy):
104 |
105 | params = (("riskfree_rate" , 0),)
106 |
107 | def computeReward(self):
108 | trades = list(list(self._trades.copy().values())[0].values())[0]
109 | filterd_trades = list(filter(lambda x : x.isclosed, trades))
110 |
111 | if len(filterd_trades) < 1:
112 | return 0
113 |
114 | ret = list(map(lambda x : ((x.pnl/x.price) * 100) - self.p.riskfree_rate, filterd_trades))
115 |
116 |
117 | downside_ret = list(filter(lambda x : x < 0, ret))
118 |
119 | if len(downside_ret) < 1 or np.std(downside_ret) == 0:
120 | return 0
121 |
122 | sharp_ratio = np.mean(ret)/np.std(downside_ret)
123 |
124 | return sharp_ratio
--------------------------------------------------------------------------------
/backtrader_rl/utils.py:
--------------------------------------------------------------------------------
1 | import backtrader as bt
2 |
3 | class minPeriodIndicator(bt.Indicator):
4 | lines = ("state",)
5 | params = (('period',5),)
6 | plotinfo = dict(plot = False,
7 | subplot=False)
8 |
9 | def __init__(self) -> None:
10 | self.addminperiod(self.params.period+1)
11 |
12 | class rewardObserver(bt.Observer):
13 | alias = ("reward",)
14 | lines = ("rewards",)
15 | plotinfo = dict(plot=True,
16 | subplot=True,
17 | plotname = "Reward")
18 |
19 | def next(self):
20 | self.lines.rewards[0] = self._owner.reward
21 |
22 | class cummulativeRewardObserver(bt.Observer):
23 | alias = ("cummulativeReward",)
24 | lines = ("cummulativeRewards",)
25 | plotinfo = dict(plot=True,
26 | subplot=True,
27 | plotname = "Cumulative Reward")
28 |
29 | def next(self):
30 | if len(self.lines.cummulativeRewards) == 1:
31 | self.lines.cummulativeRewards[0] = self._owner.reward
32 | else:
33 | self.lines.cummulativeRewards[0] = self.lines.cummulativeRewards[-1] + self._owner.reward
34 |
35 | class RewardAnalyzer(bt.Analyzer):
36 |
37 | def __init__(self):
38 | self.cummulative_reward = 0
39 | self.reward_history = []
40 |
41 | def next(self):
42 | self.reward_history.append(self.strategy.reward)
43 | self.cummulative_reward += self.strategy.reward
44 |
45 | def get_analysis(self):
46 | return dict(cummulative_reward = self.cummulative_reward, reward_history = self.reward_history)
47 |
48 | class actionObserver(bt.Observer):
49 | alias = ("action",)
50 | lines = ("actions",)
51 |
52 | plotinfo = dict(plot=True,
53 | subplot=True,
54 | plotname = "Action Space",
55 | plotyticks=(0,1,2),
56 | plothlines = (0,1,2))
57 |
58 | def next(self):
59 | self.lines.actions[0] = self._owner.action
60 |
--------------------------------------------------------------------------------
/examples/BNB_USDT_5m.csv:
--------------------------------------------------------------------------------
1 | ,timestamp,open,high,low,close,volume
2 | 0,2020-01-01 00:00:00,13.7071,13.716,13.699,13.699,1604.4
3 | 1,2020-01-01 00:05:00,13.7,13.7102,13.6988,13.7,1782.4
4 | 2,2020-01-01 00:10:00,13.701,13.7128,13.701,13.7104,2854.41
5 | 3,2020-01-01 00:15:00,13.7118,13.7198,13.7006,13.7095,1081.23
6 | 4,2020-01-01 00:20:00,13.7107,13.7123,13.7004,13.7043,891.17
7 | 5,2020-01-01 00:25:00,13.7043,13.708,13.7018,13.7018,1414.77
8 | 6,2020-01-01 00:30:00,13.7019,13.7069,13.7006,13.7069,250.03
9 | 7,2020-01-01 00:35:00,13.7008,13.7051,13.7007,13.7051,150.33
10 | 8,2020-01-01 00:40:00,13.7051,13.7197,13.7035,13.7197,2299.51
11 | 9,2020-01-01 00:45:00,13.7176,13.73,13.7147,13.73,1542.77
12 | 10,2020-01-01 00:50:00,13.7284,13.7494,13.7225,13.7425,635.75
13 | 11,2020-01-01 00:55:00,13.7469,13.7469,13.7122,13.7161,2178.86
14 | 12,2020-01-01 01:00:00,13.7159,13.7194,13.7004,13.701,6609.47
15 | 13,2020-01-01 01:05:00,13.701,13.7105,13.7,13.7079,5018.62
16 | 14,2020-01-01 01:10:00,13.7125,13.7182,13.7,13.7041,4358.32
17 | 15,2020-01-01 01:15:00,13.7051,13.7172,13.7008,13.7027,3445.14
18 | 16,2020-01-01 01:20:00,13.7024,13.7024,13.7,13.7002,8187.39
19 | 17,2020-01-01 01:25:00,13.7023,13.711,13.7,13.7048,5586.67
20 | 18,2020-01-01 01:30:00,13.7038,13.7211,13.7004,13.7053,4481.68
21 | 19,2020-01-01 01:35:00,13.7042,13.7069,13.7,13.7002,3847.14
22 | 20,2020-01-01 01:40:00,13.7002,13.7067,13.7002,13.7035,5518.74
23 | 21,2020-01-01 01:45:00,13.7043,13.7108,13.7019,13.7103,5025.31
24 | 22,2020-01-01 01:50:00,13.7094,13.7153,13.6903,13.6925,7300.01
25 | 23,2020-01-01 01:55:00,13.6917,13.7052,13.6906,13.6981,2638.2
26 | 24,2020-01-01 02:00:00,13.6981,13.7273,13.6953,13.7141,3976.52
27 | 25,2020-01-01 02:05:00,13.7141,13.7315,13.7124,13.7219,4795.39
28 | 26,2020-01-01 02:10:00,13.7204,13.7377,13.7199,13.7337,1869.75
29 | 27,2020-01-01 02:15:00,13.7318,13.7433,13.7182,13.7382,5069.92
30 | 28,2020-01-01 02:20:00,13.7443,13.7546,13.7377,13.7426,3470.39
31 | 29,2020-01-01 02:25:00,13.7438,13.8,13.7428,13.7854,9327.15
32 | 30,2020-01-01 02:30:00,13.7902,13.8,13.7746,13.796,3117.83
33 | 31,2020-01-01 02:35:00,13.7979,13.798,13.784,13.7897,1186.74
34 | 32,2020-01-01 02:40:00,13.7898,13.79,13.7863,13.7878,6068.08
35 | 33,2020-01-01 02:45:00,13.7878,13.79,13.7795,13.7892,3807.32
36 | 34,2020-01-01 02:50:00,13.7885,13.8,13.7885,13.7991,3757.03
37 | 35,2020-01-01 02:55:00,13.7952,13.7998,13.7904,13.7995,7345.13
38 | 36,2020-01-01 03:00:00,13.7984,13.8,13.7906,13.7958,9305.23
39 | 37,2020-01-01 03:05:00,13.7969,13.7969,13.7906,13.7947,7104.65
40 | 38,2020-01-01 03:10:00,13.7947,13.8261,13.7924,13.8028,6464.71
41 | 39,2020-01-01 03:15:00,13.8028,13.8261,13.7992,13.825,7043.85
42 | 40,2020-01-01 03:20:00,13.8234,13.8243,13.8037,13.8216,3405.91
43 | 41,2020-01-01 03:25:00,13.8199,13.8287,13.7993,13.8123,7692.33
44 | 42,2020-01-01 03:30:00,13.811,13.8376,13.811,13.8216,3728.95
45 | 43,2020-01-01 03:35:00,13.8145,13.8293,13.8058,13.8237,6288.38
46 | 44,2020-01-01 03:40:00,13.8255,13.8297,13.8205,13.8287,2941.97
47 | 45,2020-01-01 03:45:00,13.8289,13.8422,13.8241,13.8422,5529.1
48 | 46,2020-01-01 03:50:00,13.8422,13.8449,13.8391,13.8401,3397.21
49 | 47,2020-01-01 03:55:00,13.8401,13.8488,13.839,13.8478,12298.2
50 | 48,2020-01-01 04:00:00,13.8461,13.85,13.8087,13.8203,11904.48
51 | 49,2020-01-01 04:05:00,13.8173,13.8205,13.7881,13.7909,4023.65
52 | 50,2020-01-01 04:10:00,13.7887,13.8002,13.7855,13.7922,1869.77
53 | 51,2020-01-01 04:15:00,13.791,13.8093,13.7895,13.8013,1882.18
54 | 52,2020-01-01 04:20:00,13.8036,13.8235,13.8036,13.8202,775.46
55 | 53,2020-01-01 04:25:00,13.8201,13.822,13.817,13.8209,497.7
56 | 54,2020-01-01 04:30:00,13.8199,13.8364,13.8199,13.835,3523.31
57 | 55,2020-01-01 04:35:00,13.8349,13.8417,13.818,13.8257,2231.97
58 | 56,2020-01-01 04:40:00,13.825,13.8295,13.8089,13.8099,3232.91
59 | 57,2020-01-01 04:45:00,13.8095,13.8173,13.8073,13.8173,1674.06
60 | 58,2020-01-01 04:50:00,13.8173,13.8173,13.8092,13.8118,1916.62
61 | 59,2020-01-01 04:55:00,13.8173,13.8205,13.8101,13.817,2463.86
62 | 60,2020-01-01 05:00:00,13.8157,13.8203,13.81,13.8164,2291.47
63 | 61,2020-01-01 05:05:00,13.8194,13.8203,13.811,13.8193,2711.54
64 | 62,2020-01-01 05:10:00,13.8193,13.8193,13.8003,13.8009,3726.41
65 | 63,2020-01-01 05:15:00,13.8009,13.8079,13.8007,13.8073,3462.59
66 | 64,2020-01-01 05:20:00,13.8073,13.8153,13.8007,13.8053,3220.16
67 | 65,2020-01-01 05:25:00,13.8041,13.812,13.8007,13.8067,3821.46
68 | 66,2020-01-01 05:30:00,13.808,13.8262,13.8059,13.8206,2783.13
69 | 67,2020-01-01 05:35:00,13.8206,13.823,13.8031,13.8144,2762.5
70 | 68,2020-01-01 05:40:00,13.8154,13.8154,13.8048,13.8078,2097.8
71 | 69,2020-01-01 05:45:00,13.807,13.8142,13.805,13.8068,3109.56
72 | 70,2020-01-01 05:50:00,13.8069,13.8072,13.8,13.8,1643.67
73 | 71,2020-01-01 05:55:00,13.8008,13.8008,13.7801,13.7922,2779.26
74 | 72,2020-01-01 06:00:00,13.7968,13.8009,13.7889,13.7999,2836.29
75 | 73,2020-01-01 06:05:00,13.7999,13.8127,13.7985,13.8117,4994.48
76 | 74,2020-01-01 06:10:00,13.8144,13.8144,13.8051,13.806,2388.13
77 | 75,2020-01-01 06:15:00,13.8059,13.8111,13.7997,13.7997,3910.12
78 | 76,2020-01-01 06:20:00,13.7997,13.8069,13.7987,13.799,2313.43
79 | 77,2020-01-01 06:25:00,13.8,13.8,13.7985,13.799,4883.98
80 | 78,2020-01-01 06:30:00,13.799,13.8,13.7986,13.7997,5763.29
81 | 79,2020-01-01 06:35:00,13.7997,13.812,13.7989,13.8078,2398.37
82 | 80,2020-01-01 06:40:00,13.81,13.81,13.804,13.8089,3612.65
83 | 81,2020-01-01 06:45:00,13.804,13.81,13.8039,13.809,4088.02
84 | 82,2020-01-01 06:50:00,13.809,13.8099,13.7991,13.8047,1842.58
85 | 83,2020-01-01 06:55:00,13.8046,13.8089,13.7985,13.8007,3843.69
86 | 84,2020-01-01 07:00:00,13.8007,13.8047,13.7988,13.8047,2753.4
87 | 85,2020-01-01 07:05:00,13.8026,13.8097,13.801,13.806,3365.35
88 | 86,2020-01-01 07:10:00,13.8088,13.8154,13.8078,13.8106,1912.57
89 | 87,2020-01-01 07:15:00,13.812,13.826,13.8119,13.8183,2155.89
90 | 88,2020-01-01 07:20:00,13.8195,13.829,13.8195,13.8279,2864.33
91 | 89,2020-01-01 07:25:00,13.8279,13.829,13.8191,13.828,2419.62
92 | 90,2020-01-01 07:30:00,13.828,13.8329,13.8206,13.8222,1843.24
93 | 91,2020-01-01 07:35:00,13.8224,13.8317,13.8214,13.8295,3123.57
94 | 92,2020-01-01 07:40:00,13.8317,13.8501,13.8303,13.842,1775.63
95 | 93,2020-01-01 07:45:00,13.8386,13.8443,13.827,13.8308,1041.86
96 | 94,2020-01-01 07:50:00,13.8319,13.8351,13.8204,13.8214,837.87
97 | 95,2020-01-01 07:55:00,13.8202,13.8247,13.815,13.8203,1184.4
98 | 96,2020-01-01 08:00:00,13.8217,13.8298,13.8151,13.8222,1617.99
99 | 97,2020-01-01 08:05:00,13.822,13.8222,13.821,13.8213,1632.7
100 | 98,2020-01-01 08:10:00,13.8213,13.8268,13.8147,13.8247,1757.76
101 | 99,2020-01-01 08:15:00,13.8258,13.8327,13.8171,13.8309,1547.41
102 | 100,2020-01-01 08:20:00,13.8309,13.8309,13.8208,13.8296,1199.69
103 | 101,2020-01-01 08:25:00,13.827,13.8321,13.8217,13.8235,1898.11
104 | 102,2020-01-01 08:30:00,13.8235,13.8241,13.8055,13.8078,1954.98
105 | 103,2020-01-01 08:35:00,13.8081,13.8172,13.8055,13.8055,1493.8
106 | 104,2020-01-01 08:40:00,13.8056,13.8056,13.7663,13.7711,7263.84
107 | 105,2020-01-01 08:45:00,13.7669,13.7686,13.745,13.7646,4820.76
108 | 106,2020-01-01 08:50:00,13.7623,13.7623,13.7428,13.75,2595.72
109 | 107,2020-01-01 08:55:00,13.749,13.7621,13.749,13.7608,2575.95
110 | 108,2020-01-01 09:00:00,13.7618,13.7621,13.7336,13.7352,3293.0
111 | 109,2020-01-01 09:05:00,13.7311,13.75,13.7305,13.7418,2545.01
112 | 110,2020-01-01 09:10:00,13.7406,13.7424,13.7293,13.7364,2406.82
113 | 111,2020-01-01 09:15:00,13.7325,13.7362,13.7008,13.7112,3094.87
114 | 112,2020-01-01 09:20:00,13.7123,13.7199,13.7092,13.7153,1818.92
115 | 113,2020-01-01 09:25:00,13.7153,13.7345,13.7076,13.7271,5321.54
116 | 114,2020-01-01 09:30:00,13.7228,13.724,13.6994,13.7112,2839.53
117 | 115,2020-01-01 09:35:00,13.7145,13.7183,13.7027,13.7104,3029.35
118 | 116,2020-01-01 09:40:00,13.717,13.7256,13.7017,13.7098,3753.17
119 | 117,2020-01-01 09:45:00,13.701,13.7163,13.699,13.7163,2358.3
120 | 118,2020-01-01 09:50:00,13.7105,13.7172,13.7067,13.7156,1892.06
121 | 119,2020-01-01 09:55:00,13.7157,13.73,13.7157,13.7299,3067.63
122 | 120,2020-01-01 10:00:00,13.7289,13.7375,13.7176,13.7239,2585.78
123 | 121,2020-01-01 10:05:00,13.7239,13.7361,13.7194,13.7256,1436.78
124 | 122,2020-01-01 10:10:00,13.7242,13.7269,13.7194,13.7224,2413.05
125 | 123,2020-01-01 10:15:00,13.7223,13.7233,13.7157,13.718,3386.96
126 | 124,2020-01-01 10:20:00,13.719,13.7193,13.712,13.7164,4237.19
127 | 125,2020-01-01 10:25:00,13.7184,13.7184,13.696,13.6998,3006.82
128 | 126,2020-01-01 10:30:00,13.6997,13.7235,13.6997,13.7206,2268.48
129 | 127,2020-01-01 10:35:00,13.7253,13.73,13.7194,13.721,1989.42
130 | 128,2020-01-01 10:40:00,13.7251,13.7269,13.7199,13.7256,2396.75
131 | 129,2020-01-01 10:45:00,13.7256,13.7256,13.7191,13.7239,3872.11
132 | 130,2020-01-01 10:50:00,13.7228,13.724,13.7,13.7009,1865.97
133 | 131,2020-01-01 10:55:00,13.6998,13.7053,13.6981,13.7019,1427.06
134 | 132,2020-01-01 11:00:00,13.7013,13.7019,13.6813,13.692,3227.45
135 | 133,2020-01-01 11:05:00,13.6919,13.7142,13.6919,13.7142,2860.93
136 | 134,2020-01-01 11:10:00,13.7145,13.7269,13.7089,13.7234,2405.78
137 | 135,2020-01-01 11:15:00,13.7222,13.728,13.7203,13.7246,2714.44
138 | 136,2020-01-01 11:20:00,13.7228,13.7239,13.7135,13.716,2526.5
139 | 137,2020-01-01 11:25:00,13.716,13.719,13.7118,13.719,2485.18
140 | 138,2020-01-01 11:30:00,13.719,13.7241,13.7081,13.7089,2579.7
141 | 139,2020-01-01 11:35:00,13.7084,13.7187,13.7084,13.7184,3848.13
142 | 140,2020-01-01 11:40:00,13.7173,13.725,13.7096,13.725,2748.72
143 | 141,2020-01-01 11:45:00,13.7228,13.73,13.7227,13.729,4646.03
144 | 142,2020-01-01 11:50:00,13.7243,13.7301,13.7231,13.7288,3038.62
145 | 143,2020-01-01 11:55:00,13.7286,13.7477,13.7275,13.7434,4413.62
146 | 144,2020-01-01 12:00:00,13.7453,13.7738,13.7372,13.7672,6183.76
147 | 145,2020-01-01 12:05:00,13.7663,13.785,13.7656,13.7696,4377.15
148 | 146,2020-01-01 12:10:00,13.7696,13.7792,13.7482,13.7584,6881.18
149 | 147,2020-01-01 12:15:00,13.7592,13.7747,13.7552,13.7635,3914.31
150 | 148,2020-01-01 12:20:00,13.7648,13.7894,13.7633,13.7894,5093.36
151 | 149,2020-01-01 12:25:00,13.7894,13.8125,13.7797,13.7931,8807.57
152 | 150,2020-01-01 12:30:00,13.7931,13.8052,13.771,13.7773,5541.26
153 | 151,2020-01-01 12:35:00,13.7766,13.7785,13.7604,13.7647,3926.3
154 | 152,2020-01-01 12:40:00,13.7636,13.7807,13.763,13.7788,3457.52
155 | 153,2020-01-01 12:45:00,13.7788,13.7954,13.7622,13.7622,5826.88
156 | 154,2020-01-01 12:50:00,13.7605,13.7663,13.7127,13.7148,10468.66
157 | 155,2020-01-01 12:55:00,13.7148,13.7246,13.7079,13.719,2970.8
158 | 156,2020-01-01 13:00:00,13.719,13.7696,13.7168,13.7683,5225.02
159 | 157,2020-01-01 13:05:00,13.7637,13.7684,13.7402,13.75,5424.75
160 | 158,2020-01-01 13:10:00,13.7527,13.7563,13.7404,13.7436,1827.4
161 | 159,2020-01-01 13:15:00,13.7446,13.7647,13.7425,13.7647,4307.01
162 | 160,2020-01-01 13:20:00,13.7657,13.7999,13.763,13.7999,2860.17
163 | 161,2020-01-01 13:25:00,13.7998,13.7998,13.7635,13.7667,5171.8
164 | 162,2020-01-01 13:30:00,13.7669,13.7816,13.7636,13.7774,3690.86
165 | 163,2020-01-01 13:35:00,13.7865,13.7938,13.7749,13.7817,4421.89
166 | 164,2020-01-01 13:40:00,13.7847,13.7873,13.7713,13.7795,2562.41
167 | 165,2020-01-01 13:45:00,13.771,13.7981,13.77,13.7908,3040.26
168 | 166,2020-01-01 13:50:00,13.7848,13.8,13.7758,13.7973,4962.51
169 | 167,2020-01-01 13:55:00,13.7981,13.7999,13.7973,13.7998,3978.15
170 | 168,2020-01-01 14:00:00,13.7985,13.8174,13.7974,13.7988,6719.99
171 | 169,2020-01-01 14:05:00,13.7986,13.8054,13.7918,13.804,3911.31
172 | 170,2020-01-01 14:10:00,13.8041,13.8241,13.8041,13.8208,3675.73
173 | 171,2020-01-01 14:15:00,13.8208,13.8211,13.7983,13.7989,3383.81
174 | 172,2020-01-01 14:20:00,13.7971,13.8137,13.797,13.8137,2685.2
175 | 173,2020-01-01 14:25:00,13.8115,13.8212,13.8103,13.8132,1521.82
176 | 174,2020-01-01 14:30:00,13.8132,13.8262,13.8111,13.8262,1898.72
177 | 175,2020-01-01 14:35:00,13.8262,13.8449,13.8246,13.8262,1764.04
178 | 176,2020-01-01 14:40:00,13.8206,13.8421,13.8206,13.8335,2883.94
179 | 177,2020-01-01 14:45:00,13.8347,13.8347,13.814,13.8277,1928.0
180 | 178,2020-01-01 14:50:00,13.8287,13.829,13.8179,13.8245,1469.07
181 | 179,2020-01-01 14:55:00,13.824,13.8256,13.8112,13.812,770.02
182 | 180,2020-01-01 15:00:00,13.8199,13.8201,13.7921,13.8019,2016.41
183 | 181,2020-01-01 15:05:00,13.8007,13.8007,13.7785,13.7948,2069.8
184 | 182,2020-01-01 15:10:00,13.7948,13.7949,13.7826,13.7906,1524.39
185 | 183,2020-01-01 15:15:00,13.7938,13.8101,13.7919,13.7988,3074.97
186 | 184,2020-01-01 15:20:00,13.809,13.8264,13.8047,13.8164,3698.75
187 | 185,2020-01-01 15:25:00,13.8166,13.8271,13.8102,13.8252,2748.47
188 | 186,2020-01-01 15:30:00,13.8261,13.8494,13.8261,13.8469,3900.09
189 | 187,2020-01-01 15:35:00,13.8478,13.8692,13.8382,13.8424,4191.33
190 | 188,2020-01-01 15:40:00,13.8464,13.85,13.84,13.8401,2225.91
191 | 189,2020-01-01 15:45:00,13.8411,13.8442,13.8335,13.8345,1839.94
192 | 190,2020-01-01 15:50:00,13.8335,13.8359,13.8161,13.8161,3498.32
193 | 191,2020-01-01 15:55:00,13.8164,13.8316,13.814,13.8274,3123.95
194 | 192,2020-01-01 16:00:00,13.8315,13.8397,13.8254,13.83,2281.62
195 | 193,2020-01-01 16:05:00,13.83,13.8344,13.8193,13.8251,2205.85
196 | 194,2020-01-01 16:10:00,13.8239,13.8259,13.8081,13.8149,2298.45
197 | 195,2020-01-01 16:15:00,13.8149,13.818,13.8057,13.8057,1780.6
198 | 196,2020-01-01 16:20:00,13.809,13.8127,13.7786,13.7856,3875.51
199 | 197,2020-01-01 16:25:00,13.7856,13.8151,13.7804,13.813,3672.58
200 | 198,2020-01-01 16:30:00,13.8136,13.8247,13.8107,13.8124,2571.2
201 | 199,2020-01-01 16:35:00,13.815,13.86,13.8033,13.8465,6245.08
202 | 200,2020-01-01 16:40:00,13.8473,13.856,13.8226,13.8239,2726.24
203 | 201,2020-01-01 16:45:00,13.8235,13.8345,13.809,13.8181,3026.68
204 | 202,2020-01-01 16:50:00,13.8118,13.8236,13.8096,13.8134,3393.09
205 | 203,2020-01-01 16:55:00,13.8134,13.8223,13.8126,13.8223,2195.89
206 | 204,2020-01-01 17:00:00,13.8223,13.8301,13.813,13.8174,3000.1
207 | 205,2020-01-01 17:05:00,13.8294,13.8298,13.8095,13.8095,3073.16
208 | 206,2020-01-01 17:10:00,13.8099,13.8241,13.8095,13.8241,838.28
209 | 207,2020-01-01 17:15:00,13.8254,13.8254,13.8003,13.8038,2436.43
210 | 208,2020-01-01 17:20:00,13.8037,13.8146,13.7861,13.801,2653.29
211 | 209,2020-01-01 17:25:00,13.7976,13.8132,13.7961,13.8123,1979.39
212 | 210,2020-01-01 17:30:00,13.8111,13.812,13.8004,13.8091,1625.93
213 | 211,2020-01-01 17:35:00,13.8114,13.8211,13.8048,13.8199,2489.85
214 | 212,2020-01-01 17:40:00,13.8104,13.8262,13.8104,13.8262,2471.43
215 | 213,2020-01-01 17:45:00,13.8262,13.8262,13.8082,13.8261,7120.01
216 | 214,2020-01-01 17:50:00,13.821,13.8475,13.8181,13.8458,2852.21
217 | 215,2020-01-01 17:55:00,13.8462,13.8661,13.8394,13.8522,3083.9
218 |
--------------------------------------------------------------------------------
/examples/downloader.py:
--------------------------------------------------------------------------------
1 | import ccxt
2 | import pandas as pd
3 | import numpy as np
4 | import datetime
5 | import time
6 |
7 | def toDatetime(value):
8 | return datetime.datetime.fromtimestamp(int(value/1000))
9 |
10 | binance = ccxt.binance()
11 |
12 | pair = "BTC/USDT"
13 | timeframe = "1h"
14 | timedelta = datetime.timedelta(hours = 1)
15 | chunk_size = 1000 # max is 1000
16 | normalize = False
17 |
18 | p = pair.split("/")
19 | csv_name = f"examples/{p[0]}_{p[1]}_{timeframe}.csv"
20 |
21 | save_interval = 1000
22 |
23 | start = datetime.datetime(2021,1,1)
24 | end = datetime.datetime(2022,1,1)
25 |
26 | steps = int((end-start)/(timedelta))
27 | num = int(np.ceil(steps/chunk_size)) if end else 10
28 |
29 | t = int(start.timestamp() * 1000)
30 | df = pd.DataFrame(columns = ["timestamp","open","high","low","close","volume"])
31 |
32 | for i in range(num):
33 | candles = np.array(binance.fetch_ohlcv( pair,
34 | timeframe,
35 | limit = chunk_size + 1 if i != num -1 else steps - (num-1) * chunk_size,
36 | since=t))
37 |
38 | if normalize:
39 | for n in range(1,6):
40 | candles[:,n] = (candles[:,n] - candles[:,n].min())/ (candles[:,n].max() - candles[:,n].min())
41 |
42 | temp = pd.DataFrame(candles, columns = ["timestamp","open","high","low","close","volume"])
43 | t = int(temp.tail(1).timestamp) + timedelta.seconds * 1000
44 |
45 | temp.timestamp = list(map(toDatetime,candles[:,0]))
46 |
47 | df = pd.concat([df, temp], ignore_index=True)
48 |
49 | print(f"{i*chunk_size}/{steps}")
50 | df.to_csv(csv_name)
51 |
52 | time.sleep(0.5)
53 |
54 | # TODO clean up and interpolate when time index is missing
55 |
56 | print(f"{steps}/{steps}")
57 |
58 | print("done")
59 | print("Dataframe length {}".format(len(df)))
60 |
61 | df.to_csv(csv_name)
--------------------------------------------------------------------------------
/examples/gym_env_example.py:
--------------------------------------------------------------------------------
1 | from __future__ import (absolute_import, division, print_function,
2 | unicode_literals)
3 |
4 | import pandas as pd
5 |
6 | from random import randint
7 |
8 | import backtrader as bt
9 | from backtrader_rl.strategys import returnBasedStrategy
10 | from backtrader_rl.utils import actionObserver,rewardObserver,cummulativeRewardObserver
11 | from backtrader_rl.engines import BTEngine
12 | from backtrader_rl.adapters.gymAdapter import gymAdapter
13 |
14 | # ================
15 | # Defining constants
16 | # ================
17 |
18 | # the length of data points available to the agent at each step
19 | LOOKBACK = 40
20 |
21 |
22 | # ================
23 | # Preparing test data
24 | # ================
25 |
26 | from pathlib import Path
27 | root = Path().absolute()
28 | file = "examples\BNB_USDT_5m.csv"
29 | df = pd.read_csv(Path(root,file),index_col=0)
30 | df["timestamp"] = pd.to_datetime(df["timestamp"])
31 | df = df.set_index("timestamp",drop=True)
32 | data = bt.feeds.PandasData(dataname=df)
33 |
34 | engine = BTEngine(lookback = LOOKBACK)
35 | engine.broker.set_cash(100)
36 | engine.adddata(data)
37 |
38 | # ================
39 | # Defining the Strategy
40 | # ================
41 |
42 | # the strategy defines the reward schema
43 | # the position based strategy uses the position PNL as a reward at each step
44 | engine.addstrategy(returnBasedStrategy)
45 |
46 | # observeres allow us to peak into the actions taken by the agent over the episode
47 | engine.addobserver(actionObserver)
48 | engine.addobserver(rewardObserver)
49 | engine.addobserver(cummulativeRewardObserver)
50 |
51 |
52 | # default backtrader observers also work just fine
53 | engine.addobserver(bt.observers.BuySell)
54 | engine.addobserver(bt.observers.Broker)
55 | engine.addobserver(bt.observers.Trades)
56 |
57 |
58 | # ================
59 | # use the openai gym environment
60 | # ================
61 |
62 | env = gymAdapter(engine)
63 |
64 | env.reset()
65 | terminated = False
66 |
67 | rewards = []
68 |
69 | while not terminated:
70 | observation, reward, terminated, truncated, info = env.step(randint(0,2))
71 |
72 | env.close()
73 | env.render()
--------------------------------------------------------------------------------
/examples/raylib_example.py:
--------------------------------------------------------------------------------
1 | from __future__ import (absolute_import, division, print_function,
2 | unicode_literals)
3 |
4 | import pandas as pd
5 |
6 | import backtrader as bt
7 | from backtrader_rl.strategys import PositionBasedStrategy as strat
8 | from backtrader_rl.utils import actionObserver,rewardObserver,cummulativeRewardObserver
9 | from backtrader_rl.engines import BTEngine
10 | from backtrader_rl.adapters.tensorforceAdapter import tensorforceAdapter
11 |
12 | from tensorforce.agents import Agent
13 | from tensorforce.environments import Environment
14 | from tensorforce.execution import Runner
15 |
16 | import matplotlib.pyplot as plt
17 | import numpy as np
18 | # ================
19 | # Defining constants
20 | # ================
21 |
22 | # the length of data points available to the agent at each step
23 | LOOKBACK = 40
24 | DATA_LENGTH = 10000
25 |
26 | # ================
27 | # Preparing test data
28 | # ================
29 |
30 | from pathlib import Path
31 | root = Path().absolute()
32 | file = "examples\BTC_USDT_5m.csv"
33 | df = pd.read_csv(Path(root,file),index_col=0)
34 | df["timestamp"] = pd.to_datetime(df["timestamp"])
35 | df = df.set_index("timestamp",drop=True)
36 |
37 | print(df.isnull().values.any())
--------------------------------------------------------------------------------
/examples/tensorforce_example.py:
--------------------------------------------------------------------------------
1 | from __future__ import (absolute_import, division, print_function,
2 | unicode_literals)
3 |
4 | import pandas as pd
5 |
6 | import backtrader as bt
7 | from backtrader_rl.strategys import BaseStrategy
8 | from backtrader_rl.utils import actionObserver,rewardObserver,cummulativeRewardObserver
9 | from backtrader_rl.engines import BTEngine
10 | from backtrader_rl.adapters.tensorforceAdapter import tensorforceAdapter
11 |
12 | from tensorforce.agents import Agent
13 | from tensorforce.environments import Environment
14 | from tensorforce.execution import Runner
15 |
16 | import matplotlib.pyplot as plt
17 | import numpy as np
18 |
19 | # ================
20 | # Reward Shema
21 | # ================
22 |
23 | class RewardSchema(BaseStrategy):
24 |
25 | lastRef = -1
26 | total = []
27 | down = []
28 | lastSortino = 0
29 | lastNonZeroChange = 0
30 | steps_from_change = 0
31 | useLastingReward = True
32 |
33 | def claclSortino(self):
34 |
35 | trades = list(list(self._trades.copy().values())[0].values())[0]
36 | filterd_trades = list(filter(lambda x : x.isclosed, trades))
37 |
38 | if len(filterd_trades) < 1:
39 | return 0
40 |
41 | lastTrade = filterd_trades[-1]
42 |
43 | if self.lastRef != lastTrade.ref:
44 | self.lastRef = lastTrade.ref
45 | ret = (lastTrade.pnlcomm/lastTrade.price)*100
46 | if ret <= 0:
47 | self.down.append(ret)
48 | self.total.append(ret)
49 |
50 | m = np.mean(self.total)
51 |
52 | std = np.std(self.down)
53 |
54 | if std == 0 or type(std) == np.nan:
55 | return 0
56 |
57 |
58 | sr = np.sqrt(len(filterd_trades))
59 |
60 | return (m*sr)/std
61 |
62 | # cal sortiono ratio
63 | def computeReward(self):
64 |
65 | sortino = self.claclSortino()
66 |
67 | change = sortino - self.lastSortino
68 | change = change if not np.isnan(change) else 0
69 |
70 | if change != 0:
71 | self.lastNonZeroChange = change
72 | self.steps_from_change = 0
73 | else:
74 | self.steps_from_change += 1
75 |
76 | self.lastSortino = sortino
77 |
78 | if self.useLastingReward:
79 | return (self.lastNonZeroChange / (self.steps_from_change + 1))
80 |
81 | return change
82 |
83 | # ================
84 | # Defining constants
85 | # ================
86 |
87 | # the length of data points available to the agent at each step
88 | LOOKBACK = 15
89 | DATA_LENGTH = 10000
90 |
91 | # ================
92 | # Preparing test data
93 | # ================
94 |
95 | from pathlib import Path
96 | root = Path().absolute()
97 | file_name = "examples\BTC_USDT_5m.csv"
98 | df = pd.read_csv(Path(root,file_name),index_col=0)
99 | df["timestamp"] = pd.to_datetime(df["timestamp"])
100 | df = df.set_index("timestamp",drop=True)
101 |
102 | # df = df.iloc[500:500+DATA_LENGTH]
103 | # df = df.reset_index()
104 |
105 |
106 | data = bt.feeds.PandasData(dataname=df)
107 |
108 | engine = BTEngine( lookback = LOOKBACK,
109 | state_rows=("ohlcv",),
110 | normalize = True,
111 | canhold = True)
112 |
113 | engine.broker.set_cash(100)
114 | engine.adddata(data)
115 |
116 | # ================
117 | # Defining the Strategy
118 | # ================
119 |
120 | # the strategy defines the reward schema
121 | # the position based strategy uses the position PNL as a reward at each step
122 | engine.addstrategy(RewardSchema)
123 |
124 | # observeres allow us to peak into the actions taken by the agent over the episode
125 | engine.addobserver(actionObserver)
126 | engine.addobserver(rewardObserver)
127 | engine.addobserver(cummulativeRewardObserver)
128 |
129 |
130 | # default backtrader observers also work just fine
131 | engine.addobserver(bt.observers.BuySell)
132 | engine.addobserver(bt.observers.Value)
133 | engine.addobserver(bt.observers.Trades)
134 |
135 | #
136 |
137 | environment = Environment.create(
138 | environment=tensorforceAdapter(engine), max_episode_timesteps=len(df)-LOOKBACK-1
139 | )
140 |
141 | agent = Agent.create(
142 | agent = "ppo" , environment = environment, batch_size = 2
143 | )
144 |
145 | import time
146 |
147 | times = []
148 | for episode in range(5):
149 | # Episode using act and observe
150 | start_time = time.time()
151 | num_steps = 0
152 | states = environment.reset()
153 | terminal = False
154 | sum_rewards = 0.0
155 | num_updates = 0
156 |
157 | while not terminal:
158 | actions = agent.act(states=states)
159 | states, terminal, reward = environment.execute(actions=actions)
160 | num_updates += agent.observe(terminal=terminal, reward=reward)
161 | sum_rewards += reward
162 | num_steps += 1
163 |
164 | print('Episode {}: return= {} updates= {}'.format(episode, sum_rewards, num_updates))
165 |
166 | end_time = time.time()
167 | times.append(end_time-start_time)
168 |
169 | print("total time[s]: ", sum(times))
170 | print("time per episode", np.mean(times))
171 | print("total steps per episode: ", num_steps)
172 | print("seconds per step: ", np.mean(times)/num_steps)
173 |
174 | # Evaluate for 100 episodes
175 | sum_rewards = 0.0
176 | num = 1
177 | for _ in range(num):
178 | states = environment.reset()
179 | internals = agent.initial_internals()
180 | terminal = False
181 | while not terminal:
182 | actions, internals = agent.act(
183 | states=states, internals=internals, independent=True, deterministic=False
184 | )
185 | states, terminal, reward = environment.execute(actions=actions)
186 | sum_rewards += reward
187 |
188 | print('Mean evaluation return:', sum_rewards / num)
189 |
190 | environment.plot()
191 |
192 | # Close agent and environment
193 | agent.close()
194 | environment.close()
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup, find_packages
2 |
3 | setup(
4 | name='backtrader_rl',
5 | version='0.2',
6 | description='Reinforcement Environment for Finacial trading based on the Backtrader infrastructure',
7 | author='Max Lödige',
8 | # author_email='foomail@foo.com',
9 | packages = ["backtrader_rl","backtrader_rl.adapters"], # would be the same as name
10 | install_requires=['backtrader', 'gym', 'tensorforce', 'ray[rllib]'], #external packages acting as dependencies
11 | )
12 |
--------------------------------------------------------------------------------