├── .gitignore
├── .travis.yml
├── LICENSE
├── Makefile
├── README.md
├── backtradercn
├── __init__.py
├── analyzers
│ ├── __init__.py
│ └── drawdown.py
├── datas
│ ├── __init__.py
│ ├── tushare.py
│ └── utils.py
├── libs
│ ├── __init__.py
│ ├── log.py
│ ├── models.py
│ ├── sina.py
│ ├── wechat.py
│ ├── xq_client.py
│ └── xueqiu_trader.py
├── settings
│ ├── __init__.py
│ ├── common.py
│ ├── dev.py
│ ├── prod.py
│ └── test.py
├── strategies
│ ├── __init__.py
│ ├── ma.py
│ └── utils.py
└── tasks.py
├── daily_alert.py
├── data_main.py
├── dev-requirements.txt
├── docs
├── Makefile
├── conf.py
├── content.rst.inc
├── getting_started.rst
├── index.rst
├── make.bat
└── usage.rst
├── frm_main.py
├── issue_template.md
├── pylintrc
├── requirements.txt
├── stock_match.py
├── tests
├── libs
│ └── test_models.py
├── test_datas_tushare.py
├── test_datas_utils.py
├── test_strategies_ma.py
└── test_strategies_utils.py
└── train_main.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 | env/
12 | build/
13 | develop-eggs/
14 | dist/
15 | downloads/
16 | eggs/
17 | .eggs/
18 | lib/
19 | lib64/
20 | parts/
21 | sdist/
22 | var/
23 | wheels/
24 | *.egg-info/
25 | .installed.cfg
26 | *.egg
27 |
28 | # PyInstaller
29 | # Usually these files are written by a python script from a template
30 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
31 | *.manifest
32 | *.spec
33 |
34 | # Installer logs
35 | pip-log.txt
36 | pip-delete-this-directory.txt
37 |
38 | # Unit test / coverage reports
39 | htmlcov/
40 | .tox/
41 | .coverage
42 | .coverage.*
43 | .cache
44 | nosetests.xml
45 | coverage.xml
46 | *.cover
47 | .hypothesis/
48 |
49 | # Translations
50 | *.mo
51 | *.pot
52 |
53 | # Django stuff:
54 | *.log
55 | local_settings.py
56 |
57 | # Flask stuff:
58 | instance/
59 | .webassets-cache
60 |
61 | # Scrapy stuff:
62 | .scrapy
63 |
64 | # Sphinx documentation
65 | docs/_build/
66 |
67 | # PyBuilder
68 | target/
69 |
70 | # Jupyter Notebook
71 | .ipynb_checkpoints
72 |
73 | # pyenv
74 | .python-version
75 |
76 | # celery beat schedule file
77 | celerybeat-schedule
78 |
79 | # SageMath parsed files
80 | *.sage.py
81 |
82 | # dotenv
83 | .env
84 |
85 | # virtualenv
86 | .venv
87 | venv/
88 | ENV/
89 |
90 | # Spyder project settings
91 | .spyderproject
92 | .spyproject
93 |
94 | # Rope project settings
95 | .ropeproject
96 |
97 | # mkdocs documentation
98 | /site
99 |
100 | # mypy
101 | .mypy_cache/
102 | .idea
103 | .DS_Store
104 | backtradercn.tar.gz
105 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: python
2 | python:
3 | - "3.6"
4 |
5 | # email notification
6 | notifications:
7 | email:
8 | recipients:
9 | - 23249735@qq.com
10 | on_success: never # default: change
11 | on_failure: never # default: always
12 |
13 | # services
14 | services:
15 | - mongodb
16 |
17 | # command to install dependencies
18 | install:
19 | - make pip
20 |
21 | # command to run tests coverage report
22 | script:
23 | - make coverage
24 |
25 | after_success:
26 | - codecov
27 | - make webhook
28 |
--------------------------------------------------------------------------------
/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 | {one line to give the program's name and a brief idea of what it does.}
635 | Copyright (C) {year} {name of author}
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 | {project} Copyright (C) {year} {fullname}
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 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | .PHONY: all, pip, install-dev, deploy, test, coverage, webhook, lint, docs, clean
2 |
3 | all: test
4 |
5 | pip:
6 | @echo 'pip install Python modules ...'
7 | @grep -Ev '^#' requirements.txt | awk -F'# ' '{print $$1}' | xargs -n 1 -L 1 pip install
8 |
9 | install-dev:
10 | @pip install -U -r dev-requirements.txt
11 |
12 | deploy: clean
13 | @echo "upload source code to remote server ..."
14 | @rsync -raPH -e ssh --delete ./ gvm-2c8g:/data/web/backtrader-cn
15 | @rsync -raPH -e ssh --delete ./ gvm-4c8g:/root/web/backtrader-cn
16 |
17 | test: clean install-dev
18 | pytest
19 |
20 | coverage: clean install-dev
21 | coverage run --source backtradercn -m pytest -v
22 | coverage report
23 |
24 | webhook:
25 | @echo "trigger webhooks ..."
26 | @curl -X POST http://35.194.246.210/hooks/travis
27 | @curl -X POST http://35.189.182.250/webhook
28 |
29 | lint:
30 | pylint *.py backtradercn
31 |
32 | docs: clean install-dev
33 | $(MAKE) -C docs html
34 |
35 | clean:
36 | @echo "make clean ..."
37 | @find ./ -name '*.pyc' -exec rm -f {} +
38 | @find ./ -name '*.pyo' -exec rm -f {} +
39 | @find ./ -name '*~' -exec rm -f {} +
40 | @find ./ -name '__pycache__' -exec rm -rf {} +
41 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | ## backtrader-cn
2 |
3 | [](https://travis-ci.org/pandalibin/backtrader-cn)
4 | [](https://codecov.io/gh/pandalibin/backtrader-cn)
5 | [](http://backtrader-cn.readthedocs.io/en/latest/?badge=latest)
6 |
7 | ### 快速上手
8 |
9 | python 版本
10 |
11 | $ python --version
12 | Python 3.6.0
13 |
14 | 注:
15 |
16 | - 项目中使用了 `f-string`,所以,需要 `Python 3.6` 以上的版本。
17 | - 可以使用 `pyenv` 安装不同版本的 `Python`,用 `pyenv virtualenv` 创建彼此独立的环境。
18 |
19 | #### 下载代码
20 |
21 | $ git clone https://github.com/pandalibin/backtrader-cn.git
22 |
23 | #### 安装 `mongodb`
24 |
25 | ##### Mac OSX
26 |
27 | 安装项目需要的软件包:
28 |
29 | $ brew install mongodb
30 | $ brew services start mongodb
31 | $ xcode-select --install # 安装`arctic`模块报错提示缺少`limits.h`
32 |
33 | ##### Ubuntu/Debian
34 |
35 | 安装项目需要的软件包:
36 |
37 | $ sudo apt-get install gcc build-essential # arctic
38 | $ sudo apt-get install mongodb
39 |
40 | 安装 Python modules
41 |
42 | > ~~$ pip install -U -r requirements.txt~~
43 |
44 | > `pip install -r requirements.txt` 会并行安装 Python modules。
45 | >
46 | > `tushare` 没有将它安装时依赖的包在 `setup.py` 的 `install_requires` 中做声明,导致如果在 `lxml` 安装之前安装 `tushare` 就会报错。
47 |
48 | $ make pip
49 |
50 | 获取股票数据
51 |
52 | $ python data_main.py
53 |
54 | 计算入场信号
55 |
56 | $ python frm_main.py
57 |
58 | ### 参与项目开发
59 |
60 | #### 安装项目需要的 `Python modules`
61 |
62 | $ make pip
63 |
64 | #### Python code check
65 |
66 | ##### git hooks
67 |
68 | 提交代码前运行 `git-pylint-commit-hook`
69 |
70 | `.git/hooks/pre-commit` 文件内容:
71 |
72 | $ cat .git/hooks/pre-commit
73 | #!/usr/bin/env bash
74 | git-pylint-commit-hook
75 |
76 | 添加执行权限:
77 |
78 | $ chmod +x .git/hooks/pre-commit
79 |
80 | ##### 自己运行 `pylint`
81 |
82 | $ make lint
83 |
84 | ##### 集成 Pylint 到 PyCharm
85 |
86 | [Integrate Pylint with PyCharm](https://docs.pylint.org/en/latest/user_guide/ide-integration.html#integrate-pylint-with-pycharm)
87 |
--------------------------------------------------------------------------------
/backtradercn/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pandalibin/backtrader-cn/1dd18d00d0e8cfbb9d34cc36b1bab7fc70dd0477/backtradercn/__init__.py
--------------------------------------------------------------------------------
/backtradercn/analyzers/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pandalibin/backtrader-cn/1dd18d00d0e8cfbb9d34cc36b1bab7fc70dd0477/backtradercn/analyzers/__init__.py
--------------------------------------------------------------------------------
/backtradercn/analyzers/drawdown.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import (absolute_import, division, print_function,
3 | unicode_literals)
4 |
5 | import backtrader as bt
6 |
7 |
8 | __all__ = ['TimeDrawDown']
9 |
10 |
11 | class TimeDrawDown(bt.TimeFrameAnalyzerBase):
12 | """
13 | This analyzer calculates trading system drawdowns on the chosen
14 | timeframe which can be different from the one used in the underlying data
15 | Params:
16 |
17 | - ``timeframe`` (default: ``None``)
18 | If ``None`` the ``timeframe`` of the 1st data in the system will be
19 | used
20 |
21 | Pass ``TimeFrame.NoTimeFrame`` to consider the entire dataset with no
22 | time constraints
23 |
24 | - ``compression`` (default: ``None``)
25 |
26 | Only used for sub-day timeframes to for example work on an hourly
27 | timeframe by specifying "TimeFrame.Minutes" and 60 as compression
28 |
29 | If ``None`` then the compression of the 1st data of the system will be
30 | used
31 | - *None*
32 |
33 | - ``fund`` (default: ``None``)
34 |
35 | If ``None`` the actual mode of the broker (fundmode - True/False) will
36 | be autodetected to decide if the returns are based on the total net
37 | asset value or on the fund value. See ``set_fundmode`` in the broker
38 | documentation
39 |
40 | Set it to ``True`` or ``False`` for a specific behavior
41 |
42 | Methods:
43 |
44 | - ``get_analysis``
45 |
46 | Returns a dictionary (with . notation support and subdctionaries) with
47 | drawdown stats as values, the following keys/attributes are available:
48 |
49 | - ``drawdown`` - drawdown value in 0.xx %
50 | - ``maxdrawdown`` - drawdown value in monetary units
51 | - ``maxdrawdownperiod`` - drawdown length
52 |
53 | - Those are available during runs as attributes
54 | - ``dd``
55 | - ``maxdd``
56 | - ``maxddlen``
57 | """
58 |
59 | params = (
60 | ('fund', None),
61 | )
62 |
63 | def start(self):
64 | super(TimeDrawDown, self).start()
65 | if self.p.fund is None:
66 | self._fundmode = self.strategy.broker.fundmode
67 | else:
68 | self._fundmode = self.p.fund
69 | self.dd = 0.0
70 | self.maxdd = 0.0
71 | self.maxddlen = 0
72 | self.peak = float('-inf')
73 | self.ddlen = 0
74 | self.tmpmaxdd = 0
75 | self.tmpmaxddlen = 0
76 | self.drawdown_points = []
77 | self.tmpdatetime = None
78 |
79 | def on_dt_over(self):
80 |
81 | if not self._fundmode:
82 | value = self.strategy.broker.getvalue()
83 | else:
84 | value = self.strategy.broker.fundvalue
85 |
86 | # update the maximum seen peak
87 | if value >= self.peak:
88 | self.peak = value
89 | self.ddlen = 0 # start of streak
90 |
91 | if self.tmpdatetime and self.tmpmaxdd and self.tmpmaxddlen:
92 | tmpdrawdown = dict(
93 | datetime=self.tmpdatetime.date(),
94 | drawdown=self.tmpmaxdd,
95 | drawdownlen=self.tmpmaxddlen
96 | )
97 | self.drawdown_points.append(tmpdrawdown)
98 |
99 | self.tmpdatetime_updated = False
100 | self.tmpmaxdd = 0
101 | self.tmpmaxddlen = 0
102 | self.tmpdatetime = None
103 |
104 | # draw down period
105 | else:
106 | # calculate the current drawdown
107 | self.dd = dd = 100.0 * (self.peak - value) / self.peak
108 | self.ddlen += bool(dd) # if peak == value -> dd = 0
109 |
110 | if not self.tmpdatetime_updated:
111 | self.tmpdatetime = self.strategy.datas[0].datetime
112 | self.tmpdatetime_updated = True
113 |
114 | self.tmpmaxdd = max(self.tmpmaxdd, dd)
115 | self.tmpmaxddlen += bool(self.dd)
116 |
117 | # update the maxdrawdown if needed
118 | self.maxdd = max(self.maxdd, dd)
119 | self.maxddlen = max(self.maxddlen, self.ddlen)
120 |
121 | def stop(self):
122 | self.rets['maxdrawdown'] = self.maxdd
123 | self.rets['maxdrawdownperiod'] = self.maxddlen
124 | self.rets['drawdownpoints'] = self.drawdown_points
125 |
--------------------------------------------------------------------------------
/backtradercn/datas/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pandalibin/backtrader-cn/1dd18d00d0e8cfbb9d34cc36b1bab7fc70dd0477/backtradercn/datas/__init__.py
--------------------------------------------------------------------------------
/backtradercn/datas/tushare.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import datetime as dt
3 | import tushare as ts
4 |
5 | import backtradercn.datas.utils as bdu
6 | from backtradercn.settings import settings as conf
7 | from backtradercn.libs.log import get_logger
8 | from backtradercn.libs.models import get_or_create_library
9 |
10 |
11 | logger = get_logger(__name__)
12 |
13 |
14 | class TsHisData(object):
15 | """
16 | Mapping one collection in 'ts_his_lib' library, download and
17 | maintain history data from tushare, and provide other modules with the data.
18 | columns: open, high, close, low, volume
19 | Attributes:
20 | coll_name(string): stock id like '000651' for gree.
21 |
22 | """
23 |
24 | def __init__(self, coll_name):
25 | self._lib_name = conf.CN_STOCK_LIBNAME
26 | self._coll_name = coll_name
27 | self._library = get_or_create_library(self._lib_name)
28 | self._unused_cols = ['price_change', 'p_change', 'ma5', 'ma10', 'ma20',
29 | 'v_ma5', 'v_ma10', 'v_ma20', 'turnover']
30 | self._new_added_colls = []
31 |
32 | @classmethod
33 | def download_one_delta_data(cls, coll_name):
34 | """
35 | Download all the collections' delta data.
36 | :param coll_name: a stock code
37 | :return: None
38 | """
39 | ts_his_data = TsHisData(coll_name)
40 | ts_his_data.download_delta_data()
41 |
42 | @classmethod
43 | def download_all_delta_data(cls, *coll_names):
44 | """
45 | Download all the collections' delta data.
46 | :param coll_names: list of the collections.
47 | :return: None
48 | """
49 | for coll_name in coll_names:
50 | ts_his_data = TsHisData(coll_name)
51 | ts_his_data.download_delta_data()
52 |
53 | def download_delta_data(self):
54 | """
55 | Get yesterday's data and append it to collection,
56 | this method is planned to be executed at each day's 8:30am to update the data.
57 | 1. Connect to arctic and get the library.
58 | 2. Get today's history data from tushare and strip the unused columns.
59 | 3. Store the data to arctic.
60 | :return: None
61 | """
62 |
63 | self._init_coll()
64 |
65 | if self._coll_name in self._new_added_colls:
66 | return
67 |
68 | # 15:00 PM can get today data
69 | # start = latest_date + 1 day
70 | latest_date = self.get_data().index[-1]
71 | start = latest_date + dt.timedelta(days=1)
72 | start = dt.datetime.strftime(start, '%Y-%m-%d')
73 |
74 | his_data = ts.get_hist_data(
75 | code=self._coll_name,
76 | start=start,
77 | retry_count=5
78 | )
79 |
80 | # delta data is empty
81 | if len(his_data) == 0:
82 | logger.info(
83 | f'delta data of stock {self._coll_name} is empty, after {start}')
84 | return
85 |
86 | his_data = bdu.Utils.strip_unused_cols(his_data, *self._unused_cols)
87 |
88 | logger.info(f'got delta data of stock: {self._coll_name}, after {start}')
89 | self._library.append(self._coll_name, his_data)
90 |
91 | def get_data(self):
92 | """
93 | Get all the data of one collection.
94 | :return: data(DataFrame)
95 | """
96 |
97 | data = self._library.read(self._coll_name).data
98 | # parse the date
99 | data.index = data.index.map(bdu.Utils.parse_date)
100 |
101 | return data
102 |
103 | def _init_coll(self):
104 | """
105 | Get all the history data when initiate the library.
106 | 1. Connect to arctic and create the library.
107 | 2. Get all the history data from tushare and strip the unused columns.
108 | 3. Store the data to arctic.
109 | :return: None
110 | """
111 |
112 | # if collection is not initialized
113 | if self._coll_name not in self._library.list_symbols():
114 | self._new_added_colls.append(self._coll_name)
115 | his_data = ts.get_hist_data(code=self._coll_name, retry_count=5).sort_index()
116 | if len(his_data) == 0:
117 | logger.warning(
118 | f'data of stock {self._coll_name} when initiation is empty'
119 | )
120 | return
121 |
122 | his_data = bdu.Utils.strip_unused_cols(his_data, *self._unused_cols)
123 |
124 | logger.debug(f'write history data for stock: {self._coll_name}.')
125 | self._library.write(self._coll_name, his_data)
126 |
--------------------------------------------------------------------------------
/backtradercn/datas/utils.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import datetime
3 |
4 |
5 | class Utils(object):
6 | """
7 | Tools set for datas.
8 | """
9 |
10 | @classmethod
11 | def strip_unused_cols(cls, data, *unused_cols):
12 | """
13 | Strip the unused columns of data frame.
14 | :param data(DataFrame): input data frame.
15 | :param unused_cols(array): unused columns
16 | :return: None
17 | """
18 | for unused_col in unused_cols:
19 | data = data.drop(unused_col, axis=1)
20 |
21 | return data
22 |
23 | @classmethod
24 | def parse_date(cls, date_string):
25 | return datetime.datetime.strptime(date_string, '%Y-%m-%d')
26 |
--------------------------------------------------------------------------------
/backtradercn/libs/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
--------------------------------------------------------------------------------
/backtradercn/libs/log.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import os
3 | import logging
4 | from datetime import datetime
5 | from logging.config import dictConfig
6 | from backtradercn.settings import settings as conf
7 |
8 |
9 | __all__ = ['get_logger']
10 |
11 |
12 | LOG_PATH = os.path.join(
13 | conf.LOG_DIR,
14 | f'{datetime.now().strftime("%Y%m%d-%H%M%S-%f")}.log'
15 | )
16 |
17 | logging_config = dict(
18 | version=1,
19 | formatters={
20 | 'standard': {
21 | 'format':
22 | '%(asctime)s %(name)s:%(funcName)s:%(lineno)d %(levelname)s: %(message)s',
23 | 'default_msec_format': '%s.%03d',
24 | 'converter': 'time.gmtime'
25 | }
26 | },
27 | handlers={
28 | 'console': {
29 | 'class': 'logging.StreamHandler',
30 | 'formatter': 'standard',
31 | 'level': conf.LOG_LEVEL,
32 | 'stream': 'ext://sys.stdout'
33 | },
34 | 'file': {
35 | 'class': 'logging.FileHandler',
36 | 'formatter': 'standard',
37 | 'level': conf.LOG_LEVEL,
38 | 'filename': LOG_PATH,
39 | 'mode': 'a',
40 | }
41 | },
42 | root={
43 | 'handlers': ['console', 'file'],
44 | 'level': conf.LOG_LEVEL,
45 | },
46 | )
47 |
48 | dictConfig(logging_config)
49 |
50 | # replace comma with period
51 | # e.g.: 2010-09-06 22:38:15,292 => 2010-09-06 22:38:15.292
52 | for h in logging.getLogger().handlers:
53 | h.formatter.default_msec_format = '%s.%03d'
54 |
55 |
56 | def get_logger(name=None):
57 | return logging.getLogger(name)
58 |
--------------------------------------------------------------------------------
/backtradercn/libs/models.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import arctic
3 | import pandas as pd
4 | from backtradercn.libs.log import get_logger
5 | from backtradercn.settings import settings as conf
6 |
7 |
8 | logger = get_logger(__name__)
9 |
10 |
11 | def get_store():
12 | """
13 | get Arctic store connection
14 | :return: arctic connection
15 | """
16 |
17 | mongo_host = conf.MONGO_HOST
18 | store = arctic.Arctic(mongo_host)
19 | return store
20 |
21 |
22 | def get_library(lib_name):
23 | """
24 | get library by name
25 | :param lib_name: str, library name
26 | :return: arctic library object
27 | """
28 |
29 | store = get_store()
30 |
31 | lib = None
32 | if lib_name not in store.list_libraries():
33 | logger.debug(f'can not find library: {lib_name}.')
34 | else:
35 | lib = store.get_library(lib_name)
36 |
37 | return lib
38 |
39 |
40 | def create_library(lib_name):
41 | """
42 | create library with name: `lib_name`
43 | :param lib_name: str, library name
44 | :return: arctic library object
45 | """
46 |
47 | store = get_store()
48 | if lib_name not in store.list_libraries():
49 | logger.info(f'initialize library: {lib_name}')
50 | try:
51 | store.initialize_library(lib_name)
52 | except Exception as e:
53 | logger.error(f'initialize library failed: {e}', exc_info=True)
54 | else:
55 | logger.debug(f'library: {lib_name} exist, skip.')
56 |
57 | return store.get_library(lib_name)
58 |
59 |
60 | def get_or_create_library(lib_name):
61 | """
62 | get library by `lib_name`, if not exists, then create it.
63 | :param lib_name: str, library name
64 | :return: arctic library object
65 | """
66 |
67 | lib = get_library(lib_name)
68 | if not lib:
69 | lib = create_library(lib_name)
70 |
71 | return lib
72 |
73 |
74 | def drop_library(lib_name):
75 | """
76 | drop library by name: `lib_name`
77 | :param lib_name: str, library name
78 | :return: None
79 | """
80 |
81 | store = get_store()
82 | if lib_name in store.list_libraries():
83 | logger.info(f'drop library: {lib_name}')
84 | store.delete_library(lib_name)
85 | else:
86 | logger.warning(f'can not find library: {lib_name}')
87 |
88 |
89 | def get_cn_stocks():
90 | """
91 | get all chinese stock ids from arctic library.
92 | :return: list, stock id list. e.g.: ['000651', '601988' ...]
93 | """
94 |
95 | lib = get_library(conf.CN_STOCK_LIBNAME)
96 | return lib.list_symbols()
97 |
98 |
99 | def save_training_params(symbol, params):
100 | """
101 | save training params to library.
102 | :param symbol: str, arctic symbol
103 | :param params: dict, e.g.: {"ma_period_s": 1, "ma_period_l": 2, "stock_id": "600909"}
104 | :return: None
105 | """
106 |
107 | stock_id = params.ma_periods['stock_id']
108 | params_to_save = dict(params=params)
109 | df = pd.DataFrame([params_to_save], columns=params_to_save.keys(), index=[stock_id])
110 |
111 | # write to database
112 | # if library does not exist, create it
113 | lib = get_or_create_library(conf.STRATEGY_PARAMS_LIBNAME)
114 |
115 | if lib.has_symbol(symbol):
116 | logger.debug(
117 | f'symbol: {symbol} already exists, '
118 | f'change the params of stock {stock_id}, '
119 | f'then delete and write symbol: {symbol}.'
120 | )
121 | params_df = lib.read(symbol).data
122 | params_df.loc[stock_id, 'params'] = params
123 | lib.delete(symbol)
124 | lib.write(symbol, params_df)
125 | else:
126 | logger.debug(
127 | f'write the params of stock {stock_id} to symbol: {symbol}'
128 | )
129 | lib.write(symbol, df)
130 |
--------------------------------------------------------------------------------
/backtradercn/libs/sina.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import base64
3 | import json
4 | import random
5 | import re
6 | import string
7 | import time
8 | import urllib.parse
9 | from collections import namedtuple
10 | from datetime import datetime
11 | from enum import IntEnum
12 | from pprint import pprint
13 |
14 | import demjson
15 | import requests
16 | from retrying import retry
17 |
18 | from backtradercn.libs.log import get_logger
19 | from backtradercn.settings import settings as conf
20 |
21 | logger = get_logger(__name__)
22 |
23 |
24 | def enable_debug_requests():
25 | # Enabling debugging at http.client level (requests->urllib3->http.client)
26 | # you will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.
27 | # the only thing missing will be the response.body which is not logged.
28 | from http.client import HTTPConnection
29 | import logging
30 |
31 | HTTPConnection.debuglevel = 1
32 | logger.setLevel(logging.DEBUG)
33 | requests_log = logging.getLogger("requests.packages.urllib3")
34 | requests_log.setLevel(logging.DEBUG)
35 | requests_log.propagate = True
36 |
37 |
38 | # 去掉注释,开启调试模式
39 | # enable_debug_requests()
40 |
41 | def pretty_print(data):
42 | print(json.dumps(data, indent=4, ensure_ascii=False))
43 |
44 |
45 | def pretty_print_namedtuple(namedtuple_obj):
46 | pprint(dict(namedtuple_obj._asdict()))
47 |
48 |
49 | def _json_object_hook(d):
50 | class_name = d.pop('_class_name', 'NamedTuple')
51 | return namedtuple(class_name, d.keys())(*d.values())
52 |
53 |
54 | def json2obj(data):
55 | """将json转换为对象"""
56 | return json.loads(data, object_hook=_json_object_hook)
57 |
58 |
59 | def get_unix_timestamp(with_millisecond=True):
60 | """
61 | get unix时间戳
62 | :param with_millisecond: 是否返回毫秒信息
63 | :return:
64 | """
65 | return int(time.time() * 1000) if with_millisecond else int(time.time())
66 |
67 |
68 | def get_random_string(length=8, digits_only=True):
69 | """
70 | 获取随机字符串长度
71 | :param length:
72 | :param digits_only:
73 | :return:
74 | """
75 | random_str = ""
76 | random_list = string.digits if digits_only else string.ascii_letters + string.digits
77 | for i in range(length):
78 | random_str += random.choice(random_list)
79 | return random_str
80 |
81 |
82 | def extract_stock_info(stock_str):
83 | """解析股票信息
84 | :param stock_str:
85 | :return:
86 | >>> empty_stock_str="var suggestdata_1511245999245="";"
87 | >>> extract_stock_info(empty_stock_str)
88 | []
89 | >>> cn_stock_str='var suggestdata_1511246914696="格力电器,111,000651,sz000651,格力电器,gldq,格力电器,0;格力地产,111,600185,sh600185,格力地产,gldc,格力地产,0";'
90 | >>> extract_stock_info(cn_stock_str)
91 | [{'name': '格力电器', 'type': '111', 'stock_code': '000651', 'symbol': 'sz000651', 'first_letters': 'gldq'}, {'name': '格力地产', 'type': '111', 'stock_code': '600185', 'symbol': 'sh600185', 'first_letters': 'gldc'}]
92 |
93 | >>> us_stock_str='var suggestdata_1511246560937="阿里巴巴,41,baba,alibaba group,阿里巴巴,albb,阿里巴巴,10;阿里那,41,arna,arena pharmaceuticals,阿里那,aln,阿里那,0;阿里阿德,41,aria,ariad pharmaceuticals,阿里阿德,alad,阿里阿德,0";'
94 | >>> extract_stock_info(us_stock_str)
95 | [{'name': '阿里巴巴', 'type': '41', 'stock_code': 'baba', 'symbol': 'alibaba group', 'first_letters': 'albb'}, {'name': '阿里那', 'type': '41', 'stock_code': 'arna', 'symbol': 'arena pharmaceuticals', 'first_letters': 'aln'}, {'name': '阿里阿德', 'type': '41', 'stock_code': 'aria', 'symbol': 'ariad pharmaceuticals', 'first_letters': 'alad'}]
96 | """
97 | stocks = []
98 | match = re.search(r'"(.*)"', stock_str)
99 | if not match:
100 | return stocks
101 | stock_info = match.groups()[0]
102 | str_stocks = stock_info.split(";")
103 | for stock in str_stocks:
104 | search_key, market_type, stock_code, symbol, name, first_letters, _, _ = stock.split(
105 | ',')
106 | stocks.append(
107 | {
108 | "name": name,
109 | "type": market_type,
110 | "stock_code": stock_code,
111 | "symbol": symbol,
112 | "first_letters": first_letters,
113 | }
114 | )
115 | return stocks
116 |
117 |
118 | def jsonp2dict(jsonp):
119 | """
120 | 解析jsonp类型的返回
121 | :param jsonp:
122 | :return:
123 | """
124 |
125 | try:
126 | l_index = jsonp.index("(") + 2
127 | r_index = jsonp.rindex(")") - 1
128 | jsonp_info = jsonp[l_index:r_index]
129 | except ValueError:
130 | logger.error("Input is not in a jsonp format. %s" % jsonp)
131 | return
132 | try:
133 | return demjson.decode(jsonp_info)
134 | except demjson.JSONDecodeError as e:
135 | if jsonp_info == "new Boolean(true)":
136 | return True
137 | elif jsonp_info == "null":
138 | return None
139 | else:
140 | logger.error("解析jsonp返回失败")
141 | logger.error(jsonp)
142 | raise e
143 |
144 |
145 | def check_error(res_dict):
146 | """
147 | 检测返回值中是否包含错误的返回码。
148 | 如果返回码提示有错误,抛出一个异常
149 | """
150 | logger.error(json.dumps(res_dict, ensure_ascii=False))
151 | if "retcode" in res_dict:
152 | if res_dict['retcode'] == 1005:
153 | logger.warning("下单失败, 操作过快,即将重试!")
154 | raise HighFrequencyError("{}: {}".format(res_dict["retcode"], res_dict["msg"]))
155 | raise StockMatchError("{}: {}".format(res_dict["retcode"], res_dict["msg"]))
156 | raise StockMatchError(json.dumps(res_dict))
157 |
158 |
159 | def retry_if_if_high_frequency(exception):
160 | """Return True if we should retry (in this case when it's an IOError), False otherwise"""
161 | return isinstance(exception, HighFrequencyError)
162 |
163 |
164 | class OrderStatus(IntEnum):
165 | # 未成交
166 | undealt = 0
167 | # 成交
168 | dealt = 1
169 | # 已经撤销
170 | canceled = 2
171 |
172 | def __str__(self):
173 | return '%s' % self.value
174 |
175 |
176 | class StockMatchError(Exception):
177 | """异常处理"""
178 |
179 | def __init__(self, message=None):
180 | super(StockMatchError, self).__init__()
181 | self.message = message
182 |
183 |
184 | class LoginFailedError(StockMatchError):
185 | """登录失败"""
186 | pass
187 |
188 |
189 | class HighFrequencyError(StockMatchError):
190 | """操作频率太快"""
191 | pass
192 |
193 |
194 | class StockMatch(object):
195 | """
196 | 新浪模拟炒股
197 | 沪深练习场
198 |
199 | http://jiaoyi.sina.com.cn/jy/index.php
200 | """
201 |
202 | def __init__(self, username, password):
203 | self.session, self.uid = self.login(username, password)
204 |
205 | # 注意: 目前采用的登录方式没有对密码做RSA加密
206 | # 参考
207 | # http://lovenight.github.io/2015/11/23/Python-%E6%A8%A1%E6%8B%9F%E7%99%BB%E5%BD%95%E6%96%B0%E6%B5%AA%E5%BE%AE%E5%8D%9A/
208 | # http://www.jianshu.com/p/816594c83c74
209 | def login(self, username, password):
210 | """
211 | # 新浪微博登录
212 | :param username: 微博手机号
213 | :param password: 微博密码
214 | :return:
215 | """
216 | if username == "" or password == "":
217 | raise StockMatchError("用户名或密码不能为空")
218 | post_data = {
219 | "entry": "finance",
220 | "gateway": "1",
221 | "from": None,
222 | "savestate": "30",
223 | "qrcode_flag": True,
224 | "useticket": "0",
225 | "pagerefer": "http://jiaoyi.sina.com.cn/jy/index.php",
226 | "vsnf": "1",
227 | "su": base64.b64encode(username.encode("utf-8")).decode("utf-8"),
228 | "service": "sso",
229 | "servertime": get_unix_timestamp(False),
230 | "nonce": "RA12UM",
231 | # "pwencode": "rsa2", # 取消掉使用rsa2加密密码
232 | "sp": password,
233 | "sr": "1280*800",
234 | "encoding": "UTF-8",
235 | "cdult": "3",
236 | "domain": "sina.com.cn",
237 | "prelt": "56",
238 | "returntype": "TEXT",
239 | }
240 | session = requests.Session()
241 | session.headers.update(conf.SINA_CONFIG["request_headers"])
242 | res = session.post(conf.SINA_CONFIG["login_url"], data=post_data, params={
243 | "client": "ssologin.js(v1.4.19)",
244 | "_": get_unix_timestamp(),
245 | })
246 | res.encoding = "gb2312"
247 | info = json.loads(res.content)
248 | if info["retcode"] != "0":
249 | logger.error(info["reason"])
250 | raise LoginFailedError(info["reason"])
251 | logger.info("用户%s登录成功" % username)
252 | return session, info['uid']
253 |
254 | @property
255 | def available_fund(self):
256 | """获取当前可用资产"""
257 | return self.get_account_info()['AvailableFund']
258 |
259 | # 返回字段含义参考
260 | # http://n.sinaimg.cn/finance/jiaoyi/js/STP.js
261 | def get_account_info(self):
262 | """
263 | 获取账户基本信息
264 | :return:
265 | {
266 | "sid": 1768615155, # 用户ID
267 | "contest_id": 10000, # 比赛ID
268 | "match_id": "1", # 比赛ID
269 | "StockFund": "500000.000", # 资产
270 | "AvailableFund": "500000.000", # 可用资金
271 | "WarrantFund": "0.000",
272 | "LastTotalFund": "500000.000",
273 | "ctime": "2017-11-20 11:32:03",
274 | "ProfitRatio": "0.000",
275 | "StockProfit": "0.000", # 当日盈亏
276 | "StockCode": "",
277 | "StockName": "",
278 | "max_profit_ratio": "",
279 | "rank": "--", # 比赛排名
280 | "rank_yesterday": "",
281 | "rank_week": "", # 周排行
282 | "rank_month": "", # 月排行
283 | "profit_ratio": "--", # 比赛收益
284 | "profit_ratio_day": "", # 当日收益
285 | "profit_ratio_week": "", # 周收益率
286 | "profit_ratio_month": "", #月收益率
287 | "success_ratio": "",
288 | "frequency": "",
289 | "industry": "",
290 | "stockhold": ""
291 | }
292 | """
293 |
294 | url = "http://jiaoyi.sina.com.cn/api/jsonp_v2.php/jsonp_%s_%s/Account_Service.getAccountinfo" % (
295 | get_unix_timestamp(), get_random_string())
296 |
297 | r = self.session.get(url, params={
298 | "sid": self.uid,
299 | "contest_id": 10000,
300 | })
301 | return jsonp2dict(r.text)
302 |
303 | def _query_orders(self, from_position=0, per_page=10):
304 | """
305 | 查询当日委托
306 | :param from_position: 从第几个开始
307 | :param per_page: 每页返回个数
308 | :return:
309 | """
310 | url = "http://jiaoyi.sina.com.cn/api/jsonp_v2.php/jsonp_%s_%s/V2_CN_Order_Service.getOrder" % (
311 | get_unix_timestamp(), get_random_string())
312 | r = self.session.get(
313 | url, params={
314 | "sid": self.uid,
315 | "cid": 10000,
316 | "sdate": datetime.strftime(datetime.now(), '%Y-%m-%d'),
317 | "edate": "",
318 | "from": from_position, # 请求偏移0
319 | "count": per_page, # 每个返回个数
320 | "sort": 1
321 | })
322 | return jsonp2dict(r.text)
323 |
324 | # fixme:
325 | # 调用新浪接口发现返回的是所有委托,请求时的传递的时间参数没有任何作用
326 | def get_today_orders(self, status=None):
327 | """
328 | 获取当日委托,
329 | :param status: 委托状态: "0": 未成交委托, "1": 成交的委托, "2":已撤销委托,默认返回当天所有委托
330 | :return:
331 | [Order(og_id='120350', contest_id='10000', sid='5175517774', StockCode='sz000651', StockName='格力电器', SellBuy='0', OrderPrice='47.800', DealAmount='100', OrderAmount='100', IfDealt='2', OrderTime='2017-11-21 17:30:10', mtime='2017-11-21 17:33:40')]
332 |
333 | {
334 | "data": [
335 | {
336 | "og_id": "120350", # 委托ID
337 | "contest_id": "10000", # 比赛ID
338 | "sid": "5175517774",
339 | "StockCode": "sz000651",
340 | "StockName": "格力电器",
341 | "SellBuy": "0", # 0表示买入
342 | "OrderPrice": "47.800",
343 | "DealAmount": "100",
344 | "OrderAmount": "100",
345 | "IfDealt": "2", # 成交状态: 0: 未成交,2: 已撤销
346 | "OrderTime": "2017-11-21 17:30:10", # 委托创建时间
347 | "mtime": "2017-11-21 17:33:40"
348 | },
349 | """
350 | if isinstance(status, int):
351 | status = str(status)
352 | from_position = 0
353 | per_page = 10
354 | obj_stocks = []
355 | while True:
356 | json_stocks = self._query_orders(from_position, per_page)
357 | for stock in json_stocks['data']:
358 | stock['_class_name'] = 'Order'
359 | if status is None:
360 | obj_stocks.append(json2obj(json.dumps(stock)))
361 | elif stock['IfDealt'] == status:
362 | obj_stocks.append(json2obj(json.dumps(stock)))
363 | if from_position + per_page >= int(json_stocks['count']):
364 | break
365 | from_position += per_page
366 |
367 | return obj_stocks
368 |
369 | def cancel_all_orders(self):
370 | """
371 | 撤销所有未成交的委托
372 | :return:
373 | """
374 | orders = self.get_today_orders(OrderStatus.undealt)
375 | for order in orders:
376 | self.cancel_order(order)
377 |
378 | def cancel_order(self, order):
379 | """
380 | 撤销委托
381 | :param order:
382 | :return:
383 | """
384 | url = "http://jiaoyi.sina.com.cn/api/jsonp_v2.php/jsonp_%s_%s/Order_Service.cancel" % (
385 | get_unix_timestamp(), get_random_string())
386 | r = self.session.get(url, params={
387 | "sid": self.uid,
388 | "cid": 10000,
389 | "order_id": order.og_id
390 | })
391 | res = jsonp2dict(r.text)
392 | if isinstance(res, bool) and res:
393 | logger.info("撤销委托成功。%s" % str(order))
394 | else:
395 | logger.warning("撤销委托失败, 无效的委托号或重复撤销的委托: %s" % str(order))
396 |
397 | def search_stocks(self, key, market="cn"):
398 | """
399 | 搜索股票信息
400 | :param market: 股票市场: cn: 沪深, us: 美股, hk:港股
401 | :param key: 搜索关键字: 股票名称/代码/拼音
402 | :return:
403 | """
404 | key = urllib.parse.quote(key)
405 | assert market in ["cn", "us", "hk"]
406 | type = "111" # cn
407 | if market == "us":
408 | type = "41"
409 | elif market == "hk":
410 | type = "31"
411 | url = "http://suggest3.sinajs.cn/suggest/type=%s&key=%s&name=suggestdata_%s" % (
412 | type, key, get_unix_timestamp()
413 | )
414 | r = self.session.get(url)
415 | return extract_stock_info(r.text)
416 |
417 | def get_stock_price(self, symbol):
418 | """
419 | 获取股票当前价格
420 | :param symbol:
421 | :return:
422 | """
423 | url = "http://hq.sinajs.cn/list=s_%s" % symbol
424 | r = self.session.get(url)
425 | m = re.search(r'"(.*)"', r.text)
426 | if m and m.groups()[0]:
427 | name, price, _, _, _, _ = m.groups()[0].split(',')
428 | logger.info("股票[%s](%s)当前价格为: %s" % (name, symbol, price))
429 | return price
430 | else:
431 | logger.error("获取股票%s当前价格失败" % symbol)
432 | raise StockMatchError()
433 |
434 | # fixme: 该方法暂时只支持买入A股,不支持操作美股和港股
435 | @retry(wait_random_min=3000, wait_random_max=5000, retry_on_exception=retry_if_if_high_frequency)
436 | def buy(self, stock_code, amount=100, price=None):
437 | """
438 | 买入股票, 该方法调用频率不能太快,调用频率不能高于3s/次
439 | :param stock_code: 股票代码
440 | :param price: 委托买入股票的价格,默认为股票当前价格
441 | :param amount: 买入股票数,必须为100的倍数
442 | :return:
443 | """
444 | assert amount >= 100 and amount % 100 == 0
445 | stocks = self.search_stocks(stock_code, market='cn')
446 | if len(stocks) != 1:
447 | raise StockMatchError("无法确定股票代码%s对应的股票。\r\n%s" % (stock_code, stocks))
448 | stock = stocks[0]
449 | if price is None:
450 | price = self.get_stock_price(stock['symbol'])
451 |
452 | url = "http://jiaoyi.sina.com.cn/api/jsonp_v2.php/jsonp_%s_%s/V2_CN_Order_Service.order" % (
453 | get_unix_timestamp(), get_random_string())
454 |
455 | r = self.session.get(url, params={
456 | "sid": self.uid,
457 | "cid": 10000, # 该参数可能是比赛类型的参数,不同比赛时,该值可能不同
458 | "symbol": stock['symbol'],
459 | "price": price,
460 | "amount": amount,
461 | "type": "buy",
462 | "toweibo": 0,
463 | "enc": "utf8"
464 | })
465 | logger.info("准备买入股票[%s](%s), 买入价格: %s, 买入数量: %s" % (
466 | (stock['name'], stock['symbol'], price, amount)
467 | ))
468 | res = jsonp2dict(r.text)
469 | if isinstance(res, bool) and res:
470 | logger.info("下单成功")
471 | elif isinstance(res, dict):
472 | check_error(res)
473 | else:
474 | logger.error("未处理的返回情况: %s" % r.text)
475 |
476 | def _query_stock_hold(self, from_position=0, per_page=10):
477 | url = "http://jiaoyi.sina.com.cn/api/jsonp_v2.php/jsonp_%s_%s/V2_CN_Stockhold_Service.getStockhold" % (
478 | get_unix_timestamp(), get_random_string())
479 | r = self.session.get(url, params={
480 | "sid": self.uid,
481 | "cid": 10000,
482 | "count": per_page,
483 | "from": from_position
484 | })
485 | return jsonp2dict(r.text)
486 |
487 | def get_stock_hold(self):
488 | """
489 | 获取当前持仓
490 |
491 | {
492 | "data": [
493 | {
494 | "sg_id": "117989",
495 | "contest_id": "10000",
496 | "sid": "1768615155",
497 | "zs_price": null,
498 | "zy_price": null,
499 | "HoldPercent": 0.6, # 仓位
500 | "StockCode": "sz000001",
501 | "StockName": "平安银行",
502 | "StockAmount": "200", # 当前持股
503 | "AvailSell": "0", # 可用股数
504 | "TodayBuy": "200",
505 | "TodaySell": "0",
506 | "T4AvailSell": "0",
507 | "T3AvailSell": "0",
508 | "T2AvailSell": "0",
509 | "T1AvailSell": "0",
510 | "CurrentValue": null,
511 | "cost": "14.920", # 持仓成本
512 | "StartDate": "2017-11-22 10:24:36",
513 | "EndDate": "0000-00-00 00:00:00",
514 | "mtime": "0000-00-00 00:00:00",
515 | "CostFund": "2983.980", # 持仓花费金额
516 | "newcost": 14.99, # 最新价格
517 | "dealvalue": "2983.980",
518 | "newvalue": 2998, # 持股市值
519 | "profit": 14, # 浮动盈亏
520 | "profitRate": 0.47 # 盈亏比例
521 | }
522 | ],
523 | "count": "1",
524 | "status": "2"
525 | }
526 | """
527 | from_position = 0
528 | per_page = 10
529 | obj_stocks = []
530 | while True:
531 | json_stocks = self._query_stock_hold(from_position, per_page)
532 | for stock in json_stocks['data']:
533 | obj_stocks.append(json2obj(json.dumps(stock)))
534 | if from_position + per_page >= int(json_stocks['count']):
535 | break
536 | from_position += per_page
537 |
538 | return obj_stocks
539 |
540 | def sell(self, stock_code):
541 | """
542 | 卖出股票
543 | :param stock_code:
544 | :return:
545 | """
546 | pass
547 |
548 |
549 | if __name__ == "__main__":
550 | user = StockMatch(conf.SINA_CONFIG["username"], conf.SINA_CONFIG["password"])
551 | # stock_code = '000001'
552 | # user.buy(stock_code)
553 | # pretty_print(user.get_stock_hold())
554 | # print(len(user.get_today_orders()))
555 | # print(len(user.get_stock_hold()))
556 | for order in user.get_today_orders(status=OrderStatus.undealt):
557 | pretty_print_namedtuple(order)
558 |
--------------------------------------------------------------------------------
/backtradercn/libs/wechat.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from backtradercn.settings import settings as conf
3 | from backtradercn.libs.log import get_logger
4 | from werobot.client import Client
5 |
6 |
7 | logger = get_logger(__name__)
8 |
9 |
10 | class WeChatClient(Client):
11 | def send_all_text_message(self, content):
12 | '''
13 | 群发文本消息。
14 |
15 | :param content: 消息正文
16 | :return: 返回的 JSON 数据包
17 | '''
18 | return self.post(
19 | url='https://api.weixin.qq.com/cgi-bin/message/mass/sendall',
20 | data={
21 | 'filter': {
22 | 'is_to_all': True,
23 | },
24 | 'text': {
25 | 'content': content,
26 | },
27 | 'msgtype': 'text'
28 | }
29 | )
30 |
31 |
32 | if __name__ == '__main__':
33 | client = WeChatClient({
34 | 'APP_ID': conf.WECHAT_APP_ID,
35 | 'APP_SECRET': conf.WECHAT_APP_SECRET,
36 | })
37 | response = client.send_all_text_message('just test')
38 | logger.debug(response)
39 |
--------------------------------------------------------------------------------
/backtradercn/libs/xq_client.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import json
3 | import os
4 | from json import JSONDecodeError
5 |
6 | import re
7 | import requests
8 |
9 | from easytrader.log import log
10 | from easytrader.webtrader import NotLoginError, TradeError
11 | from easytrader.webtrader import WebTrader
12 | import easytrader.xqtrader
13 |
14 |
15 | class XueQiuClient(WebTrader):
16 | config_path = os.path.dirname(easytrader.xqtrader.__file__) + '/config/xq.json'
17 |
18 | def __init__(self, **kwargs):
19 | super(XueQiuClient, self).__init__()
20 | headers = {
21 | 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:32.0) Gecko/20100101 Firefox/32.0',
22 | 'Host': 'xueqiu.com',
23 | 'Pragma': 'no-cache',
24 | 'Connection': 'keep-alive',
25 | 'Accept': '*/*',
26 | 'Accept-Encoding': 'gzip,deflate,sdch',
27 | 'Cache-Control': 'no-cache',
28 | 'Referer': 'http://xueqiu.com/P/ZH003694',
29 | 'X-Requested-With': 'XMLHttpRequest',
30 | 'Accept-Language': 'zh-CN,zh;q=0.8'
31 | }
32 | self.session = requests.Session()
33 | self.session.headers.update(headers)
34 | self.account_config = None
35 | self.config.update({
36 | "create_cubes_url": "https://xueqiu.com/cubes/create.json",
37 | "get_token_url": "https://xueqiu.com/service/csrf",
38 | "get_cubes_list": "https://xueqiu.com/v4/stock/portfolio/stocks.json",
39 | "get_cubes_detail": "https://xueqiu.com/cubes/quote.json",
40 | })
41 |
42 | def autologin(self, **kwargs):
43 | """
44 | 重写自动登录方法
45 | 避免重试导致的帐号封停
46 | :return:
47 | """
48 | self.login()
49 |
50 | def login(self, throw=False):
51 | """
52 | 登录
53 | :param throw:
54 | :return:
55 | """
56 | login_status, result = self.post_login_data()
57 | if login_status is False and throw:
58 | raise NotLoginError(result)
59 | log.debug('login status: %s' % result)
60 | return login_status
61 |
62 | def _prepare_account(self, user='', password='', **kwargs):
63 | """
64 | 转换参数到登录所需的字典格式
65 | :param user: 雪球邮箱(邮箱手机二选一)
66 | :param password: 雪球密码
67 | :param account: 雪球手机号(邮箱手机二选一)
68 | :param portfolio_market: 交易市场, 可选['cn', 'us', 'hk'] 默认 'cn'
69 | :return:
70 | """
71 | if 'portfolio_market' not in kwargs:
72 | kwargs['portfolio_market'] = 'cn'
73 | if 'account' not in kwargs:
74 | kwargs['account'] = ''
75 | self.account_config = {
76 | 'username': user,
77 | 'account': kwargs['account'],
78 | 'password': password,
79 | 'portfolio_market': kwargs['portfolio_market']
80 | }
81 |
82 | def post_login_data(self):
83 | login_post_data = {
84 | 'username': self.account_config.get('username', ''),
85 | 'areacode': '86',
86 | 'telephone': self.account_config['account'],
87 | 'remember_me': '0',
88 | 'password': self.account_config['password']
89 | }
90 | login_response = self.session.post(self.config['login_api'], data=login_post_data)
91 | login_status = login_response.json()
92 | if 'error_description' in login_status:
93 | return False, login_status['error_description']
94 | return True, "SUCCESS"
95 |
96 | def __search_stock_info(self, code):
97 | """
98 | 通过雪球的接口获取股票详细信息
99 | :param code: 股票代码 000001
100 |
101 | :return: 查询到的股票
102 | {"code":"SZ000651","name":"格力电器","enName":null,"hasexist":null,"flag":1,"type":null,"current":45.46,"chg":0.6,"percent":"1.34","stock_id":1001306,"ind_id":100007,"ind_name":"家用电器","ind_color":"#82b952","textname":"格力电器(SZ000651)","segment_name":"家用电器","weight":30,"url":"/S/SZ000651","proactive":true,"price":"45.46"}
103 | ** flag : 未上市(0)、正常(1)、停牌(2)、涨跌停(3)、退市(4)
104 | """
105 | data = {
106 | 'code': str(code),
107 | 'size': '300',
108 | 'key': '47bce5c74f',
109 | 'market': self.account_config['portfolio_market'],
110 | }
111 | r = self.session.get(self.config['search_stock_url'], params=data)
112 | stocks = json.loads(r.text)
113 | stocks = stocks['stocks']
114 | stock = None
115 | if len(stocks) > 0:
116 | stock = stocks[0]
117 | return stock
118 |
119 | def __get_create_cube_token(self):
120 | """获取创建组合时需要的token信息
121 | :return: token
122 | """
123 | response = self.session.get(self.config["get_token_url"], params={
124 | "api": "/cubes/create.json"
125 | })
126 | try:
127 | token_response = json.loads(response.text)
128 | except JSONDecodeError:
129 | raise TradeError("解析创建组合的token信息失败: %s" % response.text)
130 | if 'token' not in token_response:
131 | raise TradeError("获取创建组合的token信息失败: %s" % response.text)
132 | return token_response['token']
133 |
134 | @staticmethod
135 | def get_cube_name(cube_prefix, stock_code):
136 | return "%s%s" % (cube_prefix, stock_code)
137 |
138 | def create_cube(self, stock_code, weight, cube_prefix="SC", description="", market='cn'):
139 | """创建组合, 并设置股票初始买入的百分比
140 | ** 组合名称默认格式为前缀 + 股票代码
141 | :param stock_code: str 股票代码
142 | :param weight: int 初始仓位的百分比, 0 - 100 之间的整数
143 | :param cube_prefix: 组合名字的前缀
144 | :param description: 组合描述信息
145 | :param market: 市场范围, cn: 沪深, us: 美股, hk: 港股
146 | :return: (是否创建成功, 组合代码, 组合名称)
147 | """
148 | cube_name = self.get_cube_name(cube_prefix, stock_code)
149 | stock = self.__search_stock_info(stock_code)
150 | if stock is None:
151 | raise TradeError(u"没有查询要操作的股票信息")
152 | if stock['flag'] != 1:
153 | raise TradeError(u"未上市、停牌、涨跌停、退市的股票无法操作。")
154 | holdings = [
155 | {
156 | "code": stock['code'],
157 | "name": stock['name'],
158 | "enName": stock['enName'],
159 | "hasexist": stock['hasexist'],
160 | "flag": stock['flag'],
161 | "type": stock['type'],
162 | "current": stock['current'],
163 | "chg": stock['chg'],
164 | "percent": str(stock['percent']),
165 | "stock_id": stock['stock_id'],
166 | "ind_id": stock['ind_id'],
167 | "ind_name": stock['ind_name'],
168 | "ind_color": stock['ind_color'],
169 | "textname": "%s(%s)" % (stock['name'], stock['code']),
170 | "segment_name": stock['ind_name'],
171 | "weight": weight,
172 | "url": "/S/" + stock['code'],
173 | "proactive": True,
174 | "price": str(stock['current'])
175 | }
176 | ]
177 |
178 | create_cube_data = {
179 | "name": cube_name,
180 | "cash": 100 - weight,
181 | "description": description,
182 | "market": market,
183 | "holdings": json.dumps(holdings),
184 | "session_token": self.__get_create_cube_token(),
185 | }
186 | try:
187 | cube_res = self.session.post(self.config['create_cubes_url'], data=create_cube_data)
188 | except Exception as e:
189 | log.warn('创建组合%s失败: %s ' % (cube_name, e))
190 | return (False, None, None)
191 | else:
192 | log.debug('创建组合%s: 持仓比例%d' % (cube_name, weight))
193 | cube_res_status = json.loads(cube_res.text)
194 | if 'error_description' in cube_res_status.keys() and cube_res.status_code != 200:
195 | log.error('创建组合错误: %s, error_no: %s, error_info: %s' % (
196 | cube_res_status['error_description'],
197 | cube_res_status['error_code'],
198 | cube_res_status['error_description'],
199 | ))
200 | if cube_res_status['error_code'] == '20912':
201 | log.error("组合名称: %s 不符合要求, 请尝试换一个组合名称,组合名称只能是中文,英文,数字(测试时发现某些情况下可以包含下划线)" % cube_name)
202 | return (False, None, None)
203 | log.debug('创建组合成功 %s: 持仓比例%d, 创建信息: \n%s' % (
204 | cube_name, weight, json.dumps(cube_res_status, ensure_ascii=False, indent=4)))
205 | return (True, cube_res_status['symbol'], cube_name)
206 |
207 | def get_cubes_list(self, type=4):
208 | """获取组合详情,默认获取自选组合
209 | :param type: 组合名字的前缀, 1: 全部组合。 4: 我的组合。 5: 只看沪深组合。 6: 只看美股。7: 只看港股
210 | :return: 组合列表
211 | """
212 | response = self.session.get(self.config['get_cubes_list'], params={
213 | "category": 1,
214 | "type": type
215 | })
216 | try:
217 | cubes_response = json.loads(response.text)
218 | except JSONDecodeError:
219 | log.warning(response.text)
220 | raise TradeError("解析组合列表失败: %s" % response.text)
221 | if 'stocks' not in cubes_response:
222 | log.warning(cubes_response)
223 | raise TradeError("获取组合信息失败: %s" % response.text)
224 | cubes_code_list = [cube['code'] for cube in cubes_response['stocks']]
225 |
226 | response = self.session.get(self.config['get_cubes_detail'], params={
227 | "code": ','.join(cubes_code_list),
228 | "return_hasexist": False,
229 | })
230 | try:
231 | cubes_detail_response = json.loads(response.text)
232 | except JSONDecodeError:
233 | raise TradeError("解析组合详情失败: %s" % response.text)
234 | if 'stocks' not in cubes_response:
235 | raise TradeError("获取组合信息失败: %s" % response.text)
236 | return cubes_detail_response
237 |
238 | def get_portfolio_info(self, portfolio_code):
239 | """
240 | 获取组合信息
241 | :return: 字典
242 | """
243 | url = self.config['portfolio_url'] + portfolio_code
244 | html = self.__get_html(url)
245 | match_info = re.search(r'(?<=SNB.cubeInfo = ).*(?=;\n)', html)
246 | if match_info is None:
247 | raise Exception('cant get portfolio info, portfolio html : {}'.format(html))
248 | try:
249 | portfolio_info = json.loads(match_info.group())
250 | except Exception as e:
251 | raise Exception('get portfolio info error: {}'.format(e))
252 | return portfolio_info
253 |
254 | def __get_html(self, url):
255 | return self.session.get(url).text
256 |
257 | if __name__ == '__main__':
258 | from backtradercn.settings import settings as conf
259 |
260 | client = XueQiuClient()
261 | client.prepare(account=conf.XQ_ACCOUNT, password=conf.XQ_PASSWORD, portfolio_market=conf.XQ_PORTFOLIO_MARKET)
262 | # 创建股票代码为000651的组合
263 | response = client.create_cube(stock_code="000651", weight=5, cube_prefix=conf.XQ_CUBES_PREFIX)
264 | print(response)
265 | # 获取自定义组合信息
266 | cubes_list = client.get_cubes_list()
267 | print(cubes_list)
268 |
--------------------------------------------------------------------------------
/backtradercn/libs/xueqiu_trader.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import easytrader
3 | from easytrader import log
4 | from backtradercn.settings import settings as conf
5 | from backtradercn.libs.xq_client import XueQiuClient
6 | from easytrader.exceptions import TradeError
7 |
8 |
9 | class XueQiuTrader(object):
10 | """
11 | 雪球组合操作类,适用于每个组合只能包含一直股票的买入和卖出操作
12 | """
13 |
14 | def __init__(self, xq_account, xq_password, xq_portfolio_market, xq_cube_prefix):
15 | self.xq_account = xq_account
16 | self.xq_password = xq_password
17 | self.xq_portfolio_market = xq_portfolio_market
18 | self.cube_prefix = xq_cube_prefix
19 |
20 | @property
21 | def client(self):
22 | """获取操作雪球组合的客户端
23 | :return:
24 | """
25 | if not hasattr(self, '_client'):
26 | self._client = XueQiuClient()
27 | self._client.prepare(
28 | account=self.xq_account,
29 | password=self.xq_password,
30 | portfolio_market=self.xq_portfolio_market
31 | )
32 | return self._client
33 |
34 | def get_current_weight(self, symbol):
35 | """获取组合股票当前百分比
36 | :param symbol: 组合编码
37 | :return:
38 | """
39 | portfolio_info = self.client.get_portfolio_info(symbol)
40 | position = portfolio_info['view_rebalancing'] # 仓位结构
41 | stocks = position['holdings'] # 持仓股票
42 | # 当前股票持仓为0%
43 | if len(stocks) == 0:
44 | return 0
45 | if len(stocks) > 1:
46 | raise TradeError("当前组合%s包含%d支股票,不适合当前的策略" % (symbol, len(stocks)))
47 | return stocks[0]['weight']
48 |
49 | def adjust_weight(self, symbol, stock_code, weight):
50 | """调整组合中股票的百分比
51 | :param symbol: 组合编码
52 | :param stock_code: 股票编码
53 | :param weight: 股票百分比
54 | :return:
55 | """
56 | user = easytrader.use('xq')
57 | user.prepare(
58 | account=self.xq_account,
59 | password=self.xq_password,
60 | portfolio_market=self.xq_portfolio_market,
61 | portfolio_code=symbol
62 | )
63 | user.adjust_weight(stock_code, weight)
64 |
65 | def buy(self, stock_code, weight=conf.XQ_DEFAULT_BUY_WEIGHT):
66 | """买入股票,默认一次买入指定的百分比数
67 | :param stock_code: 股票编码
68 | :param weight: 股票百分比
69 | :return:
70 | """
71 | symbol = self.is_cube_exist(stock_code)
72 | if symbol:
73 | current_weight = self.get_current_weight(symbol)
74 | if current_weight == 100:
75 | log.info("已经满仓,无法再买入股票%s" % stock_code)
76 | return
77 | new_weight = current_weight + weight
78 | if new_weight > 100:
79 | log.info("买入后, 股票%s的百分数超出100, 按照100买入" % stock_code)
80 | new_weight = 100
81 | self.adjust_weight(symbol, stock_code, new_weight)
82 | log.info("组合%s, 股票%s持仓由%s调整到%s" % (symbol, stock_code, current_weight, new_weight))
83 | else:
84 | created_success, symbol, cube_name = self.client.create_cube(stock_code, weight,
85 | cube_prefix=self.cube_prefix)
86 | if created_success:
87 | log.info("建仓成功。股票: %s, 组合名字: %s。组合代码: %s。" % (stock_code, cube_name, symbol))
88 | else:
89 | log.info("建仓失败。股票: %s" % stock_code)
90 |
91 | def is_cube_exist(self, stock_code):
92 | """检查满足组合前缀和股票代码的组合是否存在
93 | :param stock_code: 股票编码
94 | """
95 | cube_name = XueQiuClient.get_cube_name(self.cube_prefix, stock_code)
96 | cubes_list = self.client.get_cubes_list()
97 | for symbol, detail in cubes_list.items():
98 | if detail['name'] == cube_name:
99 | return symbol
100 |
101 | def sell(self, stock_code):
102 | """清仓
103 | :param stock_code: 股票编码
104 | """
105 | symbol = self.is_cube_exist(stock_code)
106 | if not symbol:
107 | log.info("当前没有包含股票%s的组合, 不需要卖出" % stock_code)
108 | return
109 | current_weight = self.get_current_weight(symbol)
110 | if current_weight == 0:
111 | log.info("组合%s, 股票%s已经处于空仓状态,不需要卖出" % (symbol, stock_code))
112 | return
113 | self.adjust_weight(symbol, stock_code, 0)
114 | log.info("组合%s, 股票%s清仓" % (symbol, stock_code))
115 |
116 |
117 | if __name__ == '__main__':
118 | trader = XueQiuTrader(
119 | xq_account=conf.XQ_ACCOUNT,
120 | xq_password=conf.XQ_PASSWORD,
121 | xq_portfolio_market=conf.XQ_PORTFOLIO_MARKET,
122 | xq_cube_prefix=conf.XQ_CUBES_PREFIX,
123 | )
124 | trader.buy('601088')
125 | trader.sell('601088')
126 |
--------------------------------------------------------------------------------
/backtradercn/settings/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import os
3 | import logging
4 |
5 | from backtradercn.settings import dev
6 | from backtradercn.settings import test
7 | from backtradercn.settings import prod
8 |
9 |
10 | __all_ = ['settings']
11 |
12 |
13 | settings = None
14 |
15 | if os.environ.get('DEPLOY_ENV') == 'dev':
16 | settings = dev
17 | elif os.environ.get('DEPLOY_ENV') == 'test':
18 | settings = test
19 | elif os.environ.get('DEPLOY_ENV') == 'prod':
20 | settings = prod
21 | else:
22 | # raise Exception('You must set the environment variable: `DEPLOY_ENV`'
23 | # 'to one of ["dev", "test", "prod"]')
24 |
25 | log_format = '%(name)s:%(lineno)d %(levelname)s: %(message)s'
26 | logging.basicConfig(format=log_format)
27 | logger = logging.getLogger(__name__)
28 | logger.warning(
29 | 'Do not set the environment variable: `DEPLOY_ENV`, '
30 | 'using the default value: `dev`.'
31 | )
32 | settings = dev
33 |
--------------------------------------------------------------------------------
/backtradercn/settings/common.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import os
3 |
4 | PROJECT_NAME = 'backtradercn'
5 |
6 | # log setting
7 | LOG_DIR = '/tmp/'
8 | LOG_LEVEL = os.getenv('LOG_LEVEL', 'DEBUG')
9 |
10 | # database setting
11 | MONGO_HOST = 'localhost'
12 | CN_STOCK_LIBNAME = 'ts_his_lib'
13 | DAILY_STOCK_ALERT_LIBNAME = 'daily_stock_alert'
14 | STRATEGY_PARAMS_LIBNAME = 'strategy_params'
15 | STRATEGY_PARAMS_MA_SYMBOL = 'ma_trend'
16 |
17 | # wechat
18 | WECHAT_APP_ID = 'wx5e8e3c4779887f32'
19 | WECHAT_APP_SECRET = 'd4624c36b6795d1d99dcf0547af5443d'
20 |
21 | # xueqiu account
22 | XQ_ACCOUNT = os.getenv('XQ_ACCOUNT', '18628391725')
23 | XQ_PASSWORD = os.getenv('XQ_PASSWORD', 'gupiao999')
24 | XQ_PORTFOLIO_MARKET = os.getenv('XQ_PORTFOLIO_MARKET', 'cn')
25 | # 默认的组合前缀,组合名称格式为 组合前缀 + 股票代码
26 | # 组合名字
27 | XQ_CUBES_PREFIX = 'SC'
28 | # 默认创建组合时股票的初始百分数
29 | XQ_DEFAULT_BUY_WEIGHT = 5
30 |
31 | SINA_CONFIG = {
32 | "username": os.getenv('WEIBO_USERNAME', '18628391725'),
33 | "password": os.getenv('WEIBO_PASSWORD', 'Gupiao888'),
34 | "request_headers": {
35 | 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36',
36 | 'Pragma': 'no-cache',
37 | 'Connection': 'keep-alive',
38 | 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
39 | 'Accept-Encoding': 'gzip, deflate',
40 | 'Cache-Control': 'no-cache',
41 | 'Referer': 'http://jiaoyi.sina.com.cn/jy/index.php',
42 | 'Accept-Language': 'zh-CN,zh;q=0.8'
43 | },
44 | "login_url": "https://login.sina.com.cn/sso/login.php",
45 | }
46 |
--------------------------------------------------------------------------------
/backtradercn/settings/dev.py:
--------------------------------------------------------------------------------
1 | # pylint: disable=wildcard-import, unused-wildcard-import
2 | # -*- coding: utf-8 -*-
3 | from .common import *
4 |
--------------------------------------------------------------------------------
/backtradercn/settings/prod.py:
--------------------------------------------------------------------------------
1 | # pylint: disable=wildcard-import, unused-wildcard-import
2 | # -*- coding: utf-8 -*-
3 | from .common import *
4 |
--------------------------------------------------------------------------------
/backtradercn/settings/test.py:
--------------------------------------------------------------------------------
1 | # pylint: disable=wildcard-import, unused-wildcard-import
2 | # -*- coding: utf-8 -*-
3 | from .common import *
4 |
--------------------------------------------------------------------------------
/backtradercn/strategies/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/pandalibin/backtrader-cn/1dd18d00d0e8cfbb9d34cc36b1bab7fc70dd0477/backtradercn/strategies/__init__.py
--------------------------------------------------------------------------------
/backtradercn/strategies/ma.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import datetime as dt
3 | import math
4 |
5 | import backtrader as bt
6 |
7 | import backtradercn.analyzers.drawdown as bad
8 | import backtradercn.datas.tushare as bdt
9 | import backtradercn.strategies.utils as bsu
10 | from backtradercn.settings import settings as conf
11 | from backtradercn.libs.log import get_logger
12 | from backtradercn.libs.models import get_or_create_library
13 |
14 | logger = get_logger(__name__)
15 |
16 |
17 | class MATrendStrategy(bt.Strategy):
18 | """
19 | If short ma > long ma, then go to long market, else, go to short market.
20 | Attributes:
21 | sma_s(DataFrame): short term moving average.
22 | sma_l(DataFrame): long term moving average.
23 | """
24 |
25 | name = conf.STRATEGY_PARAMS_MA_SYMBOL
26 |
27 | params = dict(
28 | ma_periods=dict(
29 | ma_period_s=15,
30 | ma_period_l=60,
31 | stock_id='0'
32 | )
33 | )
34 |
35 | def __init__(self):
36 | super().__init__()
37 |
38 | self.sma_s = bt.indicators.MovingAverageSimple(
39 | self.datas[0], period=self.params.ma_periods.get('ma_period_s')
40 | )
41 | self.sma_l = bt.indicators.MovingAverageSimple(
42 | self.datas[0], period=self.params.ma_periods.get('ma_period_l')
43 | )
44 |
45 | self.order = None
46 |
47 | def start(self):
48 | logger.debug('>Starting strategy, ma_period_s is %d, ma_period_l is %d' % (
49 | self.params.ma_periods.get('ma_period_s'),
50 | self.params.ma_periods.get('ma_period_l')
51 | ))
52 |
53 | def next(self):
54 |
55 | if self.order:
56 | return
57 |
58 | if not self.position:
59 | if self.sma_s[0] > self.sma_l[0]:
60 | # Using the current close price to calculate the size to buy, but use
61 | # the next open price to executed, so it is possible that the order
62 | # can not be executed due to margin, so set the target to 0.8 instead
63 | # of 1.0 to reduce the odds of not being executed
64 | target_long = 0.8
65 | self.order = self.order_target_percent(target=target_long, valid=bt.Order.DAY)
66 | if self.datas[0].datetime.date() == dt.datetime.now().date() - dt.timedelta(days=1):
67 | stock_id = self.params.ma_periods.get('stock_id')
68 | action = 'buy'
69 | bsu.Utils.log(
70 | self.datas[0].datetime.date(),
71 | f'Market Signal: stock {stock_id}, action: {action}, '
72 | f'adjust position to {target_long:.2f}')
73 | symbol = dt.datetime.now().strftime('%Y-%m-%d')
74 | bsu.Utils.write_daily_alert(symbol, stock_id, action)
75 | else:
76 | if self.sma_s[0] <= self.sma_l[0]:
77 | target_short = 0.0
78 | self.order = self.order_target_percent(target=target_short, valid=bt.Order.DAY)
79 | if self.datas[0].datetime.date() == dt.datetime.now().date() - dt.timedelta(days=1):
80 | stock_id = self.params.ma_periods.get('stock_id')
81 | action = 'sell'
82 | bsu.Utils.log(
83 | self.datas[0].datetime.date(),
84 | f'Market Signal: stock {stock_id}, action: {action}, '
85 | f'adjust position to {target_short:.2f}')
86 | symbol = dt.datetime.now().strftime('%Y-%m-%d')
87 | bsu.Utils.write_daily_alert(symbol, stock_id, action)
88 |
89 | def notify_order(self, order):
90 | if order.status in [order.Completed]:
91 | if order.isbuy():
92 | bsu.Utils.log(self.datas[0].datetime.date(),
93 | 'Stock %s buy Executed, portfolio value is %.2f' %
94 | (self.params.ma_periods.get('stock_id'),
95 | self.broker.get_value()))
96 | else:
97 | bsu.Utils.log(self.datas[0].datetime.date(),
98 | 'Stock %s sell Executed, portfolio value is %.2f' %
99 | (self.params.ma_periods.get('stock_id'),
100 | self.broker.get_value()))
101 |
102 | elif order.status in [order.Canceled, order.Margin, order.Rejected]:
103 | if order.isbuy():
104 | bsu.Utils.log(self.datas[0].datetime.date(),
105 | 'Stock %s buy order Canceled/Margin/Rejected, order_status is %d' %
106 | (self.params.ma_periods.get('stock_id'),
107 | order.status))
108 | else:
109 | bsu.Utils.log(self.datas[0].datetime.date(),
110 | 'Stock %s sell order Canceled/Margin/Rejected, order_status is %d' %
111 | (self.params.ma_periods.get('stock_id'),
112 | order.status))
113 |
114 | self.order = None
115 |
116 | @classmethod
117 | def get_data(cls, coll_name):
118 | """
119 | Get the time serials used by strategy.
120 | :param coll_name: stock id (string).
121 | :return: time serials(DataFrame).
122 | """
123 | ts_his_data = bdt.TsHisData(coll_name)
124 |
125 | return ts_his_data.get_data()
126 |
127 | @classmethod
128 | def get_params_list(cls, training_data, stock_id):
129 | """
130 | Get the params list for finding the best strategy.
131 | :param training_data(DateFrame): data for training.
132 | :param stock_id(integer): stock on which strategy works.
133 | :return: list(dict)
134 | """
135 | params_list = []
136 |
137 | data_len = len(training_data)
138 | ma_l_len = math.floor(data_len * 0.2)
139 | # data_len = 10
140 |
141 | # ma_s_len is [1, data_len * 0.1)
142 | ma_s_len = math.floor(data_len * 0.1)
143 |
144 | for i in range(1, int(ma_s_len)):
145 | for j in range(i + 1, int(ma_l_len), 5):
146 | params = dict(
147 | ma_period_s=i,
148 | ma_period_l=j,
149 | stock_id=stock_id
150 | )
151 | params_list.append(params)
152 |
153 | return params_list
154 |
155 | @classmethod
156 | def train_strategy(cls, training_data, stock_id):
157 | """
158 | Find the optimized parameter of the stategy by using training data.
159 | :param training_data(DataFrame): data used to train the strategy.
160 | :param stock_id(integer): stock on which the strategy works.
161 | :return: params(dict like {ma_periods: dict{ma_period_s: 1, ma_period_l: 2, stock_id: '0'}}
162 | """
163 | # get the params list
164 | params_list = cls.get_params_list(training_data, stock_id)
165 |
166 | al_results = []
167 |
168 | cerebro = bt.Cerebro()
169 | data = bt.feeds.PandasData(dataname=training_data)
170 |
171 | cerebro.adddata(data)
172 | cerebro.optstrategy(cls, ma_periods=params_list)
173 | cerebro.addanalyzer(bt.analyzers.TimeReturn, _name='al_return',
174 | timeframe=bt.analyzers.TimeFrame.NoTimeFrame)
175 | cerebro.addanalyzer(bt.analyzers.TimeDrawDown, _name='al_max_drawdown')
176 |
177 | cerebro.broker.setcash(bsu.Utils.DEFAULT_CASH)
178 |
179 | logger.debug(f'Starting train the strategy for stock {stock_id}...')
180 |
181 | results = cerebro.run()
182 |
183 | for result in results:
184 | params = result[0].params
185 | analyzers = result[0].analyzers
186 | al_return_rate = analyzers.al_return.get_analysis()
187 | total_return_rate = 0.0
188 | for k, v in al_return_rate.items():
189 | total_return_rate = v
190 | al_result = dict(
191 | params=params,
192 | total_return_rate=total_return_rate,
193 | max_drawdown=analyzers.al_max_drawdown.get_analysis().get('maxdrawdown'),
194 | max_drawdown_period=analyzers.al_max_drawdown.get_analysis().get('maxdrawdownperiod')
195 | )
196 | al_results.append(al_result)
197 |
198 | # Get the best params
199 | best_al_result = bsu.Utils.get_best_params(al_results)
200 |
201 | params = best_al_result.get('params')
202 | ma_periods = params.ma_periods
203 |
204 | logger.debug(
205 | 'Stock %s best parma is ma_period_s: %d, ma_period_l: %d' %
206 | (
207 | ma_periods.get('stock_id'),
208 | ma_periods.get('ma_period_s'),
209 | ma_periods.get('ma_period_l')
210 | ))
211 |
212 | return params
213 |
214 | @classmethod
215 | def run_training(cls, stock_id):
216 | # get the data
217 | data = cls.get_data(stock_id)
218 |
219 | # train the strategy for this stock_id to get the params
220 | params = cls.train_strategy(data, stock_id)
221 |
222 | return params
223 |
224 | @classmethod
225 | def run_back_testing(cls, stock_id):
226 | """
227 | Run the back testing, return the analysis data.
228 | :param stock_id(string)
229 | :return(dict): analysis data.
230 | """
231 | # get the data
232 | data = cls.get_data(stock_id)
233 | length = len(data)
234 | # get the params
235 | best_params = cls.get_params(stock_id)
236 |
237 | cerebro = bt.Cerebro()
238 | data = bt.feeds.PandasData(dataname=data)
239 |
240 | cerebro.adddata(data)
241 | ma_periods = best_params.ma_periods
242 | cerebro.addstrategy(cls, ma_periods=dict(ma_period_s=ma_periods.get('ma_period_s'),
243 | ma_period_l=ma_periods.get('ma_period_l'),
244 | stock_id=ma_periods.get('stock_id')))
245 | cerebro.addanalyzer(bt.analyzers.TimeReturn, _name='al_return',
246 | timeframe=bt.analyzers.TimeFrame.NoTimeFrame)
247 |
248 | cerebro.addanalyzer(bad.TimeDrawDown, _name='al_max_drawdown')
249 |
250 | cerebro.broker.set_cash(bsu.Utils.DEFAULT_CASH)
251 |
252 | logger.debug(
253 | 'Starting back testing, stock is %s, params is ma_period_s: %d, ma_period_l: %d...' %
254 | (
255 | ma_periods.get('stock_id'),
256 | ma_periods.get('ma_period_s'),
257 | ma_periods.get('ma_period_l')
258 | ))
259 |
260 | strats = cerebro.run()
261 | strat = strats[0]
262 |
263 | for k, v in strat.analyzers.al_return.get_analysis().items():
264 | total_return_rate = v
265 |
266 | al_result = dict(
267 | stock_id=ma_periods.get('stock_id'),
268 | trading_days=length,
269 | total_return_rate=total_return_rate,
270 | max_drawdown=strat.analyzers.al_max_drawdown.get_analysis().get('maxdrawdown'),
271 | max_drawdown_period=strat.analyzers.al_max_drawdown.get_analysis().get('maxdrawdownperiod'),
272 | drawdown_points=strat.analyzers.al_max_drawdown.get_analysis().get('drawdownpoints')
273 | )
274 |
275 | # cerebro.plot()
276 |
277 | return al_result
278 |
279 | @classmethod
280 | def get_params(cls, stock_id):
281 | """
282 | Get the params of the stock_id for this strategy.
283 | :param stockid:
284 | :return: dict(like dict(ma_periods=dict(ma_period_s=0, ma_period_l=0, stock_id='0')))
285 | """
286 | lib = get_or_create_library(conf.STRATEGY_PARAMS_LIBNAME)
287 | symbol = cls.name
288 |
289 | params_list = lib.read(symbol).data
290 | params = params_list.loc[stock_id, 'params']
291 |
292 | return params
293 |
294 | @classmethod
295 | def is_stock_in_symbol(cls, stock_id, symbol, lib):
296 | params_list = lib.read(symbol).data
297 |
298 | if stock_id in params_list.index:
299 | return True
300 | else:
301 | return False
302 |
--------------------------------------------------------------------------------
/backtradercn/strategies/utils.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import math
3 |
4 | import pandas as pd
5 |
6 | from backtradercn.settings import settings as conf
7 | from backtradercn.libs.log import get_logger
8 | from backtradercn.libs.models import get_or_create_library
9 |
10 | logger = get_logger(__name__)
11 |
12 |
13 | class Utils(object):
14 |
15 | DEFAULT_CASH = 10000.0
16 |
17 | @classmethod
18 | def split_data(cls, data, percent=0.3):
19 | """
20 | Split the data into training data and test data.
21 | :param data(DataFrame): data to be split.
22 | :param percent(float): percent of data used as training data.
23 | :return: training data(DataFrame) and testing data(DataFrame)
24 | """
25 |
26 | rows = len(data)
27 | train_rows = math.floor(rows * percent)
28 | test_rows = rows - train_rows
29 |
30 | return data.iloc[:train_rows], data.iloc[-test_rows:]
31 |
32 | @classmethod
33 | def log(cls, dt, txt):
34 | """
35 | Logging function for strategy, level is info.
36 | :param dt(datetime): datetime for bar.
37 | :param txt(string): txt to be logged.
38 | :return: None
39 | """
40 | logger.debug('%s, %s' % (dt.isoformat(), txt))
41 |
42 | @classmethod
43 | def get_best_params(cls, al_results):
44 | """
45 | Get the best params, current algorithm is the largest total return rate.
46 | :param al_results(list): all the optional params and corresponding analysis data.
47 | :return: best params and corresponding analysis data(dict)
48 | """
49 | al_results_df = pd.DataFrame.from_dict(al_results)
50 | al_results_df = al_results_df.sort_values('total_return_rate', ascending=False)
51 |
52 | al_result_dict = al_results_df.iloc[0].to_dict()
53 |
54 | return al_result_dict
55 |
56 | @classmethod
57 | def write_daily_alert(cls, symbol, stock_id, action):
58 | """
59 | write daily stock alert to MongoDB.
60 | :param symbol: Arctic symbol
61 | :param data: dict, like: {'stock': '000651', 'action': 'buy/sell'}
62 | :return: None
63 | """
64 |
65 | lib = get_or_create_library(conf.DAILY_STOCK_ALERT_LIBNAME)
66 |
67 | data = {
68 | 'stock': stock_id,
69 | 'action': action
70 | }
71 | df = pd.DataFrame([data], columns=data.keys())
72 | if symbol in lib.list_symbols():
73 | lib.append(symbol, df)
74 | else:
75 | lib.write(symbol, df)
76 |
--------------------------------------------------------------------------------
/backtradercn/tasks.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 |
3 |
4 | class Task(object):
5 | """
6 | Task for each stock's back testing.
7 | Attributes:
8 | Strategy(Strategy): class of strategy used for back testing.
9 | stock_id(string): id of stock to be back tested.
10 | """
11 |
12 | def __init__(self, Strategy, stock_id):
13 | self._Strategy = Strategy
14 | self._stock_id = stock_id
15 |
16 | def task(self):
17 | """
18 | Task for each stock's back testing.
19 | 1. Execute the back testing.
20 | 2. Get the analysis data of the back testing(average annual return rate,
21 | max draw down, draw down length, average annual draw down).
22 | :return: analysis of this back testing(dict).
23 | """
24 | # Get the data
25 | # data = self._Strategy.get_data(self._stock_id)
26 |
27 | # Split the data
28 | # training_data, testing_data = bsu.Utils.split_data(data)
29 |
30 | # Find the optimized parameter by using training data
31 | # best_param = self._Strategy.train_strategy(training_data, self._stock_id)
32 |
33 | # best_param = dict(
34 | # ma_periods=dict(
35 | # ma_period_s=10,
36 | # ma_period_l=20,
37 | # stock_id=self._stock_id
38 | #
39 | # )
40 | # )
41 |
42 | # Run back testing, get the analysis data
43 | # result = self._Strategy.run_back_testing(data, best_param)
44 |
45 | result = self._Strategy.run_back_testing(self._stock_id)
46 |
47 | return result
48 |
49 | def train(self):
50 | return self._Strategy.run_training(self._stock_id)
51 |
--------------------------------------------------------------------------------
/daily_alert.py:
--------------------------------------------------------------------------------
1 | import datetime as dt
2 | import json
3 |
4 | from backtradercn.libs.log import get_logger
5 | from backtradercn.libs.wechat import WeChatClient
6 | from backtradercn.settings import settings as conf
7 | from backtradercn.libs.xueqiu_trader import XueQiuTrader
8 | from backtradercn.libs.models import get_library
9 |
10 | logger = get_logger(__name__)
11 |
12 |
13 | def get_market_signal_by_date(date):
14 | msg = {
15 | 'buy': [],
16 | 'sell': [],
17 | }
18 |
19 | lib = get_library(conf.DAILY_STOCK_ALERT_LIBNAME)
20 | if lib:
21 | if date in lib.list_symbols():
22 | data = lib.read(date).data
23 | data = data.to_dict('records')
24 | for item in data:
25 | if item['action'] == 'buy':
26 | msg['buy'].append(item['stock'])
27 | elif item['action'] == 'sell':
28 | msg['sell'].append(item['stock'])
29 |
30 | return msg
31 |
32 |
33 | def send_daily_alert():
34 | date = dt.datetime.now().strftime('%Y-%m-%d')
35 | msg = get_market_signal_by_date(date)
36 |
37 | # send notification via wechat
38 | wx_client = WeChatClient({
39 | 'APP_ID': conf.WECHAT_APP_ID,
40 | 'APP_SECRET': conf.WECHAT_APP_SECRET,
41 | })
42 |
43 | try:
44 | response = wx_client.send_all_text_message(
45 | json.dumps(msg, ensure_ascii=False))
46 | logger.debug(response)
47 | except Exception as e:
48 | logger.error(e, exc_info=True)
49 |
50 |
51 | def update_xueqiu_cubes():
52 | date = dt.datetime.now().strftime('%Y-%m-%d')
53 | msg = get_market_signal_by_date(date)
54 | trader = XueQiuTrader(
55 | xq_account=conf.XQ_ACCOUNT,
56 | xq_password=conf.XQ_PASSWORD,
57 | xq_portfolio_market=conf.XQ_PORTFOLIO_MARKET,
58 | xq_cube_prefix=conf.XQ_CUBES_PREFIX
59 | )
60 |
61 | for stock_code in msg['buy']:
62 | trader.buy(stock_code)
63 |
64 | for stock_code in msg['sell']:
65 | trader.sell(stock_code)
66 |
67 |
68 | if __name__ == '__main__':
69 | send_daily_alert()
70 |
--------------------------------------------------------------------------------
/data_main.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import gevent.pool
3 | import gevent.monkey
4 | import tushare as ts
5 | import backtradercn.datas.tushare as bdt
6 | from backtradercn.libs.log import get_logger
7 | from backtradercn.libs import models
8 | from backtradercn.settings import settings as conf
9 |
10 |
11 | gevent.monkey.patch_all()
12 | logger = get_logger(__name__)
13 |
14 |
15 | def download_delta_data(stocks, pool_size=40):
16 | """
17 | Download delta data for all stocks collections of all libraries.
18 | :param stocks: stock code list.
19 | :param pool_size: the pool size of gevent.pool.Pool.
20 | :return: None
21 | """
22 |
23 | pool = gevent.pool.Pool(pool_size)
24 | for i in range(len(stocks) // pool_size + 1):
25 | start = i * pool_size
26 | end = (i + 1) * pool_size
27 | lst = stocks[start:end]
28 | logger.debug(f'download delta data for stock list: {lst}')
29 | for stock in lst:
30 | pool.spawn(bdt.TsHisData.download_one_delta_data, stock)
31 | pool.join(timeout=30)
32 |
33 |
34 | if __name__ == '__main__':
35 | # make sure the library exists
36 | models.get_or_create_library(conf.CN_STOCK_LIBNAME)
37 |
38 | # download_delta_data(['000651', '000001'])
39 |
40 | hs300s = ts.get_hs300s()
41 | stock_pools = hs300s['code'].tolist() if 'code' in hs300s else []
42 | if not stock_pools:
43 | logger.warning('can not ts.geths300s() return empty.')
44 | stock_pools = models.get_cn_stocks()
45 | download_delta_data(stock_pools)
46 |
--------------------------------------------------------------------------------
/dev-requirements.txt:
--------------------------------------------------------------------------------
1 | coverage
2 | codecov
3 | pytest
4 | pylint
5 | git-pylint-commit-hook
6 | sphinx
7 | sphinx_rtd_theme
8 |
--------------------------------------------------------------------------------
/docs/Makefile:
--------------------------------------------------------------------------------
1 | # Minimal makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | SPHINXPROJ = backtrader-cn
8 | SOURCEDIR = .
9 | BUILDDIR = _build
10 |
11 | # Put it first so that "make" without argument is like "make help".
12 | help:
13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
14 |
15 | .PHONY: help Makefile
16 |
17 | # Catch-all target: route all unknown targets to Sphinx using the new
18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
19 | %: Makefile
20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
--------------------------------------------------------------------------------
/docs/conf.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | #
4 | # backtrader-cn documentation build configuration file, created by
5 | # sphinx-quickstart on Sat Oct 7 20:20:47 2017.
6 | #
7 | # This file is execfile()d with the current directory set to its
8 | # containing dir.
9 | #
10 | # Note that not all possible configuration values are present in this
11 | # autogenerated file.
12 | #
13 | # All configuration values have a default; values that are commented out
14 | # serve to show the default.
15 |
16 | # If extensions (or modules to document with autodoc) are in another directory,
17 | # add these directories to sys.path here. If the directory is relative to the
18 | # documentation root, use os.path.abspath to make it absolute, like shown here.
19 | #
20 | # import os
21 | # import sys
22 | # sys.path.insert(0, os.path.abspath('.'))
23 | # from recommonmark.parser import CommonMarkParser
24 |
25 | # source_parsers = {
26 | # '.md': CommonMarkParser,
27 | # }
28 |
29 | # -- General configuration ------------------------------------------------
30 |
31 | # If your documentation needs a minimal Sphinx version, state it here.
32 | #
33 | # needs_sphinx = '1.0'
34 |
35 | # Add any Sphinx extension module names here, as strings. They can be
36 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
37 | # ones.
38 | extensions = []
39 |
40 | # Add any paths that contain templates here, relative to this directory.
41 | templates_path = ['_templates']
42 |
43 | # The suffix(es) of source filenames.
44 | # You can specify multiple suffix as a list of string:
45 | #
46 | # source_suffix = ['.rst', '.md']
47 | source_suffix = '.rst'
48 |
49 | # The master toctree document.
50 | master_doc = 'index'
51 |
52 | # General information about the project.
53 | project = 'backtrader-cn'
54 | copyright = '2017, pandalibin'
55 | author = 'pandalibin'
56 |
57 | # The version info for the project you're documenting, acts as replacement for
58 | # |version| and |release|, also used in various other places throughout the
59 | # built documents.
60 | #
61 | # The short X.Y version.
62 | version = '0.0.1'
63 | # The full version, including alpha/beta/rc tags.
64 | release = '0.0.1'
65 |
66 | # The language for content autogenerated by Sphinx. Refer to documentation
67 | # for a list of supported languages.
68 | #
69 | # This is also used if you do content translation via gettext catalogs.
70 | # Usually you set "language" from the command line for these cases.
71 | language = None
72 |
73 | # List of patterns, relative to source directory, that match files and
74 | # directories to ignore when looking for source files.
75 | # This patterns also effect to html_static_path and html_extra_path
76 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
77 |
78 | # The name of the Pygments (syntax highlighting) style to use.
79 | pygments_style = 'sphinx'
80 |
81 | # If true, `todo` and `todoList` produce output, else they produce nothing.
82 | todo_include_todos = False
83 |
84 | # -- Options for HTML output ----------------------------------------------
85 |
86 | # The theme to use for HTML and HTML Help pages. See the documentation for
87 | # a list of builtin themes.
88 | #
89 | html_theme = 'sphinx_rtd_theme'
90 |
91 | # Theme options are theme-specific and customize the look and feel of a theme
92 | # further. For a list of options available for each theme, see the
93 | # documentation.
94 | #
95 | # html_theme_options = {}
96 |
97 | # Add any paths that contain custom static files (such as style sheets) here,
98 | # relative to this directory. They are copied after the builtin static files,
99 | # so a file named "default.css" will overwrite the builtin "default.css".
100 | html_static_path = ['_static']
101 |
102 | # -- Options for HTMLHelp output ------------------------------------------
103 |
104 | # Output file base name for HTML help builder.
105 | htmlhelp_basename = 'backtrader-cndoc'
106 |
107 | # -- Options for LaTeX output ---------------------------------------------
108 |
109 | latex_elements = {
110 | # The paper size ('letterpaper' or 'a4paper').
111 | #
112 | # 'papersize': 'letterpaper',
113 |
114 | # The font size ('10pt', '11pt' or '12pt').
115 | #
116 | # 'pointsize': '10pt',
117 |
118 | # Additional stuff for the LaTeX preamble.
119 | #
120 | # 'preamble': '',
121 |
122 | # Latex figure (float) alignment
123 | #
124 | # 'figure_align': 'htbp',
125 | }
126 |
127 | # Grouping the document tree into LaTeX files. List of tuples
128 | # (source start file, target name, title,
129 | # author, documentclass [howto, manual, or own class]).
130 | latex_documents = [
131 | (master_doc, 'backtrader-cn.tex', 'backtrader-cn Documentation',
132 | 'pandalibin', 'manual'),
133 | ]
134 |
135 | # -- Options for manual page output ---------------------------------------
136 |
137 | # One entry per manual page. List of tuples
138 | # (source start file, name, description, authors, manual section).
139 | man_pages = [
140 | (master_doc, 'backtrader-cn', 'backtrader-cn Documentation',
141 | [author], 1)
142 | ]
143 |
144 | # -- Options for Texinfo output -------------------------------------------
145 |
146 | # Grouping the document tree into Texinfo files. List of tuples
147 | # (source start file, target name, title, author,
148 | # dir menu entry, description, category)
149 | texinfo_documents = [
150 | (master_doc, 'backtrader-cn', 'backtrader-cn Documentation',
151 | author, 'backtrader-cn', 'One line description of project.',
152 | 'Miscellaneous'),
153 | ]
154 |
--------------------------------------------------------------------------------
/docs/content.rst.inc:
--------------------------------------------------------------------------------
1 | User's Guide
2 | ============
3 |
4 | .. toctree::
5 | :maxdepth: 2
6 |
7 | getting_started
8 | usage
--------------------------------------------------------------------------------
/docs/getting_started.rst:
--------------------------------------------------------------------------------
1 | Getting started with backtrader-cn
2 | ==================================
3 |
4 | Installation
5 | ------------
6 |
7 | Quick start
8 | -----------
9 |
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 | :orphan:
2 |
3 | .. include :: ../README.rst
4 | .. include :: content.rst.inc
5 |
--------------------------------------------------------------------------------
/docs/make.bat:
--------------------------------------------------------------------------------
1 | @ECHO OFF
2 |
3 | pushd %~dp0
4 |
5 | REM Command file for Sphinx documentation
6 |
7 | if "%SPHINXBUILD%" == "" (
8 | set SPHINXBUILD=sphinx-build
9 | )
10 | set SOURCEDIR=.
11 | set BUILDDIR=_build
12 | set SPHINXPROJ=backtrader-cn
13 |
14 | if "%1" == "" goto help
15 |
16 | %SPHINXBUILD% >NUL 2>NUL
17 | if errorlevel 9009 (
18 | echo.
19 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
20 | echo.installed, then set the SPHINXBUILD environment variable to point
21 | echo.to the full path of the 'sphinx-build' executable. Alternatively you
22 | echo.may add the Sphinx directory to PATH.
23 | echo.
24 | echo.If you don't have Sphinx installed, grab it from
25 | echo.http://sphinx-doc.org/
26 | exit /b 1
27 | )
28 |
29 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
30 | goto end
31 |
32 | :help
33 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS%
34 |
35 | :end
36 | popd
37 |
--------------------------------------------------------------------------------
/docs/usage.rst:
--------------------------------------------------------------------------------
1 | Using backtrader-cn
2 | ===================
3 |
--------------------------------------------------------------------------------
/frm_main.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import multiprocessing
3 |
4 | import backtradercn.strategies.ma as bsm
5 | import backtradercn.tasks as btasks
6 | from backtradercn.libs.log import get_logger
7 | from backtradercn.libs import models
8 |
9 | logger = get_logger(__name__)
10 |
11 |
12 | def back_test(stock):
13 | """
14 | Run back testing tasks via multiprocessing
15 | :return: None
16 | """
17 |
18 | task = btasks.Task(bsm.MATrendStrategy, stock)
19 | result = task.task()
20 |
21 | stock_id = result.get('stock_id')
22 | trading_days = result.get('trading_days')
23 | total_return_rate = result.get('total_return_rate')
24 | max_drawdown = result.get('max_drawdown')
25 | max_drawdown_period = result.get('max_drawdown_period')
26 | logger.debug(
27 | f'Stock {stock_id} back testing result, trading days: {trading_days:.2f}, '
28 | f'total return rate: {total_return_rate:.2f}, '
29 | f'max drawdown: {max_drawdown:.2f}, '
30 | f'max drawdown period: {max_drawdown_period:.2f}'
31 | )
32 |
33 | drawdown_points = result.get('drawdown_points')
34 | logger.debug('Draw down points:')
35 | for drawdown_point in drawdown_points:
36 | drawdown_point_dt = drawdown_point.get("datetime").isoformat()
37 | drawdown = drawdown_point.get('drawdown')
38 | drawdownlen = drawdown_point.get('drawdownlen')
39 | logger.debug(
40 | f'stock: {stock_id}, drawdown_point: {drawdown_point_dt}, '
41 | f'drawdown: {drawdown:.2f}, drawdownlen: {drawdownlen}'
42 | )
43 |
44 |
45 | def main(stock_pools):
46 | """
47 | Get all stocks and run back test.
48 | :param stock_pools: list, the stock code list.
49 | :return: None
50 | """
51 |
52 | pool = multiprocessing.Pool()
53 | for stock in stock_pools:
54 | pool.apply_async(back_test, args=(stock, ))
55 | pool.close()
56 | pool.join()
57 |
58 |
59 | if __name__ == '__main__':
60 | cn_stocks = models.get_cn_stocks()
61 | main(cn_stocks)
62 |
--------------------------------------------------------------------------------
/issue_template.md:
--------------------------------------------------------------------------------
1 | ### Description
2 |
3 | ### Expected behavior
4 |
5 | ### Actual behavior
6 |
7 | ### Steps to reproduce the behavior
8 | 1.
9 | 2.
10 | 3.
11 |
12 | ### Specifications
13 | * Version:
14 |
--------------------------------------------------------------------------------
/pylintrc:
--------------------------------------------------------------------------------
1 | [MASTER]
2 |
3 | # Specify a configuration file.
4 | #rcfile=
5 |
6 | # Python code to execute, usually for sys.path manipulation such as
7 | # pygtk.require().
8 | #init-hook=
9 |
10 | # Add files or directories to the blacklist. They should be base names, not
11 | # paths.
12 | ignore=CVS
13 |
14 | # Pickle collected data for later comparisons.
15 | persistent=yes
16 |
17 | # List of plugins (as comma separated values of python modules names) to load,
18 | # usually to register additional checkers.
19 | load-plugins=
20 |
21 | # Use multiple processes to speed up Pylint.
22 | jobs=1
23 |
24 | # Allow loading of arbitrary C extensions. Extensions are imported into the
25 | # active Python interpreter and may run arbitrary code.
26 | unsafe-load-any-extension=no
27 |
28 | # A comma-separated list of package or module names from where C extensions may
29 | # be loaded. Extensions are loading into the active Python interpreter and may
30 | # run arbitrary code
31 | extension-pkg-whitelist=
32 |
33 | # Allow optimization of some AST trees. This will activate a peephole AST
34 | # optimizer, which will apply various small optimizations. For instance, it can
35 | # be used to obtain the result of joining multiple strings with the addition
36 | # operator. Joining a lot of strings can lead to a maximum recursion error in
37 | # Pylint and this flag can prevent that. It has one side effect, the resulting
38 | # AST will be different than the one from reality.
39 | optimize-ast=no
40 |
41 |
42 | [MESSAGES CONTROL]
43 |
44 | # Only show warnings with the listed confidence levels. Leave empty to show
45 | # all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED
46 | confidence=
47 |
48 | # Enable the message, report, category or checker with the given id(s). You can
49 | # either give multiple identifier separated by comma (,) or put this option
50 | # multiple time (only on the command line, not in the configuration file where
51 | # it should appear only once). See also the "--disable" option for examples.
52 | #enable=
53 |
54 | # Disable the message, report, category or checker with the given id(s). You
55 | # can either give multiple identifiers separated by comma (,) or put this
56 | # option multiple times (only on the command line, not in the configuration
57 | # file where it should appear only once).You can also use "--disable=all" to
58 | # disable everything first and then reenable specific checks. For example, if
59 | # you want to run only the similarities checker, you can use "--disable=all
60 | # --enable=similarities". If you want to run only the classes checker, but have
61 | # no Warning level messages displayed, use"--disable=all --enable=classes
62 | # --disable=W"
63 | disable=
64 | # disabled by me,
65 | locally-disabled,
66 | missing-docstring,
67 | fixme,
68 | # disabled by default,
69 | import-star-module-level,
70 | old-octal-literal,
71 | oct-method,
72 | print-statement,
73 | unpacking-in-except,
74 | parameter-unpacking,
75 | backtick,
76 | old-raise-syntax,
77 | old-ne-operator,
78 | long-suffix,
79 | dict-view-method,
80 | dict-iter-method,
81 | metaclass-assignment,
82 | next-method-called,
83 | raising-string,
84 | indexing-exception,
85 | raw_input-builtin,
86 | long-builtin,
87 | file-builtin,
88 | execfile-builtin,
89 | coerce-builtin,
90 | cmp-builtin,
91 | buffer-builtin,
92 | basestring-builtin,
93 | apply-builtin,
94 | filter-builtin-not-iterating,
95 | using-cmp-argument,
96 | useless-suppression,
97 | range-builtin-not-iterating,
98 | suppressed-message,
99 | no-absolute-import,
100 | old-division,
101 | cmp-method,
102 | reload-builtin,
103 | zip-builtin-not-iterating,
104 | intern-builtin,
105 | unichr-builtin,
106 | reduce-builtin,
107 | standarderror-builtin,
108 | unicode-builtin,
109 | xrange-builtin,
110 | coerce-method,
111 | delslice-method,
112 | getslice-method,
113 | setslice-method,
114 | input-builtin,
115 | round-builtin,
116 | hex-method,
117 | nonzero-method,
118 | map-builtin-not-iterating,
119 |
120 |
121 | [REPORTS]
122 |
123 | # Set the output format. Available formats are text, parseable, colorized, msvs
124 | # (visual studio) and html. You can also give a reporter class, eg
125 | # mypackage.mymodule.MyReporterClass.
126 | output-format=text
127 |
128 | # Put messages in a separate file for each module / package specified on the
129 | # command line instead of printing them on stdout. Reports (if any) will be
130 | # written in a file name "pylint_global.[txt|html]".
131 | files-output=no
132 |
133 | # Tells whether to display a full report or only the messages
134 | reports=yes
135 |
136 | # Python expression which should return a note less than 10 (10 is the highest
137 | # note). You have access to the variables errors warning, statement which
138 | # respectively contain the number of errors / warnings messages and the total
139 | # number of statements analyzed. This is used by the global evaluation report
140 | # (RP0004).
141 | evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)
142 |
143 | # Template used to display messages. This is a python new-style format string
144 | # used to format the message information. See doc for all details
145 | #msg-template=
146 |
147 |
148 | [FORMAT]
149 |
150 | # Maximum number of characters on a single line.
151 | max-line-length=100
152 |
153 | # Regexp for a line that is allowed to be longer than the limit.
154 | ignore-long-lines=^\s*(# )??$
155 |
156 | # Allow the body of an if to be on the same line as the test if there is no
157 | # else.
158 | single-line-if-stmt=no
159 |
160 | # List of optional constructs for which whitespace checking is disabled. `dict-
161 | # separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}.
162 | # `trailing-comma` allows a space between comma and closing bracket: (a, ).
163 | # `empty-line` allows space-only lines.
164 | no-space-check=trailing-comma,dict-separator
165 |
166 | # Maximum number of lines in a module
167 | max-module-lines=1000
168 |
169 | # String used as indentation unit. This is usually " " (4 spaces) or "\t" (1
170 | # tab).
171 | indent-string=' '
172 |
173 | # Number of spaces of indent required inside a hanging or continued line.
174 | indent-after-paren=4
175 |
176 | # Expected format of line ending, e.g. empty (any line ending), LF or CRLF.
177 | expected-line-ending-format=
178 |
179 |
180 | [SPELLING]
181 |
182 | # Spelling dictionary name. Available dictionaries: none. To make it working
183 | # install python-enchant package.
184 | spelling-dict=
185 |
186 | # List of comma separated words that should not be checked.
187 | spelling-ignore-words=
188 |
189 | # A path to a file that contains private dictionary; one word per line.
190 | spelling-private-dict-file=
191 |
192 | # Tells whether to store unknown words to indicated private dictionary in
193 | # --spelling-private-dict-file option instead of raising a message.
194 | spelling-store-unknown-words=no
195 |
196 |
197 | [LOGGING]
198 |
199 | # Logging modules to check that the string format arguments are in logging
200 | # function parameter format
201 | logging-modules=logging
202 |
203 |
204 | [BASIC]
205 |
206 | # List of builtins function names that should not be used, separated by a comma
207 | bad-functions=map,filter,input
208 |
209 | # Good variable names which should always be accepted, separated by a comma
210 | good-names=i,j,e,s,_,fd,fp,df,k,v
211 |
212 | # Bad variable names which should always be refused, separated by a comma
213 | bad-names=foo,bar,baz,toto,tutu,tata
214 |
215 | # Colon-delimited sets of names that determine each other's naming style when
216 | # the name regexes allow several styles.
217 | name-group=
218 |
219 | # Include a hint for the correct naming format with invalid-name
220 | include-naming-hint=no
221 |
222 | # Regular expression matching correct function names
223 | # original:
224 | #function-rgx=[a-z_][a-z0-9_]{2,30}$
225 | function-rgx=[a-zA-Z_][a-zA-Z0-9_]{2,40}$
226 |
227 | # Naming hint for function names
228 | function-name-hint=[a-z_][a-z0-9_]{2,30}$
229 |
230 | # Regular expression matching correct variable names
231 | variable-rgx=[a-z_][a-z0-9_]{2,30}$
232 |
233 | # Naming hint for variable names
234 | variable-name-hint=[a-z_][a-z0-9_]{2,30}$
235 |
236 | # Regular expression matching correct constant names
237 | # original:
238 | #const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$
239 | const-rgx=(([a-zA-Z_][a-zA-Z0-9_]*)|(__.*__))$
240 |
241 | # Naming hint for constant names
242 | const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$
243 |
244 | # Regular expression matching correct attribute names
245 | attr-rgx=[a-z_][a-z0-9_]{2,30}$
246 |
247 | # Naming hint for attribute names
248 | attr-name-hint=[a-z_][a-z0-9_]{2,30}$
249 |
250 | # Regular expression matching correct argument names
251 | argument-rgx=[a-z_][a-z0-9_]{2,30}$
252 |
253 | # Naming hint for argument names
254 | argument-name-hint=[a-z_][a-z0-9_]{2,30}$
255 |
256 | # Regular expression matching correct class attribute names
257 | # original:
258 | #class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
259 | class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,40}|(__.*__))$
260 |
261 | # Naming hint for class attribute names
262 | class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$
263 |
264 | # Regular expression matching correct inline iteration names
265 | inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$
266 |
267 | # Naming hint for inline iteration names
268 | inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$
269 |
270 | # Regular expression matching correct class names
271 | # original:
272 | #class-rgx=[A-Z_][a-zA-Z0-9]+$
273 | class-rgx=[a-zA-Z_][a-zA-Z0-9]+$
274 |
275 | # Naming hint for class names
276 | class-name-hint=[A-Z_][a-zA-Z0-9]+$
277 |
278 | # Regular expression matching correct module names
279 | module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
280 |
281 | # Naming hint for module names
282 | module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$
283 |
284 | # Regular expression matching correct method names
285 | # original:
286 | #method-rgx=[a-z_][a-z0-9_]{2,30}$
287 | method-rgx=[a-zA-Z_][a-zA-Z0-9_]{2,40}$
288 |
289 | # Naming hint for method names
290 | method-name-hint=[a-z_][a-z0-9_]{2,30}$
291 |
292 | # Regular expression which should only match function or class names that do
293 | # not require a docstring.
294 | no-docstring-rgx=^_
295 |
296 | # Minimum line length for functions/classes that require docstrings, shorter
297 | # ones are exempt.
298 | docstring-min-length=-1
299 |
300 |
301 | [ELIF]
302 |
303 | # Maximum number of nested blocks for function / method body
304 | max-nested-blocks=5
305 |
306 |
307 | [SIMILARITIES]
308 |
309 | # Minimum lines number of a similarity.
310 | min-similarity-lines=4
311 |
312 | # Ignore comments when computing similarities.
313 | ignore-comments=yes
314 |
315 | # Ignore docstrings when computing similarities.
316 | ignore-docstrings=yes
317 |
318 | # Ignore imports when computing similarities.
319 | ignore-imports=no
320 |
321 |
322 | [TYPECHECK]
323 |
324 | # Tells whether missing members accessed in mixin class should be ignored. A
325 | # mixin class is detected if its name ends with "mixin" (case insensitive).
326 | ignore-mixin-members=yes
327 |
328 | # List of module names for which member attributes should not be checked
329 | # (useful for modules/projects where namespaces are manipulated during runtime
330 | # and thus existing member attributes cannot be deduced by static analysis. It
331 | # supports qualified module names, as well as Unix pattern matching.
332 | ignored-modules=
333 |
334 | # List of classes names for which member attributes should not be checked
335 | # (useful for classes with attributes dynamically set). This supports can work
336 | # with qualified names.
337 | ignored-classes=
338 |
339 | # List of members which are set dynamically and missed by pylint inference
340 | # system, and so shouldn't trigger E1101 when accessed. Python regular
341 | # expressions are accepted.
342 | generated-members=
343 |
344 |
345 | [MISCELLANEOUS]
346 |
347 | # List of note tags to take in consideration, separated by a comma.
348 | notes=FIXME,XXX,TODO
349 |
350 |
351 | [VARIABLES]
352 |
353 | # Tells whether we should check for unused import in __init__ files.
354 | init-import=no
355 |
356 | # A regular expression matching the name of dummy variables (i.e. expectedly
357 | # not used).
358 | dummy-variables-rgx=_$|dummy
359 |
360 | # List of additional names supposed to be defined in builtins. Remember that
361 | # you should avoid to define new builtins when possible.
362 | additional-builtins=
363 |
364 | # List of strings which can identify a callback function by name. A callback
365 | # name must start or end with one of those strings.
366 | callbacks=cb_,_cb
367 |
368 |
369 | [CLASSES]
370 |
371 | # List of method names used to declare (i.e. assign) instance attributes.
372 | defining-attr-methods=__init__,__new__,setUp
373 |
374 | # List of valid names for the first argument in a class method.
375 | valid-classmethod-first-arg=cls
376 |
377 | # List of valid names for the first argument in a metaclass class method.
378 | valid-metaclass-classmethod-first-arg=mcs
379 |
380 | # List of member names, which should be excluded from the protected access
381 | # warning.
382 | exclude-protected=_asdict,_fields,_replace,_source,_make
383 |
384 |
385 | [DESIGN]
386 |
387 | # Maximum number of arguments for function / method
388 | max-args=5
389 |
390 | # Argument names that match this expression will be ignored. Default to name
391 | # with leading underscore
392 | ignored-argument-names=_.*
393 |
394 | # Maximum number of locals for function / method body
395 | max-locals=15
396 |
397 | # Maximum number of return / yield for function / method body
398 | max-returns=6
399 |
400 | # Maximum number of branch for function / method body
401 | max-branches=12
402 |
403 | # Maximum number of statements in function / method body
404 | max-statements=50
405 |
406 | # Maximum number of parents for a class (see R0901).
407 | max-parents=7
408 |
409 | # Maximum number of attributes for a class (see R0902).
410 | max-attributes=7
411 |
412 | # Minimum number of public methods for a class (see R0903).
413 | min-public-methods=2
414 |
415 | # Maximum number of public methods for a class (see R0904).
416 | max-public-methods=20
417 |
418 | # Maximum number of boolean expressions in a if statement
419 | max-bool-expr=5
420 |
421 |
422 | [IMPORTS]
423 |
424 | # Deprecated modules which should not be used, separated by a comma
425 | deprecated-modules=regsub,TERMIOS,Bastion,rexec
426 |
427 | # Create a graph of every (i.e. internal and external) dependencies in the
428 | # given file (report RP0402 must not be disabled)
429 | import-graph=
430 |
431 | # Create a graph of external dependencies in the given file (report RP0402 must
432 | # not be disabled)
433 | ext-import-graph=
434 |
435 | # Create a graph of internal dependencies in the given file (report RP0402 must
436 | # not be disabled)
437 | int-import-graph=
438 |
439 |
440 | [EXCEPTIONS]
441 |
442 | # Exceptions that will emit a warning when being caught. Defaults to
443 | # "Exception"
444 | overgeneral-exceptions=Exception
445 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | beautifulsoup4 # tushare require
2 | lxml # tushare require
3 | xlrd # tushare require
4 | requests # tushae require
5 | pandas==0.20.1
6 | backtrader
7 | tushare
8 | arctic
9 | WeRoBot==1.1.1
10 | gevent
11 | easytrader==0.12.3
12 | demjson==2.2.4
13 | retrying==1.3.3
14 |
--------------------------------------------------------------------------------
/stock_match.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import time
3 | from datetime import datetime, timedelta
4 | from backtradercn.settings import settings as conf
5 | from backtradercn.libs.sina import StockMatch
6 | from daily_alert import get_market_signal_by_date
7 | from backtradercn.libs.log import get_logger
8 |
9 | logger = get_logger(__name__)
10 |
11 |
12 | def update_sina_stock_match():
13 | date = (datetime.now() - timedelta(days=1)).strftime('%Y-%m-%d')
14 | msg = get_market_signal_by_date(date)
15 | user = StockMatch(
16 | username=conf.SINA_CONFIG['username'],
17 | password=conf.SINA_CONFIG['password'],
18 | )
19 | for stock_code in msg['buy']:
20 | user.buy(stock_code)
21 | # 经过测试,每隔3S进行一次买入操作的频率最合适
22 | time.sleep(3)
23 | else:
24 | logger.info("没有股票需要买入")
25 |
26 |
27 | if __name__ == '__main__':
28 | update_sina_stock_match()
29 |
--------------------------------------------------------------------------------
/tests/libs/test_models.py:
--------------------------------------------------------------------------------
1 | """
2 | Test cases for libs.moels.py
3 | """
4 | import random
5 | import arctic
6 |
7 | from backtradercn.libs import models
8 |
9 |
10 | RUN_TEST_LIBRARY = 'just_for_run_test_library'
11 |
12 |
13 | def test_get_store():
14 | store = models.get_store()
15 | assert isinstance(store, arctic.arctic.Arctic)
16 |
17 | def test_create_library():
18 | lib = models.create_library(RUN_TEST_LIBRARY)
19 | assert isinstance(lib, arctic.store.version_store.VersionStore)
20 |
21 | def test_get_library_exist():
22 | lib = models.get_library(RUN_TEST_LIBRARY)
23 | assert isinstance(lib, arctic.store.version_store.VersionStore)
24 |
25 | def test_get_library_not_exist():
26 | lib_name = '{}{}'.format(RUN_TEST_LIBRARY, random.randint(1, 100))
27 | lib = models.get_library(lib_name)
28 | assert lib is None
29 |
30 | def test_get_or_create_library_exist():
31 | lib = models.get_or_create_library(RUN_TEST_LIBRARY)
32 | assert isinstance(lib, arctic.store.version_store.VersionStore)
33 |
34 | def test_get_or_create_library_not_exist():
35 | lib_name = '{}{}'.format(RUN_TEST_LIBRARY, random.randint(1, 100))
36 | lib = models.get_or_create_library(lib_name)
37 | assert isinstance(lib, arctic.store.version_store.VersionStore)
38 |
39 | models.drop_library(lib_name)
40 | assert models.get_library(lib_name) is None
41 |
42 | def test_drop_library_exist():
43 | models.drop_library(RUN_TEST_LIBRARY)
44 | assert models.get_library(RUN_TEST_LIBRARY) is None
45 |
46 | def test_get_cn_stocks():
47 | stocks = models.get_cn_stocks()
48 | assert isinstance(stocks, list)
49 |
--------------------------------------------------------------------------------
/tests/test_datas_tushare.py:
--------------------------------------------------------------------------------
1 | import unittest
2 | import unittest.mock as um
3 | import datetime as dt
4 | import pandas as pd
5 | import backtradercn.datas.tushare as bdt
6 |
7 | from backtradercn.settings import settings as conf
8 | from backtradercn.libs import models
9 |
10 |
11 | class TsHisDataTestCase(unittest.TestCase):
12 | def test_run(self):
13 | self._test_download_delta_data_initial_no_data()
14 | self._test_download_delta_data_initial()
15 | self._test_download_delta_data_no_data()
16 | self._test_download_delta_data()
17 |
18 | @um.patch('tushare.get_hist_data')
19 | def _test_download_delta_data_initial_no_data(self, mock_get_hist_data):
20 | mock_hist_data = pd.DataFrame()
21 |
22 | mock_get_hist_data.return_value = mock_hist_data
23 |
24 | coll_name = '000651'
25 | ts_his_data = bdt.TsHisData(coll_name)
26 |
27 | lib = models.get_library(conf.CN_STOCK_LIBNAME)
28 | lib.delete(coll_name)
29 |
30 | ts_his_data.download_delta_data()
31 |
32 | self.assertFalse(lib.has_symbol(coll_name))
33 |
34 | @um.patch('tushare.get_hist_data')
35 | def _test_download_delta_data_initial(self, mock_get_hist_data):
36 | mock_hist_data = pd.DataFrame(data={
37 | 'open': [10, 11],
38 | 'high': [12, 13],
39 | 'close': [14, 15],
40 | 'low': [16, 17],
41 | 'volume': [18, 19],
42 | 'price_change': [20, 21],
43 | 'p_change': [22, 23],
44 | 'ma5': [24, 25],
45 | 'ma10': [26, 27],
46 | 'ma20': [28, 29],
47 | 'v_ma5': [30, 31],
48 | 'v_ma10': [32, 33],
49 | 'v_ma20': [34, 35],
50 | 'turnover': [36, 37]
51 | }, index=['2017-01-01', '2017-01-02'])
52 |
53 | mock_get_hist_data.return_value = mock_hist_data
54 |
55 | coll_name = '000651'
56 | ts_his_data = bdt.TsHisData(coll_name)
57 |
58 | lib = models.get_library(conf.CN_STOCK_LIBNAME)
59 | lib.delete(coll_name)
60 |
61 | ts_his_data.download_delta_data()
62 |
63 | hist_data_000651 = ts_his_data.get_data()
64 |
65 | self.assertEqual(len(hist_data_000651), 2)
66 |
67 | @um.patch('tushare.get_hist_data')
68 | def _test_download_delta_data_no_data(self, mock_get_hist_data):
69 | coll_name = '000651'
70 | ts_his_data = bdt.TsHisData(coll_name)
71 |
72 | mock_delta_data = pd.DataFrame()
73 | mock_get_hist_data.return_value = mock_delta_data
74 |
75 | ts_his_data.download_delta_data()
76 |
77 | hist_data_000651 = ts_his_data.get_data()
78 |
79 | self.assertEqual(len(hist_data_000651), 2)
80 |
81 | @um.patch('tushare.get_hist_data')
82 | def _test_download_delta_data(self, mock_get_hist_data):
83 | coll_name = '000651'
84 | ts_his_data = bdt.TsHisData(coll_name)
85 |
86 | yesterday = dt.datetime.now() - dt.timedelta(days=1)
87 | mock_delta_data = pd.DataFrame(data={
88 | 'open': 38,
89 | 'high': 39,
90 | 'close': 40,
91 | 'low': 41,
92 | 'volume': 42,
93 | 'price_change': 43,
94 | 'p_change': 44,
95 | 'ma5': 45,
96 | 'ma10': 46,
97 | 'ma20': 47,
98 | 'v_ma5': 48,
99 | 'v_ma10': 49,
100 | 'v_ma20': 50,
101 | 'turnover': 51
102 | }, index=[dt.datetime.strftime(yesterday, '%Y-%m-%d')])
103 |
104 | mock_get_hist_data.return_value = mock_delta_data
105 |
106 | ts_his_data.download_delta_data()
107 |
108 | hist_data_000651 = ts_his_data.get_data()
109 |
110 | self.assertEqual(len(hist_data_000651), 3)
111 | self.assertEqual(dt.datetime.strftime(hist_data_000651.index[-1], '%Y-%m-%d'),
112 | dt.datetime.strftime(yesterday, '%Y-%m-%d'))
113 | lib = models.get_library(conf.CN_STOCK_LIBNAME)
114 | lib.delete(coll_name)
115 |
--------------------------------------------------------------------------------
/tests/test_datas_utils.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import unittest
3 | import backtradercn.datas.utils as bdu
4 | import pandas as pd
5 | import datetime as dt
6 |
7 |
8 | class UtilsTestCase(unittest.TestCase):
9 | def test_run(self):
10 | self._test_strip_unused_cols()
11 | self._test_parse_data()
12 |
13 | def _test_parse_data(self):
14 | date_string = '2017-01-01'
15 | parsed_date = bdu.Utils.parse_date(date_string)
16 |
17 | self.assertEqual(parsed_date, dt.datetime(2017, 1, 1))
18 |
19 | def _test_strip_unused_cols(self):
20 | data = pd.DataFrame({
21 | 'name': ['tom', 'jack'],
22 | 'age': [24, 56],
23 | 'gender': ['male', 'male'],
24 | 'address': ['cn', 'us']
25 | })
26 | data.index = pd.date_range(start='2017-01-01', periods=2)
27 |
28 | origin_cols = ['name', 'age', 'gender', 'address']
29 | unused_cols = ['address', 'gender']
30 | new_cols = ['name', 'age']
31 |
32 | self.assertEqual(list(data.columns).sort(), origin_cols.sort())
33 |
34 | bdu.Utils.strip_unused_cols(data, *unused_cols)
35 |
36 | self.assertEqual(list(data.columns).sort(), new_cols.sort())
37 |
--------------------------------------------------------------------------------
/tests/test_strategies_ma.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import unittest
3 | import pandas as pd
4 | import numpy as np
5 | import backtradercn.strategies.ma as bsm
6 |
7 |
8 | class MATrendStrategyTestCase(unittest.TestCase):
9 | def test_run(self):
10 | self._test_get_params_list()
11 |
12 | def _test_get_params_list(self):
13 | training_data = pd.DataFrame(np.random.rand(100, 2))
14 | params_list = bsm.MATrendStrategy.get_params_list(training_data, '000651')
15 |
16 | self.assertEqual(len(params_list), 29)
17 |
--------------------------------------------------------------------------------
/tests/test_strategies_utils.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import unittest
3 | import backtradercn.strategies.utils as bsu
4 | import datetime as dt
5 | import pandas as pd
6 | import numpy as np
7 |
8 |
9 | class UtilsTestCase(unittest.TestCase):
10 | def test_run(self):
11 | self._test_split_data()
12 | self._test_get_best_params()
13 |
14 | def _test_split_data(self):
15 | data = pd.DataFrame(np.random.rand(10, 2))
16 | data.index = ['2017-01-01', '2017-01-02', '2017-01-03', '2017-01-04', '2017-01-05',
17 | '2017-01-06', '2017-01-07', '2017-01-08', '2017-01-09', '2017-01-10']
18 |
19 | training_data, testing_data = bsu.Utils.split_data(data, 0.3)
20 | training_data_len = len(training_data)
21 |
22 | training_data_last = training_data[1][-1]
23 | training_data_target = data[1][training_data_len - 1]
24 | testing_data_first = testing_data[0][0]
25 | testing_data_target = data[0][training_data_len]
26 | self.assertEqual(training_data_last, training_data_target)
27 | self.assertEqual(testing_data_first, testing_data_target)
28 |
29 | def _test_get_best_params(self):
30 | al_results = []
31 |
32 | for i in range(10):
33 | al_result = dict(
34 | params=None,
35 | total_return_rate=np.random.randint(1, 10),
36 | max_drawdown=0,
37 | max_drawdown_period=0
38 | )
39 | al_results.append(al_result)
40 |
41 | best_al_result = bsu.Utils.get_best_params(al_results)
42 |
43 | best_return_rate = best_al_result.get('total_return_rate')
44 | for i in range(10):
45 | self.assertGreaterEqual(best_return_rate, al_results[i].get('total_return_rate'))
46 |
--------------------------------------------------------------------------------
/train_main.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | import backtradercn.strategies.ma as bsm
3 | import backtradercn.tasks as btasks
4 | from backtradercn.libs.log import get_logger
5 | from backtradercn.settings import settings as conf
6 | from backtradercn.libs import models
7 |
8 |
9 | logger = get_logger(__name__)
10 |
11 |
12 | def train(stock):
13 | """
14 | Run training tasks via multiprocessing and save training params to arctic store.
15 | :param stock: str, stock code
16 | :return: None
17 | """
18 |
19 | task = btasks.Task(bsm.MATrendStrategy, stock)
20 | params = task.train()
21 | # write stock params to MongoDB
22 | symbol = conf.STRATEGY_PARAMS_MA_SYMBOL
23 | models.save_training_params(symbol, params)
24 |
25 |
26 | def main(stock_pools):
27 | """
28 | Get all stocks and train params for each stock.
29 | :param stock_pools: list, the stock code list.
30 | :return: None
31 | """
32 |
33 | for stock in stock_pools:
34 | train(stock)
35 |
36 |
37 | if __name__ == '__main__':
38 | # create params library if not exist
39 | models.get_or_create_library(conf.STRATEGY_PARAMS_LIBNAME)
40 |
41 | cn_stocks = models.get_cn_stocks()
42 | main(cn_stocks)
43 |
44 | # training 时会写数据到 `conf.DAILY_STOCK_ALERT_LIBNAME`
45 | models.drop_library(conf.DAILY_STOCK_ALERT_LIBNAME)
46 |
--------------------------------------------------------------------------------