├── LICENSE ├── README.md ├── setup.py ├── stockholm ├── __init__.py ├── main.py ├── mongo_scripts.txt ├── option.py ├── portfolio_test.txt └── stockholm.py └── test └── __init__.py /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | {description} 294 | Copyright (C) {year} {fullname} 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | {signature of Ty Coon}, 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | 341 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Stockholm 2 | ======= 3 | 4 | #### 一个股票数据(沪深)爬虫和选股策略测试框架,数据基于雅虎YQL和新浪财经。 5 | * 根据选定的日期范围抓取所有沪深两市股票的行情数据。 6 | * 根据指定的选股策略和指定的日期进行选股测试。 7 | * 计算选股测试实际结果(包括与沪深300指数比较)。 8 | * 保存数据到JSON文件、CSV文件。 9 | * 支持使用表达式定义选股策略。 10 | * 支持多线程处理。 11 | 12 | 能干什么 13 | ------------- 14 | 如果你想基于沪深股市行情数据进行一些工作,它可以帮助你导出指定时间范围内所有沪深A股的行情数据和一些技术指标,包括代码、名称、开盘、收盘、最高、最低、成交量、均线、KDJ等。
15 | 如果你对于技术分析有兴趣,它可以帮你根据你自定义的策略在所有沪深A股的范围内进行选股,并回测选股策略的收益情况(详细说明后面会有)。这样就能够非常方便快捷地测试和调整基于技术分析的选股策略。
16 | 17 | 还有些什么问题 18 | ------------- 19 | 行情数据目前来源于雅虎YQL,每日数据的更新时间不太稳定(一般在中国时间午夜左右)。
20 | 目前支持的技术指标还不多,还有一些指标如MACD和BOLL后续会增加。
21 | 在回测中,如果有在选定时间内发生过除权的股票,收益计算会有问题。
22 | 导出格式目前只支持CSV和JSON文本。MongoDB和MySQL会考虑后续加入。
23 | 24 | 环境 25 | ------------- 26 | Python 3.4以上
27 | [Requests](http://www.python-requests.org/en/latest/)
28 | [PyMongo](http://api.mongodb.org/python/current/installation.html)
29 | OSX和CentOS已测。Windows尚未测试,输出路径可能有问题。
30 | 31 | ```shell 32 | pip install requests 33 | pip install pymongo 34 | ``` 35 | 36 | 使用 37 | ------------- 38 | ```shell 39 | python main.py [-h] [--reload {Y,N}] [--portfolio {Y,N}] 40 | [--output {json,csv,all}] [--storepath PATH] [--thread NUM] 41 | [--startdate yyyy-MM-dd] [--enddate yyyy-MM-dd] 42 | [--targetdate yyyy-MM-dd] [--testrange NUM] [--testfile PATH] 43 | ``` 44 | 45 | 可选参数 46 | ------------- 47 | ```shell 48 | -h, --help 查看帮助并退出 49 | --reload {Y,N} 是否重新抓取股票数据,默认值:Y 50 | --portfolio {Y,N} 是否生成选股测试结果,默认值:N 51 | --output {json,csv,all} 输出文件格式,默认值:json 52 | --charset {utf-8,gbk} 输出文件编码,默认值:utf-8 53 | --storepath PATH 输出文件路径,默认值:~/tmp/stockholm_export 54 | --thread NUM 线程数,默认值:10 55 | --startdate yyyy-MM-dd 抓取数据的开始日期,默认值:当前系统日期-100天(例如2015-01-01) 56 | --enddate yyyy-MM-dd 抓取数据的结束日期,默认值:当前系统日期 57 | --targetdate yyyy-MM-dd 测试选股策略的目标日期,默认值:当前系统日期 58 | --testrange NUM 测试日期范围天数,默认值:50 59 | --testfile PATH 测试文件路径,默认值:./portfolio_test.txt 60 | ``` 61 | 62 | 可用数据/格式 63 | ------------- 64 | ### 行情数据: 65 | ```shell 66 | [ 67 | {"Symbol": "600000.SS", 68 | "Name": "浦发银行", 69 | "Data": [ 70 | {"Vol_Change": null, "MA_10": null, "Date": "2015-03-26", "High": 15.58, "Open": 15.15, "Volume": 282340700, "Close": 15.36, "Change": null, "Low": 15.04}, 71 | {"Vol_Change": -0.22726, "MA_10": null, "Date": "2015-03-27", "High": 15.55, "Open": 15.32, "Volume": 218174900, "Close": 15.36, "Change": 0.0, "Low": 15.17} 72 | ] 73 | } 74 | ] 75 | ``` 76 | Date(日期); Open(开盘价); Close(收盘价); High(当日最高); Low(当日最低); Change(价格变化%); Volume(成交量); Vol_Change(成交量较前日变化); MA_5(5日均线); MA_10(10日均线); MA_20(20日均线); MA_30(30日均线); KDJ_K(KDJ指标K); KDJ_D(KDJ指标D); KDJ_J(KDJ指标J);
77 | 以上数据都可以用于制定选股策略,后面会介绍具体方法。
78 | 79 | ### 选股策略测试数据: 80 | ```shell 81 | [ 82 | { 83 | "Symbol": "600000.SS", 84 | "Name": "浦发银行", 85 | "Close": 14.51, 86 | "Change": 0.06456, 87 | "Vol_Change": 2.39592, 88 | "MA_10": 14.171, 89 | "KDJ_K": 37.65, 90 | "KDJ_D": 33.427, 91 | "KDJ_J": 46.096, 92 | "Data": [ 93 | {"Day_5_Differ": 0.01869, "Day_9_Profit": 0.08546, "Day_1_Profit": -0.02826, "Day_1_INDEX_Change": -0.00484, "Day_3_INDEX_Change": 0.01557, "Day_5_INDEX_Change": 0.04747, "Day_3_Differ": 0.02647, "Day_9_INDEX_Change": 0.1003, "Day_5_Profit": 0.06616, "Day_3_Profit": 0.04204, "Day_1_Differ": -0.02342, "Day_9_Differ": -0.014840000000000006} 94 | ] 95 | } 96 | ] 97 | ``` 98 | Close(收盘价); Change(价格变化%); Vol_Change(成交量较前日变化); MA_10(十天均价); KDJ_K(KDJ指标K); KDJ_D(KDJ指标D); KDJ_J(KDJ指标J); Day_1_Profit(后一天利润率%); Day_1_INDEX_Change(后一天沪深300变化率%); Day_1_Differ(后一天相对利润率%——即利润率-沪深300变化率); Day_n_Profit(后n天利润率%); Day_n_INDEX_Change(后n天沪深300变化率%); Day_n_Differ(后n天相对利润率%——即利润率-沪深300变化率); 99 | 100 | 行情数据抓取范例 101 | ------------- 102 | 获取从当前日期倒推100天(不是100个交易日)的所有沪深股票行情数据。
103 | 执行完成后,数据在当前用户文件夹下./tmp/stockholm_export/stockholm_export.json
104 | ```shell 105 | python main.py 106 | ``` 107 | 如果想导出csv文件 108 | ```shell 109 | python main.py --output=csv 110 | ``` 111 | 112 | 选股策略测试范例 113 | ------------- 114 | 选股策略范例文件内容如下(包括在源码中)
115 | 选股策略"method 1"是:前前个交易日的KDJ指标的J值小于20+前个交易日的KDJ指标J值小于20+当前交易日的KDJ指标J值比上个交易日大40+当前交易日成交量变化大于100%
116 | ```shell 117 | ## Portfolio selection methodology sample file 118 | 119 | [method 1]:day(-2).{KDJ_J}<20 and day(-1).{KDJ_J}<20 and day(0).{KDJ_J}-day(-1).{KDJ_J}>=40 and day(0).{Vol_Change}>=1 120 | ``` 121 | 以当前系统日期为目标日期进行倒推60天得选股策略测试。
122 | 不重新抓取行情数据并执行测试命令。
123 | 执行完毕后,会将测试结果按照每天一个文件的方式保存在./tmp/stockholm_export/。
124 | 文件名格式为result_yyyy-MM-dd.json(例如result_2015-03-24.json)。
125 | ```shell 126 | python main.py --reload=N --portfolio=Y 127 | ``` 128 | 通过更改测试文件中的选股策略公式,可以随意测试指定时间范围内的选股效果。
129 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liqq1228/stockholm/482a04f7358313316e7968e574a18eeef52fc637/setup.py -------------------------------------------------------------------------------- /stockholm/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liqq1228/stockholm/482a04f7358313316e7968e574a18eeef52fc637/stockholm/__init__.py -------------------------------------------------------------------------------- /stockholm/main.py: -------------------------------------------------------------------------------- 1 | from stockholm import Stockholm 2 | import option 3 | import os 4 | 5 | def checkFoldPermission(path): 6 | if(path == 'USER_HOME/tmp/stockholm_export'): 7 | path = os.path.expanduser('~') + '/tmp/stockholm_export' 8 | try: 9 | if not os.path.exists(path): 10 | os.makedirs(path) 11 | else: 12 | txt = open(path + os.sep + "test.txt","w") 13 | txt.write("test") 14 | txt.close() 15 | os.remove(path + os.sep + "test.txt") 16 | 17 | except Exception as e: 18 | print(e) 19 | return False 20 | return True 21 | 22 | def main(): 23 | args = option.parser.parse_args() 24 | if not checkFoldPermission(args.store_path): 25 | print('\nPermission denied: %s' % args.store_path) 26 | print('Please make sure you have the permission to save the data!\n') 27 | else: 28 | print('Stockholm is starting...\n') 29 | stockh = Stockholm(args) 30 | stockh.run() 31 | print('Stockholm is done...\n') 32 | 33 | if __name__ == '__main__': 34 | main() 35 | -------------------------------------------------------------------------------- /stockholm/mongo_scripts.txt: -------------------------------------------------------------------------------- 1 | use stockholm 2 | 3 | db.counters.insert( 4 | { 5 | _id: "method_id", 6 | seq: 0 7 | } 8 | ) 9 | 10 | function getNextSequence(name) { 11 | var ret = db.counters.findAndModify( 12 | { 13 | query: { _id: name }, 14 | update: { $inc: { seq: 1 } }, 15 | new: true 16 | } 17 | ); 18 | 19 | return ret.seq; 20 | } 21 | 22 | db.testing_method.insert({"method_id": getNextSequence("method_id"), "name":"测试方法1", "desc":"这是一个测试方法。", "user_name":"Stockholm", "user_id":"dtnium@gmail.com", "creation_date": new Date(), "modification_date": new Date(), "method":"day(-2).{KDJ_J}<20 and day(-1).{KDJ_J}<20 and day(0).{KDJ_J}-day(-1).{KDJ_J}>=40 and day(0).{Vol_Change}>=1 and day(0).{MA_10}*1.05>day(0).{Close}"}) 23 | 24 | db.testing_method.insert({"method_id": getNextSequence("method_id"), "name":"测试方法2", "desc":"这是一个测试方法。", "user_name":"Stockholm", "user_id":"dtnium@gmail.com", "creation_date": new Date(), "modification_date": new Date(), "method":"day(-2).{KDJ_J}-day(-1).{KDJ_J}>20 and day(0).{KDJ_J}-day(-1).{KDJ_J}>20 and day(-1).{KDJ_J}<50 and day(0).{Vol_Change}<=1"}) 25 | 26 | -------------------------------------------------------------------------------- /stockholm/option.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import datetime 3 | 4 | def get_date_str(offset): 5 | if(offset is None): 6 | offset = 0 7 | date_str = (datetime.datetime.today() + datetime.timedelta(days=offset)).strftime("%Y-%m-%d") 8 | return date_str 9 | 10 | _default = dict( 11 | reload_data = 'Y', 12 | gen_portfolio = 'N', 13 | output_type = 'json', 14 | charset = 'utf-8', 15 | test_date_range = 60, 16 | start_date = get_date_str(-90), 17 | end_date = get_date_str(None), 18 | target_date = get_date_str(None), 19 | store_path = 'USER_HOME/tmp/stockholm_export', 20 | thread = 10, 21 | testfile_path = './portfolio_test.txt', 22 | db_name = 'stockholm', 23 | methods = '' 24 | ) 25 | 26 | parser = argparse.ArgumentParser(description='A stock crawler and portfolio testing framework.') 27 | 28 | parser.add_argument('--reload', type=str, default=_default['reload_data'], dest='reload_data', help='Reload the stock data or not (Y/N), Default: %s' % _default['reload_data']) 29 | 30 | parser.add_argument('--portfolio', type=str, default=_default['gen_portfolio'], dest='gen_portfolio', help='Generate the portfolio or not (Y/N), Default: %s' % _default['gen_portfolio']) 31 | 32 | parser.add_argument('--output', type=str, default=_default['output_type'], dest='output_type', help='Data output type (json/csv/all), Default: %s' % _default['output_type']) 33 | 34 | parser.add_argument('--charset', type=str, default=_default['charset'], dest='charset', help='Data output charset (utf-8/gbk), Default: %s' % _default['charset']) 35 | 36 | parser.add_argument('--testrange', type=int, default=_default['test_date_range'], dest='test_date_range', help='Test date range(days): %s' % _default['test_date_range']) 37 | 38 | parser.add_argument('--startdate', type=str, default=_default['start_date'], dest='start_date', help='Data loading start date, Default: %s' % _default['start_date']) 39 | 40 | parser.add_argument('--enddate', type=str, default=_default['end_date'], dest='end_date', help='Data loading end date, Default: %s' % _default['end_date']) 41 | 42 | parser.add_argument('--targetdate', type=str, default=_default['target_date'], dest='target_date', help='Portfolio generating target date, Default: %s' % _default['target_date']) 43 | 44 | parser.add_argument('--storepath', type=str, default=_default['store_path'], dest='store_path', help='Data file store path, Default: %s' % _default['store_path']) 45 | 46 | parser.add_argument('--thread', type=int, default=_default['thread'], dest='thread', help='Thread number, Default: %s' % _default['thread']) 47 | 48 | parser.add_argument('--testfile', type=str, default=_default['testfile_path'], dest='testfile_path', help='Portfolio test file path, Default: %s' % _default['testfile_path']) 49 | 50 | parser.add_argument('--dbname', type=str, default=_default['db_name'], dest='db_name', help='MongoDB DB name, Default: %s' % _default['db_name']) 51 | 52 | parser.add_argument('--methods', type=str, default=_default['methods'], dest='methods', help='Target methods for back testing, Default: %s' % _default['methods']) 53 | 54 | def main(): 55 | args = parser.parse_args() 56 | print(args) 57 | 58 | if __name__ == '__main__': 59 | main() 60 | -------------------------------------------------------------------------------- /stockholm/portfolio_test.txt: -------------------------------------------------------------------------------- 1 | ## Portfolio selection methodology sample file 2 | 3 | [测试方法1]:day(-2).{KDJ_J}<20 and day(-1).{KDJ_J}<20 and day(0).{KDJ_J}-day(-1).{KDJ_J}>=40 and day(0).{Vol_Change}>=1 and day(0).{MA_10}*1.05>day(0).{Close} 4 | 5 | [测试方法2]:day(-2).{KDJ_J}-day(-1).{KDJ_J}>20 and day(0).{KDJ_J}-day(-1).{KDJ_J}>20 and day(-1).{KDJ_J}<50 and day(0).{Vol_Change}<=1 6 | 7 | ##[测试方法3]:50]', val) 96 | val = re.sub(r'\.\{((-)?\w+)\}', r"['\g<1>']", val) 97 | return val 98 | 99 | def convert_null_check(self, exp): 100 | p = re.compile('\((-)?\d+...\w+\}') 101 | iterator = p.finditer(exp.replace('(0)', '(-0)')) 102 | array = [] 103 | for match in iterator: 104 | v = 'quote[\'Data\']' + match.group() 105 | v = re.sub(r'\(((-)?\d+)\)', r'[target_idx\g<1>]', v) 106 | v = re.sub(r'\.\{((-)?\w+)\}', r"['\g<1>']", v) 107 | v += ' is not None' 108 | array.append(v) 109 | val = ' and '.join(array) 110 | return val 111 | 112 | class KDJ(): 113 | def _avg(self, array): 114 | length = len(array) 115 | return sum(array)/length 116 | 117 | def _getMA(self, values, window): 118 | array = [] 119 | x = window 120 | while x <= len(values): 121 | curmb = 50 122 | if(x-window == 0): 123 | curmb = self._avg(values[x-window:x]) 124 | else: 125 | curmb = (array[-1]*2+values[x-1])/3 126 | array.append(round(curmb,3)) 127 | x += 1 128 | return array 129 | 130 | def _getRSV(self, arrays): 131 | rsv = [] 132 | x = 9 133 | while x <= len(arrays): 134 | high = max(map(lambda x: x['High'], arrays[x-9:x])) 135 | low = min(map(lambda x: x['Low'], arrays[x-9:x])) 136 | close = arrays[x-1]['Close'] 137 | rsv.append((close-low)/(high-low)*100) 138 | t = arrays[x-1]['Date'] 139 | x += 1 140 | return rsv 141 | 142 | def getKDJ(self, quote_data): 143 | if(len(quote_data) > 12): 144 | rsv = self._getRSV(quote_data) 145 | k = self._getMA(rsv,3) 146 | d = self._getMA(k,3) 147 | j = list(map(lambda x: round(3*x[0]-2*x[1],3), zip(k[2:], d))) 148 | 149 | for idx, data in enumerate(quote_data[0:12]): 150 | data['KDJ_K'] = None 151 | data['KDJ_D'] = None 152 | data['KDJ_J'] = None 153 | for idx, data in enumerate(quote_data[12:]): 154 | data['KDJ_K'] = k[2:][idx] 155 | data['KDJ_D'] = d[idx] 156 | if(j[idx] > 100): 157 | data['KDJ_J'] = 100 158 | elif(j[idx] < 0): 159 | data['KDJ_J'] = 0 160 | else: 161 | data['KDJ_J'] = j[idx] 162 | 163 | return quote_data 164 | 165 | def load_all_quote_symbol(self): 166 | print("load_all_quote_symbol start..." + "\n") 167 | 168 | start = timeit.default_timer() 169 | 170 | all_quotes = [] 171 | 172 | all_quotes.append(self.sh000001) 173 | all_quotes.append(self.sz399001) 174 | all_quotes.append(self.sh000300) 175 | ## all_quotes.append(self.sz399005) 176 | ## all_quotes.append(self.sz399006) 177 | 178 | try: 179 | count = 1 180 | while (count < 100): 181 | para_val = '[["hq","hs_a","",0,' + str(count) + ',500]]' 182 | r_params = {'__s': para_val} 183 | r = requests.get(self.all_quotes_url, params=r_params) 184 | if(len(r.json()[0]['items']) == 0): 185 | break 186 | for item in r.json()[0]['items']: 187 | quote = {} 188 | code = item[0] 189 | name = item[2] 190 | ## convert quote code 191 | if(code.find('sh') > -1): 192 | code = code[2:] + '.SS' 193 | elif(code.find('sz') > -1): 194 | code = code[2:] + '.SZ' 195 | ## convert quote code end 196 | quote['Symbol'] = code 197 | quote['Name'] = name 198 | all_quotes.append(quote) 199 | count += 1 200 | except Exception as e: 201 | print("Error: Failed to load all stock symbol..." + "\n") 202 | print(e) 203 | 204 | print("load_all_quote_symbol end... time cost: " + str(round(timeit.default_timer() - start)) + "s" + "\n") 205 | return all_quotes 206 | 207 | def load_quote_info(self, quote, is_retry): 208 | print("load_quote_info start..." + "\n") 209 | 210 | start = timeit.default_timer() 211 | 212 | if(quote is not None and quote['Symbol'] is not None): 213 | yquery = 'select * from yahoo.finance.quotes where symbol = "' + quote['Symbol'].lower() + '"' 214 | r_params = {'q': yquery, 'format': 'json', 'env': 'http://datatables.org/alltables.env'} 215 | r = requests.get(self.yql_url, params=r_params) 216 | ## print(r.url) 217 | ## print(r.text) 218 | rjson = r.json() 219 | try: 220 | quote_info = rjson['query']['results']['quote'] 221 | quote['LastTradeDate'] = quote_info['LastTradeDate'] 222 | quote['LastTradePrice'] = quote_info['LastTradePriceOnly'] 223 | quote['PreviousClose'] = quote_info['PreviousClose'] 224 | quote['Open'] = quote_info['Open'] 225 | quote['DaysLow'] = quote_info['DaysLow'] 226 | quote['DaysHigh'] = quote_info['DaysHigh'] 227 | quote['Change'] = quote_info['Change'] 228 | quote['ChangeinPercent'] = quote_info['ChangeinPercent'] 229 | quote['Volume'] = quote_info['Volume'] 230 | quote['MarketCap'] = quote_info['MarketCapitalization'] 231 | quote['StockExchange'] = quote_info['StockExchange'] 232 | 233 | except Exception as e: 234 | print("Error: Failed to load stock info... " + quote['Symbol'] + "/" + quote['Name'] + "\n") 235 | print(e + "\n") 236 | if(not is_retry): 237 | time.sleep(1) 238 | load_quote_info(quote, True) ## retry once for network issue 239 | 240 | ## print(quote) 241 | print("load_quote_info end... time cost: " + str(round(timeit.default_timer() - start)) + "s" + "\n") 242 | return quote 243 | 244 | def load_all_quote_info(self, all_quotes): 245 | print("load_all_quote_info start...") 246 | 247 | start = timeit.default_timer() 248 | for idx, quote in enumerate(all_quotes): 249 | print("#" + str(idx + 1)) 250 | load_quote_info(quote, False) 251 | 252 | print("load_all_quote_info end... time cost: " + str(round(timeit.default_timer() - start)) + "s") 253 | return all_quotes 254 | 255 | def load_quote_data(self, quote, start_date, end_date, is_retry, counter): 256 | ## print("load_quote_data start..." + "\n") 257 | 258 | start = timeit.default_timer() 259 | 260 | if(quote is not None and quote['Symbol'] is not None): 261 | yquery = 'select * from yahoo.finance.historicaldata where symbol = "' + quote['Symbol'].upper() + '" and startDate = "' + start_date + '" and endDate = "' + end_date + '"' 262 | r_params = {'q': yquery, 'format': 'json', 'env': 'http://datatables.org/alltables.env'} 263 | try: 264 | r = requests.get(self.yql_url, params=r_params) 265 | ## print(r.url) 266 | ## print(r.text) 267 | rjson = r.json() 268 | quote_data = rjson['query']['results']['quote'] 269 | quote_data.reverse() 270 | quote['Data'] = quote_data 271 | if(not is_retry): 272 | counter.append(1) 273 | 274 | except: 275 | print("Error: Failed to load stock data... " + quote['Symbol'] + "/" + quote['Name'] + "\n") 276 | if(not is_retry): 277 | time.sleep(2) 278 | self.load_quote_data(quote, start_date, end_date, True, counter) ## retry once for network issue 279 | 280 | print("load_quote_data " + quote['Symbol'] + "/" + quote['Name'] + " end..." + "\n") 281 | ## print("time cost: " + str(round(timeit.default_timer() - start)) + "s." + "\n") 282 | ## print("total count: " + str(len(counter)) + "\n") 283 | return quote 284 | 285 | def load_all_quote_data(self, all_quotes, start_date, end_date): 286 | print("load_all_quote_data start..." + "\n") 287 | 288 | start = timeit.default_timer() 289 | 290 | counter = [] 291 | mapfunc = partial(self.load_quote_data, start_date=start_date, end_date=end_date, is_retry=False, counter=counter) 292 | pool = ThreadPool(self.thread) 293 | pool.map(mapfunc, all_quotes) ## multi-threads executing 294 | pool.close() 295 | pool.join() 296 | 297 | print("load_all_quote_data end... time cost: " + str(round(timeit.default_timer() - start)) + "s" + "\n") 298 | return all_quotes 299 | 300 | def data_process(self, all_quotes): 301 | print("data_process start..." + "\n") 302 | 303 | kdj = self.KDJ() 304 | start = timeit.default_timer() 305 | 306 | for quote in all_quotes: 307 | 308 | if(quote['Symbol'].startswith('300')): 309 | quote['Type'] = '创业板' 310 | elif(quote['Symbol'].startswith('002')): 311 | quote['Type'] = '中小板' 312 | else: 313 | quote['Type'] = '主板' 314 | 315 | if('Data' in quote): 316 | try: 317 | temp_data = [] 318 | for quote_data in quote['Data']: 319 | if(quote_data['Volume'] != '000' or quote_data['Symbol'] in self.index_array): 320 | d = {} 321 | d['Open'] = float(quote_data['Open']) 322 | ## d['Adj_Close'] = float(quote_data['Adj_Close']) 323 | d['Close'] = float(quote_data['Close']) 324 | d['High'] = float(quote_data['High']) 325 | d['Low'] = float(quote_data['Low']) 326 | d['Volume'] = int(quote_data['Volume']) 327 | d['Date'] = quote_data['Date'] 328 | temp_data.append(d) 329 | quote['Data'] = temp_data 330 | except KeyError as e: 331 | print("Data Process: Key Error") 332 | print(e) 333 | print(quote) 334 | 335 | ## calculate Change / 5 10 20 30 Day MA 336 | for quote in all_quotes: 337 | if('Data' in quote): 338 | try: 339 | for i, quote_data in enumerate(quote['Data']): 340 | if(i > 0): 341 | quote_data['Change'] = self.get_profit_rate(quote['Data'][i-1]['Close'], quote_data['Close']) 342 | quote_data['Vol_Change'] = self.get_profit_rate(quote['Data'][i-1]['Volume'], quote_data['Volume']) 343 | else: 344 | quote_data['Change'] = None 345 | quote_data['Vol_Change'] = None 346 | 347 | last_5_array = [] 348 | last_10_array = [] 349 | last_20_array = [] 350 | last_30_array = [] 351 | for i, quote_data in enumerate(quote['Data']): 352 | last_5_array.append(quote_data['Close']) 353 | last_10_array.append(quote_data['Close']) 354 | last_20_array.append(quote_data['Close']) 355 | last_30_array.append(quote_data['Close']) 356 | quote_data['MA_5'] = None 357 | quote_data['MA_10'] = None 358 | quote_data['MA_20'] = None 359 | quote_data['MA_30'] = None 360 | 361 | if(i < 4): 362 | continue 363 | if(len(last_5_array) == 5): 364 | last_5_array.pop(0) 365 | quote_data['MA_5'] = self.get_MA(last_5_array) 366 | 367 | if(i < 9): 368 | continue 369 | if(len(last_10_array) == 10): 370 | last_10_array.pop(0) 371 | quote_data['MA_10'] = self.get_MA(last_10_array) 372 | 373 | if(i < 19): 374 | continue 375 | if(len(last_20_array) == 20): 376 | last_20_array.pop(0) 377 | quote_data['MA_20'] = self.get_MA(last_20_array) 378 | 379 | if(i < 29): 380 | continue 381 | if(len(last_30_array) == 30): 382 | last_30_array.pop(0) 383 | quote_data['MA_30'] = self.get_MA(last_30_array) 384 | 385 | 386 | except KeyError as e: 387 | print("Key Error") 388 | print(e) 389 | print(quote) 390 | 391 | ## calculate KDJ 392 | for quote in all_quotes: 393 | if('Data' in quote): 394 | try: 395 | kdj.getKDJ(quote['Data']) 396 | except KeyError as e: 397 | print("Key Error") 398 | print(e) 399 | print(quote) 400 | 401 | print("data_process end... time cost: " + str(round(timeit.default_timer() - start)) + "s" + "\n") 402 | 403 | def data_export(self, all_quotes, export_type_array, file_name): 404 | 405 | start = timeit.default_timer() 406 | directory = self.export_folder 407 | if(file_name is None): 408 | file_name = self.export_file_name 409 | if not os.path.exists(directory): 410 | os.makedirs(directory) 411 | 412 | if(all_quotes is None or len(all_quotes) == 0): 413 | print("no data to export...\n") 414 | 415 | if('json' in export_type_array): 416 | print("start export to JSON file...\n") 417 | f = io.open(directory + '/' + file_name + '.json', 'w', encoding=self.charset) 418 | json.dump(all_quotes, f, ensure_ascii=False) 419 | 420 | if('csv' in export_type_array): 421 | print("start export to CSV file...\n") 422 | columns = [] 423 | if(all_quotes is not None and len(all_quotes) > 0): 424 | columns = self.get_columns(all_quotes[0]) 425 | writer = csv.writer(open(directory + '/' + file_name + '.csv', 'w', encoding=self.charset)) 426 | writer.writerow(columns) 427 | 428 | for quote in all_quotes: 429 | if('Data' in quote): 430 | for quote_data in quote['Data']: 431 | try: 432 | line = [] 433 | for column in columns: 434 | if(column.find('data.') > -1): 435 | if(column[5:] in quote_data): 436 | line.append(quote_data[column[5:]]) 437 | else: 438 | line.append(quote[column]) 439 | writer.writerow(line) 440 | except Exception as e: 441 | print(e) 442 | print("write csv error: " + quote) 443 | 444 | if('mongo' in export_type_array): 445 | print("start export to MongoDB...\n") 446 | 447 | print("export is complete... time cost: " + str(round(timeit.default_timer() - start)) + "s" + "\n") 448 | 449 | def file_data_load(self): 450 | print("file_data_load start..." + "\n") 451 | 452 | start = timeit.default_timer() 453 | directory = self.export_folder 454 | file_name = self.export_file_name 455 | 456 | all_quotes_data = [] 457 | f = io.open(directory + '/' + file_name + '.json', 'r', encoding='utf-8') 458 | json_str = f.readline() 459 | all_quotes_data = json.loads(json_str) 460 | 461 | print("file_data_load end... time cost: " + str(round(timeit.default_timer() - start)) + "s" + "\n") 462 | return all_quotes_data 463 | 464 | def check_date(self, all_quotes, date): 465 | 466 | is_date_valid = False 467 | for quote in all_quotes: 468 | if(quote['Symbol'] in self.index_array and 'Data' in quote): 469 | for quote_data in quote['Data']: 470 | if(quote_data['Date'] == date): 471 | is_date_valid = True 472 | if not is_date_valid: 473 | print(date + " is not valid...\n") 474 | return is_date_valid 475 | 476 | def quote_pick(self, all_quotes, target_date, methods): 477 | print("quote_pick start..." + "\n") 478 | 479 | start = timeit.default_timer() 480 | 481 | results = [] 482 | data_issue_count = 0 483 | 484 | for quote in all_quotes: 485 | try: 486 | if(quote['Symbol'] in self.index_array): 487 | results.append(quote) 488 | continue 489 | 490 | target_idx = None 491 | for idx, quote_data in enumerate(quote['Data']): 492 | if(quote_data['Date'] == target_date): 493 | target_idx = idx 494 | if(target_idx is None): 495 | ## print(quote['Name'] + " data is not available at this date..." + "\n") 496 | data_issue_count+=1 497 | continue 498 | 499 | ## pick logic ## 500 | valid = False 501 | for method in methods: 502 | ## print(method['name']) 503 | ## null_check = eval(method['null_check']) 504 | try: 505 | value_check = eval(method['value_check']) 506 | if(value_check): 507 | quote['Method'] = method['name'] 508 | results.append(quote) 509 | valid = True 510 | break 511 | except: 512 | valid = False 513 | if(valid): 514 | continue 515 | 516 | ## pick logic end ## 517 | 518 | except KeyError as e: 519 | ## print("KeyError: " + quote['Name'] + " data is not available..." + "\n") 520 | data_issue_count+=1 521 | 522 | print("quote_pick end... time cost: " + str(round(timeit.default_timer() - start)) + "s" + "\n") 523 | print(str(data_issue_count) + " quotes of data is not available...\n") 524 | return results 525 | 526 | def profit_test(self, selected_quotes, target_date): 527 | print("profit_test start..." + "\n") 528 | 529 | start = timeit.default_timer() 530 | 531 | results = [] 532 | INDEX = None 533 | INDEX_idx = 0 534 | 535 | for quote in selected_quotes: 536 | if(quote['Symbol'] == self.sh000300['Symbol']): 537 | INDEX = quote 538 | for idx, quote_data in enumerate(quote['Data']): 539 | if(quote_data['Date'] == target_date): 540 | INDEX_idx = idx 541 | break 542 | 543 | for quote in selected_quotes: 544 | target_idx = None 545 | 546 | if(quote['Symbol'] in self.index_array): 547 | continue 548 | 549 | for idx, quote_data in enumerate(quote['Data']): 550 | if(quote_data['Date'] == target_date): 551 | target_idx = idx 552 | if(target_idx is None): 553 | print(quote['Name'] + " data is not available for testing..." + "\n") 554 | continue 555 | 556 | test = {} 557 | test['Name'] = quote['Name'] 558 | test['Symbol'] = quote['Symbol'] 559 | test['Method'] = quote['Method'] 560 | test['Type'] = quote['Type'] 561 | if('KDJ_K' in quote['Data'][target_idx]): 562 | test['KDJ_K'] = quote['Data'][target_idx]['KDJ_K'] 563 | test['KDJ_D'] = quote['Data'][target_idx]['KDJ_D'] 564 | test['KDJ_J'] = quote['Data'][target_idx]['KDJ_J'] 565 | test['Close'] = quote['Data'][target_idx]['Close'] 566 | test['Change'] = quote['Data'][target_idx]['Change'] 567 | test['Vol_Change'] = quote['Data'][target_idx]['Vol_Change'] 568 | test['MA_5'] = quote['Data'][target_idx]['MA_5'] 569 | test['MA_10'] = quote['Data'][target_idx]['MA_10'] 570 | test['MA_20'] = quote['Data'][target_idx]['MA_20'] 571 | test['MA_30'] = quote['Data'][target_idx]['MA_30'] 572 | test['Data'] = [{}] 573 | 574 | for i in range(1,11): 575 | if(target_idx+i >= len(quote['Data'])): 576 | print(quote['Name'] + " data is not available for " + str(i) + " day testing..." + "\n") 577 | break 578 | 579 | day2day_profit = self.get_profit_rate(quote['Data'][target_idx]['Close'], quote['Data'][target_idx+i]['Close']) 580 | test['Data'][0]['Day_' + str(i) + '_Profit'] = day2day_profit 581 | if(INDEX_idx+i < len(INDEX['Data'])): 582 | day2day_INDEX_change = self.get_profit_rate(INDEX['Data'][INDEX_idx]['Close'], INDEX['Data'][INDEX_idx+i]['Close']) 583 | test['Data'][0]['Day_' + str(i) + '_INDEX_Change'] = day2day_INDEX_change 584 | test['Data'][0]['Day_' + str(i) + '_Differ'] = day2day_profit-day2day_INDEX_change 585 | 586 | results.append(test) 587 | 588 | print("profit_test end... time cost: " + str(round(timeit.default_timer() - start)) + "s" + "\n") 589 | return results 590 | 591 | def data_load(self, start_date, end_date, output_types): 592 | all_quotes = self.load_all_quote_symbol() 593 | print("total " + str(len(all_quotes)) + " quotes are loaded..." + "\n") 594 | all_quotes = all_quotes 595 | ## self.load_all_quote_info(all_quotes) 596 | self.load_all_quote_data(all_quotes, start_date, end_date) 597 | self.data_process(all_quotes) 598 | 599 | self.data_export(all_quotes, output_types, None) 600 | 601 | def data_test(self, target_date, test_range, output_types): 602 | ## loading test methods 603 | methods = [] 604 | path = self.testfile_path 605 | 606 | ## from mongodb 607 | if(path == 'mongodb'): 608 | print("Load testing methods from Mongodb...\n") 609 | client = MongoClient(self.mongo_url, self.mongo_port) 610 | db = client[self.database_name] 611 | col = db[self.collection_name] 612 | q = None 613 | if(len(self.methods) > 0): 614 | applied_methods = list(map(int, self.methods.split(','))) 615 | q = {"method_id": {"$in": applied_methods}} 616 | for doc in col.find(q, ['name','desc','method']): 617 | print(doc) 618 | m = {'name': doc['name'], 'value_check': self.convert_value_check(doc['method'])} 619 | methods.append(m) 620 | 621 | ## from test file 622 | else: 623 | if not os.path.exists(path): 624 | print("Portfolio test file is not existed, testing is aborted...\n") 625 | return 626 | f = io.open(path, 'r', encoding='utf-8') 627 | for line in f: 628 | if(line.startswith('##') or len(line.strip()) == 0): 629 | continue 630 | line = line.strip().strip('\n') 631 | name = line[line.find('[')+1:line.find(']:')] 632 | value = line[line.find(']:')+2:] 633 | m = {'name': name, 'value_check': self.convert_value_check(value)} 634 | methods.append(m) 635 | 636 | if(len(methods) == 0): 637 | print("No method is loaded, testing is aborted...\n") 638 | return 639 | 640 | ## portfolio testing 641 | all_quotes = self.file_data_load() 642 | target_date_time = datetime.datetime.strptime(target_date, "%Y-%m-%d") 643 | for i in range(test_range): 644 | date = (target_date_time - datetime.timedelta(days=i)).strftime("%Y-%m-%d") 645 | is_date_valid = self.check_date(all_quotes, date) 646 | if is_date_valid: 647 | selected_quotes = self.quote_pick(all_quotes, date, methods) 648 | res = self.profit_test(selected_quotes, date) 649 | self.data_export(res, output_types, 'result_' + date) 650 | 651 | def run(self): 652 | ## output types 653 | output_types = [] 654 | if(self.output_type == "json"): 655 | output_types.append("json") 656 | elif(self.output_type == "csv"): 657 | output_types.append("csv") 658 | elif(self.output_type == "all"): 659 | output_types = ["json", "csv"] 660 | 661 | ## loading stock data 662 | if(self.reload_data == 'Y'): 663 | print("Start loading stock data...\n") 664 | self.data_load(self.start_date, self.end_date, output_types) 665 | 666 | ## test & generate portfolio 667 | if(self.gen_portfolio == 'Y'): 668 | print("Start portfolio testing...\n") 669 | self.data_test(self.target_date, self.test_date_range, output_types) 670 | 671 | 672 | -------------------------------------------------------------------------------- /test/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/liqq1228/stockholm/482a04f7358313316e7968e574a18eeef52fc637/test/__init__.py --------------------------------------------------------------------------------