├── .gitignore ├── LICENSE ├── README.md ├── calcu_3year_average_pe.py ├── finance2018.7z ├── generate_stock_report.py ├── get_new_company_in_pool.py └── requirements.txt /.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 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | .idea/ 62 | .DS_Store 63 | "2017-06-09\350\202\241\347\245\250\344\273\267\346\240\274.csv" 64 | "\350\202\241\347\245\250\345\210\227\350\241\2502017-06-09.csv" 65 | "\350\264\242\345\212\241\346\225\260\346\215\2562016/" 66 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # chinese-stock-Financial-Index 2 | 计算中国A股所有股票的3年平均财务指标,并可以按照3年平均市盈率和最近5年ROE过滤股票 3 | 4 | 使用前提: 5 | 1. 安装python3.6或者更高版本 6 | 1. 在当前目录创建python虚拟环境,运行命令 pyvenv venv 7 | 2. 安装依赖库,在当前目录打开命令行,输入 pip install -r requirement。 8 | 9 | 10 | 使用方法 11 | 1. 解压'finance2018.7z'文件到当前文件夹,解压后为finance2018文件夹,包含所有a股公司到2018年的财务数据 12 | 2. 运行calcu_3year_average_pe.py 通过3年平均收益率筛选股票,默认为市盈率范围为2-20,可以修改。 13 | 生成类似 '2018-06-09-3年平均市盈率在2和20之间的公司.xlsx'文件名的文件,里面包含筛选出来的公司。 14 | 直接用excel打开即可查看 -------------------------------------------------------------------------------- /calcu_3year_average_pe.py: -------------------------------------------------------------------------------- 1 | import os 2 | import urllib.request 3 | from datetime import datetime 4 | from time import sleep 5 | 6 | import pandas as pd 7 | import tushare as ts 8 | from dateutil.relativedelta import relativedelta 9 | 10 | current_folder = os.path.dirname(os.path.abspath(__file__)) 11 | 12 | calcu_average_profit_end_year = 2018 # 计算平均利润的截止年,包括该年 13 | caiwu_folder = os.path.join(current_folder, 14 | 'finance%s' % calcu_average_profit_end_year) 15 | 16 | today = str(datetime.now())[:10] 17 | 18 | 19 | def three_year_ago(): 20 | return int( 21 | (datetime.now().date() - relativedelta(years=3)).strftime('%Y%m%d')) 22 | 23 | 24 | def create_folder_if_need(path): 25 | if not os.path.exists(path): # 如果该文件夹不存在,创建文件夹 26 | os.makedirs(path) 27 | elif not os.path.isdir(path): 28 | os.makedirs(path) 29 | 30 | 31 | def download_if_need(code, url): 32 | path = os.path.join(caiwu_folder, code + '.csv') 33 | if not os.path.exists(path): 34 | urllib.request.urlretrieve(url, path) 35 | sleep(1.5) # 间隔一段时间,防止服务器关闭连接 36 | 37 | 38 | def create_stock_file(code): 39 | cwzb_url = 'http://quotes.money.163.com/service/zycwzb_%s.html?type=report' % code 40 | # 财务指标 41 | create_folder_if_need(caiwu_folder) 42 | download_if_need(code, cwzb_url) 43 | 44 | 45 | def calcu_3year_average_profit(code, year): 46 | create_stock_file(code) 47 | data = pd.read_csv( 48 | os.path.join(caiwu_folder, code + '.csv'), encoding="gbk", index_col=0) 49 | data = data.T 50 | average_profit = 0 51 | for i in range(year - 2, year + 1): 52 | # 确认过,这里的'净利润(万元)'就是归属净利润 53 | average_profit += float(data['净利润(万元)'][str(i) + '-12-31']) 54 | average_profit /= 3 55 | # print(average_profit) 56 | return average_profit 57 | 58 | 59 | def last_5_year_roe(code, year): 60 | create_stock_file(code) 61 | data = pd.read_csv( 62 | os.path.join(caiwu_folder, code + '.csv'), encoding="gbk", index_col=0) 63 | data = data.T 64 | roes = [] 65 | for i in range(year - 4, year + 1): 66 | try: 67 | roes.append(float(data['净资产收益率加权(%)'][str(i) + '-12-31'])) 68 | except Exception: 69 | roes.append(0) 70 | return roes 71 | 72 | 73 | def calcu_all_stocks_3year_roe_and_average_profit(year): # 生成3年平均利润列表 74 | path = os.path.join(current_folder, 'stock_list%s.csv' % today) 75 | if not os.path.exists(path): 76 | data = ts.get_stock_basics() 77 | lie = [ 78 | '名字', '行业', '地区', '市盈率', '流通股本', '总股本', '总资产(万)', '流动资产', '固定资产', 79 | '公积金', '每股公积金', '每股收益', '每股净资', '市净率', '上市日期', '未分利润', '每股未分配', 80 | '收入同比(%)', '利润同比(%)', '毛利率(%)', '净利润率(%)', '股东人数' 81 | ] 82 | data.columns = lie 83 | data.index.names = ['代码'] 84 | data = data[data['上市日期'] < three_year_ago()] # 排除上市不满3年的公司 85 | data.to_csv(path, encoding='utf-8') 86 | 87 | data = pd.read_csv(path, encoding='utf-8', index_col=0) 88 | # print(data) 89 | data['平均利润'] = 0 90 | for index, row in data.iterrows(): 91 | try: 92 | data.loc[index, '平均利润'] = calcu_3year_average_profit( 93 | '%06d' % index, year) 94 | except Exception as e: 95 | print(e) 96 | data.loc[index, '平均利润'] = 0 97 | 98 | data.loc[index, '上4年roe'], data.loc[index, '上3年roe'], data.loc[index, '上2年roe'], \ 99 | data.loc[index, '上1年roe'], data.loc[index, '当年roe'] = last_5_year_roe('%06d' % index, year) 100 | print('完成%s' % index) 101 | data.to_csv( 102 | os.path.join(current_folder, '3年平均利润及其他财务指标%s.csv' % today), 103 | encoding='utf-8') 104 | 105 | 106 | def filter_stock_by_average_pe(min, max): 107 | path = os.path.join(current_folder, '3年平均利润及其他财务指标%s.csv' % today) 108 | if not os.path.exists(path): # 没有就生成3年平均利润列表 109 | calcu_all_stocks_3year_roe_and_average_profit( 110 | calcu_average_profit_end_year) 111 | 112 | gplb = pd.read_csv(path, index_col=0, encoding='utf-8') 113 | 114 | # 获取当前股票价格 115 | price_path = os.path.join(current_folder, today + '股票价格.csv') 116 | if not os.path.exists(price_path): 117 | ts.get_today_all().set_index('code').to_csv( 118 | price_path, encoding="utf-8") 119 | 120 | current_price = pd.read_csv(price_path, encoding="utf-8", index_col=0) 121 | current_price = current_price[['trade']] 122 | current_price.columns = ['价格'] 123 | gplb = gplb[[ 124 | '名字', '行业', '地区', '流通股本', '总股本', '总资产(万)', '流动资产', '固定资产', '每股净资', 125 | '市净率', '上市日期', '平均利润' 126 | ]] 127 | 128 | data = pd.merge(gplb, current_price, left_index=True, right_index=True) 129 | # 因为这里的平均利润单位是万元,而总股本单位是亿,价格单位是元 130 | data['平均市盈率'] = data['总股本'] * data['价格'] * 10000 / data['平均利润'] 131 | print('\n%s:' % today) 132 | print() 133 | print('%d个公司' % data.shape[0]) 134 | print('3年市盈率中位数%.1f' % round(data['平均市盈率'].median(), 1)) 135 | print('市净率中位数%.1f' % round(data['市净率'].median(), 1)) 136 | data = data[data['平均市盈率'] < max] 137 | data = data[data['平均市盈率'] > min] 138 | data['平均市盈率'] = data['平均市盈率'].round(1) 139 | data['平均利润'] = data['平均利润'].round() 140 | data['市净率'] = data['市净率'].round(1) 141 | data['固定资产'] = data['固定资产'].round() 142 | data['流动资产'] = data['流动资产'].round() 143 | data['总股本'] = data['总股本'].round() 144 | data['流通股本'] = data['流通股本'].round() 145 | average_pe_file = os.path.join( 146 | current_folder, today + '-3年平均市盈率在%s和%s之间的公司.xlsx' % (min, max)) 147 | data.to_excel(average_pe_file, encoding='utf-8') 148 | 149 | 150 | def filter_by_roe(min): # 筛选出最近5年ROE都高于min的公司 151 | path = os.path.join(current_folder, '3年平均利润及其他财务指标%s.csv' % today) 152 | if not os.path.exists(path): # 没有就生成3年平均利润列表 153 | calcu_all_stocks_3year_roe_and_average_profit( 154 | calcu_average_profit_end_year) 155 | 156 | gplb = pd.read_csv(path, index_col=0, encoding='utf-8') 157 | gplb = gplb[gplb['当年roe'] > min] 158 | gplb = gplb[gplb['上1年roe'] > min] 159 | gplb = gplb[gplb['上2年roe'] > min] 160 | gplb = gplb[gplb['上3年roe'] > min] 161 | gplb = gplb[gplb['上4年roe'] > min] 162 | 163 | # 获取当前股票价格 164 | price_path = os.path.join(current_folder, today + '股票价格.csv') 165 | if not os.path.exists(price_path): 166 | ts.get_today_all().set_index('code').to_csv( 167 | price_path, encoding="utf-8") 168 | 169 | current_price = pd.read_csv(price_path, encoding="utf-8", index_col=0) 170 | current_price = current_price[['trade']] 171 | current_price.columns = ['价格'] 172 | gplb = gplb[[ 173 | '名字', '行业', '地区', '流通股本', '总股本', '总资产(万)', '流动资产', '固定资产', '每股净资', 174 | '市净率', '上市日期', '平均利润', '当年roe', '上1年roe', '上2年roe', '上3年roe', '上4年roe' 175 | ]] 176 | 177 | data = pd.merge(gplb, current_price, left_index=True, right_index=True) 178 | # 因为这里的平均利润单位是万元,而总股本单位是亿,价格单位是元 179 | data['平均市盈率'] = data['总股本'] * data['价格'] * 10000 / data['平均利润'] 180 | data['平均市盈率'] = data['平均市盈率'].round(1) 181 | data['市净率'] = data['市净率'].round(1) 182 | 183 | high_roe_file = os.path.join(current_folder, 184 | today + f'-最近5年ROE都高于{min}%的公司.xlsx') 185 | data.to_excel(high_roe_file, encoding='utf-8') 186 | 187 | 188 | if __name__ == '__main__': 189 | filter_stock_by_average_pe(1, 10) # 这个函数是根据平均pe过滤股票 190 | filter_by_roe(25) # 筛选最近5年ROE都高于参数的公司 191 | -------------------------------------------------------------------------------- /finance2018.7z: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/lfh2016/chinese-stock-Financial-Index/741d8326115205753702ff4ba2174b49b33275a3/finance2018.7z -------------------------------------------------------------------------------- /generate_stock_report.py: -------------------------------------------------------------------------------- 1 | import os 2 | import urllib.request 3 | 4 | import pandas as pd 5 | from bs4 import BeautifulSoup 6 | from openpyxl import load_workbook 7 | from pandas import ExcelWriter 8 | 9 | from calcu_3year_average_pe import create_folder_if_need 10 | 11 | current_folder = os.path.dirname(os.path.abspath(__file__)) 12 | 13 | # 拟分配的利润或股利,可以得到分红的数额 14 | 15 | 16 | class Stock(): 17 | caiwu_folder = os.path.join(current_folder, 'finance2016') 18 | need_items = [ 19 | '营业总收入(万元)', '研发费用(万元)', '财务费用(万元)', '净利润(万元)_y', '归属于母公司所有者的净利润(万元)', 20 | '总资产(万元)', '总负债(万元)', '流动资产(万元)', '流动负债(万元)', '股东权益不含少数股东权益(万元)', 21 | '净资产收益率加权(%)', ' 支付给职工以及为职工支付的现金(万元)', '经营活动产生的现金流量净额(万元)', 22 | ' 投资活动产生的现金流量净额(万元)', '应收账款(万元)', '存货(万元)', '开发支出(万元)', 23 | '归属于母公司股东权益合计(万元)', '所有者权益(或股东权益)合计(万元)', '投资收益(万元)_x', 24 | '实收资本(或股本)(万元)', '每股净资产(元)' 25 | ] 26 | # ,'支付给职工以及为职工支付的现金(万元)' 27 | 28 | items_new_name = [ 29 | '营业收入', '研发费用', '财务费用', '净利润', '归属净利润', '总资产', '总负债', '流动资产', '流动负债', 30 | '股东权益', 'ROE', ' 职工薪酬', '经营现金流', '投资现金流', '应收账款', '存货', '开发支出', 31 | '归属股东权益', '权益合计', '投资收益', '总股本', '每股净资产' 32 | ] # 名字和上面列表一一对应 33 | 34 | report_end_year = 2016 35 | 36 | def __init__(self, code, name): 37 | create_folder_if_need(self.caiwu_folder) 38 | self.code = code 39 | self.name = name 40 | # self.dframe=dframe 41 | self.cwzb_path = os.path.join(self.caiwu_folder, 42 | '财务指标' + self.code + '.csv') 43 | self.zcfzb_path = os.path.join(self.caiwu_folder, 44 | '资产负债表' + self.code + '.csv') 45 | self.lrb_path = os.path.join(self.caiwu_folder, 46 | '利润表' + self.code + '.csv') 47 | self.xjllb_path = os.path.join(self.caiwu_folder, 48 | '现金流量表' + self.code + '.csv') 49 | self.cwzb_url = 'http://quotes.money.163.com/service/zycwzb_%s.html?type=report' % self.code # 财务总表 50 | self.zcfzb_url = 'http://quotes.money.163.com/service/zcfzb_%s.html' % self.code # 资产负债表 51 | self.lrb_url = 'http://quotes.money.163.com/service/lrb_%s.html' % self.code # 利润表 52 | self.xjll_url = 'http://quotes.money.163.com/service/xjllb_%s.html' % self.code # 现金流量表 53 | self.url_reports = { 54 | self.cwzb_url: self.cwzb_path, 55 | self.zcfzb_url: self.zcfzb_path, 56 | self.lrb_url: self.lrb_path, 57 | self.xjll_url: self.xjllb_path 58 | } 59 | if self.code.startswith('6'): 60 | stock_code = 'sh' + self.code 61 | else: 62 | stock_code = 'sz' + self.code 63 | self.fh_url = 'http://f10.eastmoney.com/f10_v2/BonusFinancing.aspx?code=%s' % stock_code 64 | # url和对应的文件路径 65 | 66 | def save_xls(self, dframe): # 把数据写到已行业命名的excel文件的名字sheet 67 | xls_path = os.path.join(current_folder, self.name + '.xlsx') 68 | if os.path.exists(xls_path): # excel 文件已经存在 69 | book = load_workbook(xls_path) 70 | writer = pd.ExcelWriter(xls_path, engine='openpyxl') 71 | writer.book = book 72 | writer.sheets = dict((ws.title, ws) for ws in book.worksheets) 73 | dframe.to_excel(writer, self.name) 74 | writer.save() 75 | else: # 文件还不存在 76 | writer = ExcelWriter(xls_path) 77 | dframe.to_excel(writer, self.name) 78 | writer.save() 79 | 80 | def download_if_need(self, url, path): 81 | if not os.path.exists(path): 82 | urllib.request.urlretrieve(url, path) 83 | 84 | def doanload_stock_info(self): 85 | for url in self.url_reports: 86 | self.download_if_need(url, self.url_reports[url]) 87 | 88 | def _generate_report(self): 89 | data_frames = [] 90 | for key in self.url_reports: 91 | data_frames.append( 92 | pd.read_csv( 93 | self.url_reports[key], encoding="gbk", index_col=0).T) 94 | merge_frame = None 95 | for frame in data_frames: 96 | if merge_frame is None: 97 | merge_frame = frame 98 | else: 99 | merge_frame = pd.merge( 100 | merge_frame, frame, left_index=True, right_index=True) 101 | merge_frame = merge_frame[self.need_items] # 只取需要的指标 102 | merge_frame.columns = self.items_new_name # 重命名列 103 | for index, row in merge_frame.iterrows(): 104 | try: 105 | merge_frame.loc[index, 'ROE'] = 10000 * float(row['ROE']) 106 | except Exception: 107 | pass 108 | try: 109 | merge_frame['自由现金流'] = pd.to_numeric( 110 | merge_frame['经营现金流']) + pd.to_numeric(merge_frame['投资现金流']) 111 | except Exception as e: 112 | merge_frame['自由现金流'] = 0 113 | print(self.name + '自由现金流计算失败') 114 | 115 | try: 116 | merge_frame['负债率'] = pd.to_numeric( 117 | merge_frame['总负债']) / pd.to_numeric(merge_frame['总资产']) 118 | merge_frame['负债率'] = merge_frame['负债率'].round(2) 119 | except Exception as e: 120 | merge_frame['负债率'] = 0.66 121 | print(self.name + '负债率计算失败') 122 | try: 123 | merge_frame['流动比率'] = pd.to_numeric( 124 | merge_frame['流动资产']) / pd.to_numeric(merge_frame['流动负债']) 125 | merge_frame['流动比率'] = merge_frame['流动比率'].round(1) 126 | except Exception as e: 127 | merge_frame['流动比率'] = 0.66 128 | print(self.name + '流动比率计算失败') 129 | merge_frame = merge_frame[[ 130 | '营业收入', '流动比率', '负债率', '经营现金流', '投资现金流', '自由现金流', '净利润', '投资收益', 131 | ' 职工薪酬', '财务费用', '研发费用', '开发支出', 'ROE', '总股本', '每股净资产' 132 | ]] 133 | merge_frame = merge_frame.T 134 | years = [] 135 | for y in range(self.report_end_year, 2005, -1): 136 | date = str(y) + '-12-31' 137 | if date in merge_frame.columns: # 如果存在该时间的数据 138 | years.append(date) 139 | merge_frame = merge_frame[years] # 只取需要的时间 140 | merge_frame = merge_frame.applymap(self.convert2yi) 141 | self.save_xls(merge_frame) 142 | 143 | def generate_report(self): 144 | self.doanload_stock_info() 145 | self._generate_report() 146 | 147 | @staticmethod 148 | def convert2yi(value): 149 | try: 150 | if float(value) > 10 or float(value) < -10: 151 | return round(float(value) / 10000, 1) 152 | else: 153 | return value 154 | except Exception as e: 155 | return value 156 | 157 | def get_soup(self): 158 | response = urllib.request.urlopen(self.fh_url) 159 | html = response.read().decode('utf8') 160 | return BeautifulSoup(html, "html.parser") 161 | 162 | def get_3year_average_fh(self): # 单位为万元 163 | try: 164 | print('获取%s的分红信息' % self.name) 165 | soup = self.get_soup() 166 | fd = soup.find(id='lnfhrz') 167 | fd = fd.next_sibling.next_sibling.contents[1].contents 168 | sum_fh = float(fd[1].contents[1].string.replace(',', '')) + float( 169 | fd[2].contents[1].string.replace(',', '')) + float( 170 | fd[3].contents[1].string.replace(',', '')) 171 | # print(sum_fh) 172 | return round(sum_fh / 3) 173 | except Exception as e: # 没有分红 174 | return 0 175 | 176 | 177 | def update_fhlv(): 178 | stocks_path = os.path.join(current_folder, '筛选后股票的财务报表', '筛选后的股票列表.xlsx') 179 | stocks = pd.read_excel(stocks_path, index_col=0) 180 | stocks['3年平均分红'] = 0 181 | for index, row in stocks.iterrows(): 182 | s = Stock('%06d' % index, row['名字']) 183 | stocks.loc[index, '3年平均分红'] = s.get_3year_average_fh() 184 | stocks['平均分红率'] = stocks['3年平均分红'] * 100 / ( 185 | stocks['总股本(万)'] * stocks['价格']) 186 | stocks['平均分红率'] = stocks['平均分红率'].round() 187 | stocks.to_excel(stocks_path) 188 | 189 | 190 | def generate_reports(): # 根据股票列表,生成报表 191 | stocks_path = os.path.join(current_folder, '筛选后股票的财务报表', '筛选后的股票列表.xlsx') 192 | stocks = pd.read_excel(stocks_path, index_col=0) 193 | for index, row in stocks.iterrows(): 194 | s = Stock('%06d' % index, row['名字']) 195 | print('正在生成' + row['名字'] + '的报表') 196 | s.generate_report() 197 | 198 | 199 | if __name__ == '__main__': 200 | # s=Stock(sys.argv[1],sys.argv[2]) #股票代码,名字 201 | s = Stock('000776', '广发证券') 202 | # # #s.doanload_stock_info() 203 | s.generate_report() 204 | # # s=Stock('000568','泸州老窖','白酒') 205 | # print(s.get_3year_average_fh()) 206 | # generate_reports() 207 | # update_fhlv() 208 | print('完成') 209 | # 测试哦 210 | -------------------------------------------------------------------------------- /get_new_company_in_pool.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | 3 | # 比较2次筛选的股票池,得到新入池的公司 4 | old_day = '2016-07-12' 5 | new_day = '2016-10-08' 6 | 7 | 8 | def new_company_by_compare(new_day, old_day): 9 | old_pool_path = '3年平均市盈率在2和20之间的公司%s.xlsx' % (old_day) 10 | new_pool_path = '3年平均市盈率在2和20之间的公司%s.xlsx' % (new_day) 11 | old_pool = pd.read_excel(old_pool_path) 12 | new_pool = pd.read_excel(new_pool_path) 13 | new_index = new_pool.index.difference(old_pool.index) 14 | new_company = new_pool.reindex(new_index) 15 | new_company_file = '%s比%s新入池的公司.xlsx' % (new_day, old_day) 16 | new_company.to_excel(new_company_file) 17 | 18 | 19 | if __name__ == '__main__': 20 | new_company_by_compare(new_day, old_day) 21 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | tushare==1.0.5 2 | lxml==4.2.5 3 | pandas==0.24.2 4 | requests==2.20.1 5 | bs4==0.0.1 6 | openpyxl==2.5.11 7 | python-dateutil==2.7.3 --------------------------------------------------------------------------------