廢話很少說,直接上菜。html
第一步:基金數據爬取
打開每天基金網(https://fund.eastmoney.com/),經過瀏覽器的開發者工具,咱們能觀察到用戶的請求和數據的返回過程。從而利用正則表達式,以及 xpath 等工具,輔以一點 python 爬蟲的知識,很容易就能獲取到每支基金的增加率和持倉狀況。python
不少人學習python,不知道從何學起。
不少人學習python,掌握了基本語法事後,不知道在哪裏尋找案例上手。
不少已經作案例的人,殊不知道如何去學習更加高深的知識。
那麼針對這三類人,我給你們提供一個好的學習平臺,免費領取視頻教程,電子書籍,以及課程的源代碼!
QQ羣:883888997
我所用到的代碼以下。git
XMtool.py:正則表達式
# In[]: #!/usr/bin/env python # coding: utf-8 # encoding=utf-8 import pandas as pd import requests from lxml import etree import re #import collections import numpy as np # In[]: sample = '150000'#樣本數量 sc = '6yzf'#排序鍵值 st = 'desc'#排序方式 ft = 'gp'#基金類型 dx = '1'#是否可購 season = 1#季度選擇 r1r = 1#日增加率 r1z = 1#近1周 r1y = 1#近1月 r3y = 0.3333#近3月 r6y = 0.3333#近6月 r1n = 0.25#近1年 r2n = 0.25#近2年 r3n = 0.25#近3年 rjnl = 0.25#今年來 rcll = 1#成立來 sd = '2021-01-07' ed = '2021-02-07' # In[] 在參數文書寫單元后加上這麼一段就能夠了 #from PyQt5.QtWidgets import QInputDialog, QLineEdit, QDialog from PyQt5.QtWidgets import QDialog import sys from PyQt5.QtWidgets import QApplication import dialog class TestDialog1(QDialog,dialog.Ui_XMtool): def __init__(self,parent=None): super(TestDialog1,self).__init__(parent) self.setupUi(self) app=QApplication(sys.argv) dlg=TestDialog1() dlg.show() app.exec_() sample = dlg.sample.text() #樣本數量 sc = dlg.sc.currentText() #排序鍵值 st = dlg.st.currentText() #排序方式 ft = dlg.ft.currentText() #基金類型 dx = dlg.dx.currentText() #是否可購 season = int(dlg.season.currentText()) #季度選擇 r1r = float(dlg.r1r.text()) #日增加率 r1z = float(dlg.r1z.text())#近1周 r1y = float(dlg.r1y.text())#近1月 r3y = float(dlg.r3y.text())#近3月 r6y = float(dlg.r6y.text())#近6月 r1n = float(dlg.r1n.text())#近1年 r2n = float(dlg.r2n.text())#近2年 r3n = float(dlg.r3n.text())#近3年 rjnl = float(dlg.rjnl.text())#今年來 rcll = float(dlg.rcll.text())#成立來 # In[]: header = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.96 Safari/537.36', 'Referer': 'http://fund.eastmoney.com/data/fundranking.html', 'Cookie':'st_si=74949607860286; st_asi=delete; ASP.NET_SessionId=gekyucnll0wte0wrks2rr23b; _adsame_fullscreen_18503=1; EMFUND1=null; EMFUND2=null; EMFUND3=null; EMFUND4=null; EMFUND5=null; EMFUND6=null; EMFUND7=null; EMFUND8=null; EMFUND0=null; EMFUND9=02-07 16:37:21@#$%u521B%u91D1%u5408%u4FE1%u5DE5%u4E1A%u5468%u671F%u80A1%u7968A@%23%24005968; st_pvi=90009717841707; st_sp=2021-02-07%2012%3A14%3A29; st_inirUrl=https%3A%2F%2Fwww.baidu.com%2Flink; st_sn=21; st_psi=2021020716562364-0-0372414431' } url = 'http://fund.eastmoney.com/data/rankhandler.aspx?op=ph&dt=kf&ft='+ft+'&rs=&gs=0&sc='+sc+'&st='+st+'&sd='+sd+'&ed='+ed+'&qdii=&tabSubtype=,,,,,&pi=1&pn='+sample+'&dx='+dx+'&v=0.2692835962833908' response = requests.get(url=url, headers=header) text = response.text data = text.split('=')[1]#使用等號分開去後面一部分 compile_data = re.findall("{datas:\\[(.*)\\],allRecords", str(data))[0]#取datas和allRecords中的全部內容 strip_data = str(compile_data).strip('[').strip(']')#移除字符串頭尾的中括號 replace_quta = strip_data.replace('"', "")#雙引號替換爲空 quota_arrays = replace_quta.split(",")#使用逗號轉爲列表 intervals = [[i * 25, (i + 1) * 25] for i in range(15000)]#生成10000個區間,每一個區間長度爲25 narrays = [] for k in intervals: start, end = k[0], k[1] line = quota_arrays[start:end]#將條目25個分爲一組,表示一隻基金 narrays.append(line) header = ["基金代碼", "基金簡稱", "基金條碼", "日期", "單位淨值", "累計淨值", "日增加率", "近1周", "近1月", "近3月", "近半年", "近1年", "近2年", "近3年", "今年來", "成立來", "其餘1", "其餘2", "其餘3", "其餘4", "其餘5", "其餘6", "其餘7", "其餘8", "其餘9"] df = pd.DataFrame(narrays, columns=header)#生成pd數據結構 df.dropna() total = df.count()[0] print("共有{}支基金!".format(total)) df = df.head(total) df_part = df[["基金代碼", "基金簡稱", "日增加率", "近1周", "近1月", "近3月", "近半年", "近1年", "近2年", "近3年", "今年來", "成立來"]]#挑選部分感興趣的條目 df.to_csv("./基金增加率.csv", encoding="utf_8_sig") # In[]: df_picked_part = df_part rates = [r1r,r1z,r1y,r3y,r6y,r1n,r2n,r3n,rjnl,rcll] i = -1 for sc in ["日增加率", "近1周", "近1月", "近3月", "近半年", "近1年", "近2年", "近3年", "今年來", "成立來"]: i = i+1 #print(sc) rate = rates[i] rate_num = int(total*rate) df_tmp = df_part.sort_values(by=[sc], ascending=False, axis=0) df_tmp = df_tmp.head(rate_num) df_picked_part = pd.merge(df_picked_part,df_tmp,how='inner') print(df_picked_part.head(10)) df_picked_part.to_csv("./4433法則結果.csv", encoding="utf_8_sig") # In[]: rank_codes = df_part['基金代碼'].values.tolist() #len_codes = len(rank_codes) stocks_array = [] stock_funds = [] total_part = int(total/100)+1 #每百分之一報一次進度 for index, code in enumerate(rank_codes): # if index < 1: # print("<" * 30 + "全部基金的股票池前10狀況" + ">" * 30) # print(code) if index%total_part==0: print("<" * 30 + "得到基金持倉數據中:"+str(index)+"/"+str(total)+ ">" * 30) url = "http://fundf10.eastmoney.com/FundArchivesDatas.aspx?type=jjcc&code={}&topline=10&year=&month=&rt=0.5032668912422176".format(code) head = { "Cookie": "EMFUND1=null; EMFUND2=null; EMFUND3=null; EMFUND4=null; EMFUND5=null; EMFUND6=null; EMFUND7=null; EMFUND8=null; EMFUND0=null; st_si=44023331838789; st_asi=delete; EMFUND9=08-16 22:04:25@#$%u4E07%u5BB6%u65B0%u5229%u7075%u6D3B%u914D%u7F6E%u6DF7%u5408@%23%24519191; ASP.NET_SessionId=45qdofapdlm1hlgxapxuxhe1; st_pvi=87492384111747; st_sp=2020-08-16%2000%3A05%3A17; st_inirUrl=http%3A%2F%2Ffund.eastmoney.com%2Fdata%2Ffundranking.html; st_sn=12; st_psi=2020081622103685-0-6169905557" , "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.125 Safari/537.36"} response = requests.get(url, headers=head) text = response.text div = re.findall('content:\\"(.*)\\",arryear', text)[0] html_body = '<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>test</title></head><body>%s</body></html>' % ( div)#構造網頁 html = etree.HTML(html_body)#將傳進去的字符串轉變成_Element對象 stock_info = html.xpath('//div[{}]/div/table/tbody/tr/td/a'.format(season)) # for ii in stock_info: # print(ii.text) #print(season) stock_money = html.xpath('//div[{}]/div/table/tbody/tr/td[@class="tor"]'.format(season)) if stock_money == []: stock_money = html.xpath('//div[{}]/div/table/tbody/tr/td[@class="toc"]'.format(season)) stock_attr = [] # for i in range(0,len(stock_money)): stock_money_text = [] for ii in stock_money: ii_text = ii.text # print(ii_text) if ii_text!=None: ii.text = ii.text.replace('---','0') stock_money_text.append(float(ii.text.replace(',','').replace('%',''))) # print(ii.text) # stock_money_text.dropna() stock_one_fund = [] if len(stock_info)!=0 and len(stock_money_text)!=0: count = -1 for i in range(0,len(stock_info)): stock = stock_info[i] if stock.text==None: stock.text = '缺失' tmp0 = stock.text.split('.') tmp = tmp0[0] if stock.text and (tmp.isdigit() or (tmp.isupper() and tmp.isalnum() and len(tmp0)>1)): # if stock.text and stock.text.isdigit(): # list_tmp = [stock.text,stock_info[i+1].text] count = count+1 stock_one_fund.append([stock_info[i+1].text, stock_money_text[3*count+0], stock_money_text[3*count+1], stock_money_text[3*count+2]]) # print(stock_info[i+1].text) # if len(stock_one_fund)>1: # print("基金代碼:{}".format(code), "基金持有前10股票池", stock_one_fund) stock_funds.append([code,stock_one_fund]) # print(code) # print(stock_one_fund) # else: # print('發現無持倉基金!') # if len(stock_one_fund) > 1 and stock_one_fund: stocks_array.extend(stock_one_fund) print("<" * 30 + "得到基金持倉數據中:done!!!"+ ">" * 30) # print("test") tmp = pd.DataFrame(stock_funds,columns=['基金代碼','十大重倉']) df_funds_info_extend = pd.merge(df_part,tmp,how='inner',on='基金代碼') df_funds_info_extend.set_index('基金代碼') df_funds_info_extend.to_csv("./基金持倉.csv", encoding="utf_8_sig") # In[]: stock_info_list = [] for row in df_funds_info_extend.iterrows(): tenpos = row[1]['十大重倉'] fund_jc = row[1]['基金簡稱'] if len(tenpos)!=0: tmp = [tenpos[0][0],fund_jc,tenpos[0][1],tenpos[0][2],tenpos[0][3]] stock_info_list.append(tmp) df_stock_info = pd.DataFrame(stock_info_list,columns=['股票簡稱','所屬基金','佔淨值比例','持股數_萬','持倉市值_萬']) df_stock_info.to_csv("./股票被持有信息.csv", encoding="utf_8_sig") # In[] #df_stock_info.loc[:,['股票簡稱','持股數_萬','持倉市值_萬','佔淨值比例']] df_stock_info_cp = df_stock_info df_stock_info_cp['所屬基金cp'] = df_stock_info['所屬基金'] df_stock_info_gb = df_stock_info_cp.groupby('股票簡稱') #df_stock_info.drop(axis=1,['所屬基金']) # for n in df_stock_info_gb: # print(n) # print('\n') #stock_agg_result = df_stock_info_gb.agg({'持股數_萬':np.sum,'持倉市值_萬':np.sum,'佔淨值比例':np.mean}) stock_agg_result = df_stock_info_gb.agg({'持股數_萬':np.sum,'持倉市值_萬':np.sum,'佔淨值比例':np.mean,'所屬基金':len,'所屬基金cp':list}) stock_agg_result.columns = ['被持股數_萬','被持倉市值_萬','平均佔比','所屬基金數目','所屬基金集合'] stock_agg_result.to_csv("./股票被持有信息統計.csv", encoding="utf_8_sig") # df_stock_info_gb.to_csv("./測試.csv", encoding="utf_8_sig") # In[] rank = 10 stock_agg_result = stock_agg_result.sort_values(by="所屬基金數目",ascending=False) stock_agg_result_head0 = stock_agg_result.head(rank) stock_agg_result = stock_agg_result.sort_values(by="被持倉市值_萬",ascending=False) stock_agg_result_head1 = stock_agg_result.head(rank) stock_agg_result = stock_agg_result.sort_values(by="平均佔比",ascending=False) stock_agg_result_head2 = stock_agg_result.head(rank) funds_stocks_count = [] for st_funds_ in stock_funds: #st_funds_ = stock_funds[0] st_funds = st_funds_[1] tmp = [i[0] for i in st_funds] df_stock_funds = pd.DataFrame(tmp,columns=['股票簡稱']) # print(df_stock_funds) count0 = pd.merge(stock_agg_result_head0,df_stock_funds,how='inner',on='股票簡稱').iloc[:,0].size count1 = pd.merge(stock_agg_result_head1,df_stock_funds,how='inner',on='股票簡稱').iloc[:,0].size count2 = pd.merge(stock_agg_result_head2,df_stock_funds,how='inner',on='股票簡稱').iloc[:,0].size jc_tmp = df_part[df_part['基金代碼']==st_funds_[0]].iloc[0,1] funds_stocks_count.append([jc_tmp,count0,count1,count2]) df_funds_stock_count = pd.DataFrame(funds_stocks_count,columns = ['基金簡稱','優倉數目_所屬基金數','優倉數目_被持倉市值','平均佔比']) df_funds_stock_count = df_funds_stock_count.sort_values(by=["優倉數目_所屬基金數"], ascending=False, axis=0) df_funds_stock_count = pd.merge(df_funds_stock_count,df_part,how='inner',on='基金簡稱') df_funds_stock_count.to_csv("./基金持受歡迎股數目統計.csv", encoding="utf_8_sig")
dialog.py瀏覽器
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'dialog.ui' # # Created by: PyQt5 UI code generator 5.9.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_XMtool(object): def setupUi(self, XMtool): XMtool.setObjectName("XMtool") XMtool.resize(701, 622) self.verticalLayout = QtWidgets.QVBoxLayout(XMtool) self.verticalLayout.setObjectName("verticalLayout") self.formGroupBox_2 = QtWidgets.QGroupBox(XMtool) self.formGroupBox_2.setObjectName("formGroupBox_2") self.gridLayout = QtWidgets.QGridLayout(self.formGroupBox_2) self.gridLayout.setObjectName("gridLayout") self.label_18 = QtWidgets.QLabel(self.formGroupBox_2) self.label_18.setObjectName("label_18") self.gridLayout.addWidget(self.label_18, 0, 0, 1, 1) self.pushButton = QtWidgets.QPushButton(self.formGroupBox_2) self.pushButton.setObjectName("pushButton") self.gridLayout.addWidget(self.pushButton, 2, 0, 1, 2) self.frame = QtWidgets.QFrame(self.formGroupBox_2) self.frame.setObjectName("frame") self.formLayout_4 = QtWidgets.QFormLayout(self.frame) self.formLayout_4.setObjectName("formLayout_4") self.label = QtWidgets.QLabel(self.frame) self.label.setObjectName("label") self.formLayout_4.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.label) self.r1r = QtWidgets.QLineEdit(self.frame) self.r1r.setObjectName("r1r") self.formLayout_4.setWidget(0, QtWidgets.QFormLayout.FieldRole, self.r1r) self.label_2 = QtWidgets.QLabel(self.frame) self.label_2.setObjectName("label_2") self.formLayout_4.setWidget(1, QtWidgets.QFormLayout.LabelRole, self.label_2) self.r1z = QtWidgets.QLineEdit(self.frame) self.r1z.setObjectName("r1z") self.formLayout_4.setWidget(1, QtWidgets.QFormLayout.FieldRole, self.r1z) self.label_3 = QtWidgets.QLabel(self.frame) self.label_3.setObjectName("label_3") self.formLayout_4.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.label_3) self.r1y = QtWidgets.QLineEdit(self.frame) self.r1y.setObjectName("r1y") self.formLayout_4.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.r1y) self.label_4 = QtWidgets.QLabel(self.frame) self.label_4.setObjectName("label_4") self.formLayout_4.setWidget(3, QtWidgets.QFormLayout.LabelRole, self.label_4) self.r3y = QtWidgets.QLineEdit(self.frame) self.r3y.setObjectName("r3y") self.formLayout_4.setWidget(3, QtWidgets.QFormLayout.FieldRole, self.r3y) self.label_5 = QtWidgets.QLabel(self.frame) self.label_5.setObjectName("label_5") self.formLayout_4.setWidget(4, QtWidgets.QFormLayout.LabelRole, self.label_5) self.r6y = QtWidgets.QLineEdit(self.frame) self.r6y.setObjectName("r6y") self.formLayout_4.setWidget(4, QtWidgets.QFormLayout.FieldRole, self.r6y) self.label_6 = QtWidgets.QLabel(self.frame) self.label_6.setObjectName("label_6") self.formLayout_4.setWidget(5, QtWidgets.QFormLayout.LabelRole, self.label_6) self.r1n = QtWidgets.QLineEdit(self.frame) self.r1n.setObjectName("r1n") self.formLayout_4.setWidget(5, QtWidgets.QFormLayout.FieldRole, self.r1n) self.label_7 = QtWidgets.QLabel(self.frame) self.label_7.setObjectName("label_7") self.formLayout_4.setWidget(6, QtWidgets.QFormLayout.LabelRole, self.label_7) self.r2n = QtWidgets.QLineEdit(self.frame) self.r2n.setObjectName("r2n") self.formLayout_4.setWidget(6, QtWidgets.QFormLayout.FieldRole, self.r2n) self.label_8 = QtWidgets.QLabel(self.frame) self.label_8.setObjectName("label_8") self.formLayout_4.setWidget(7, QtWidgets.QFormLayout.LabelRole, self.label_8) self.r3n = QtWidgets.QLineEdit(self.frame) self.r3n.setObjectName("r3n") self.formLayout_4.setWidget(7, QtWidgets.QFormLayout.FieldRole, self.r3n) self.label_9 = QtWidgets.QLabel(self.frame) self.label_9.setObjectName("label_9") self.formLayout_4.setWidget(8, QtWidgets.QFormLayout.LabelRole, self.label_9) self.rjnl = QtWidgets.QLineEdit(self.frame) self.rjnl.setObjectName("rjnl") self.formLayout_4.setWidget(8, QtWidgets.QFormLayout.FieldRole, self.rjnl) self.label_10 = QtWidgets.QLabel(self.frame) self.label_10.setObjectName("label_10") self.formLayout_4.setWidget(9, QtWidgets.QFormLayout.LabelRole, self.label_10) self.rcll = QtWidgets.QLineEdit(self.frame) self.rcll.setObjectName("rcll") self.formLayout_4.setWidget(9, QtWidgets.QFormLayout.FieldRole, self.rcll) self.gridLayout.addWidget(self.frame, 1, 1, 1, 1) self.frame_2 = QtWidgets.QFrame(self.formGroupBox_2) self.frame_2.setObjectName("frame_2") self.label_11 = QtWidgets.QLabel(self.frame_2) self.label_11.setGeometry(QtCore.QRect(18, 18, 96, 24)) self.label_11.setObjectName("label_11") self.label_12 = QtWidgets.QLabel(self.frame_2) self.label_12.setGeometry(QtCore.QRect(18, 61, 96, 24)) self.label_12.setObjectName("label_12") self.sc = QtWidgets.QComboBox(self.frame_2) self.sc.setGeometry(QtCore.QRect(126, 61, 91, 30)) self.sc.setObjectName("sc") self.sc.addItem("") self.sc.addItem("") self.sc.addItem("") self.sc.addItem("") self.sc.addItem("") self.sc.addItem("") self.sc.addItem("") self.sc.addItem("") self.sc.addItem("") self.sc.addItem("") self.sc.addItem("") self.sc.addItem("") self.sc.addItem("") self.sc.addItem("") self.sc.addItem("") self.sc.addItem("") self.sc.setItemText(15, "") self.label_13 = QtWidgets.QLabel(self.frame_2) self.label_13.setGeometry(QtCore.QRect(18, 103, 96, 24)) self.label_13.setObjectName("label_13") self.st = QtWidgets.QComboBox(self.frame_2) self.st.setGeometry(QtCore.QRect(126, 103, 90, 30)) self.st.setObjectName("st") self.st.addItem("") self.st.addItem("") self.label_14 = QtWidgets.QLabel(self.frame_2) self.label_14.setGeometry(QtCore.QRect(18, 145, 96, 24)) self.label_14.setObjectName("label_14") self.ft = QtWidgets.QComboBox(self.frame_2) self.ft.setGeometry(QtCore.QRect(126, 145, 90, 30)) self.ft.setObjectName("ft") self.ft.addItem("") self.ft.addItem("") self.ft.addItem("") self.ft.addItem("") self.ft.addItem("") self.ft.addItem("") self.ft.addItem("") self.ft.addItem("") self.label_15 = QtWidgets.QLabel(self.frame_2) self.label_15.setGeometry(QtCore.QRect(18, 187, 96, 24)) self.label_15.setObjectName("label_15") self.dx = QtWidgets.QComboBox(self.frame_2) self.dx.setGeometry(QtCore.QRect(126, 187, 55, 30)) self.dx.setObjectName("dx") self.dx.addItem("") self.dx.addItem("") self.label_16 = QtWidgets.QLabel(self.frame_2) self.label_16.setGeometry(QtCore.QRect(18, 229, 96, 24)) self.label_16.setObjectName("label_16") self.season = QtWidgets.QComboBox(self.frame_2) self.season.setGeometry(QtCore.QRect(126, 229, 56, 30)) self.season.setObjectName("season") self.season.addItem("") self.season.addItem("") self.season.addItem("") self.season.addItem("") self.sample = QtWidgets.QLineEdit(self.frame_2) self.sample.setGeometry(QtCore.QRect(126, 18, 151, 30)) self.sample.setObjectName("sample") self.gridLayout.addWidget(self.frame_2, 1, 0, 1, 1) self.label_17 = QtWidgets.QLabel(self.formGroupBox_2) self.label_17.setObjectName("label_17") self.gridLayout.addWidget(self.label_17, 0, 1, 1, 1) self.frame.raise_() self.frame_2.raise_() self.label_18.raise_() self.label_17.raise_() self.pushButton.raise_() self.verticalLayout.addWidget(self.formGroupBox_2) self.retranslateUi(XMtool) self.pushButton.clicked.connect(XMtool.accept) QtCore.QMetaObject.connectSlotsByName(XMtool) def retranslateUi(self, XMtool): _translate = QtCore.QCoreApplication.translate XMtool.setWindowTitle(_translate("XMtool", "股林祕籍小明三式")) XMtool.setToolTip(_translate("XMtool", "<html><head/><body><p>歡迎使用小明選股軟件!</p></body></html>")) XMtool.setWhatsThis(_translate("XMtool", "<html><head/><body><p>不認識爸爸?</p></body></html>")) self.label_18.setText(_translate("XMtool", "基金數據參數設定:")) self.pushButton.setText(_translate("XMtool", "小明已肯定")) self.label.setText(_translate("XMtool", "日增加率")) self.r1r.setText(_translate("XMtool", "1")) self.label_2.setText(_translate("XMtool", "近1周")) self.r1z.setText(_translate("XMtool", "1")) self.label_3.setText(_translate("XMtool", "近1月")) self.r1y.setText(_translate("XMtool", "1")) self.label_4.setText(_translate("XMtool", "近3月")) self.r3y.setText(_translate("XMtool", "0.33333")) self.label_5.setText(_translate("XMtool", "近6月")) self.r6y.setText(_translate("XMtool", "0.33333")) self.label_6.setText(_translate("XMtool", "近1年")) self.r1n.setText(_translate("XMtool", "0.25")) self.label_7.setText(_translate("XMtool", "近2年")) self.r2n.setText(_translate("XMtool", "0.25")) self.label_8.setText(_translate("XMtool", "近3年")) self.r3n.setText(_translate("XMtool", "0.25")) self.label_9.setText(_translate("XMtool", "今年來")) self.rjnl.setText(_translate("XMtool", "0.25")) self.label_10.setText(_translate("XMtool", "成立來")) self.rcll.setText(_translate("XMtool", "1")) self.label_11.setText(_translate("XMtool", "樣本數量")) self.label_12.setText(_translate("XMtool", "排序鍵值")) self.sc.setItemText(0, _translate("XMtool", "6yzf")) self.sc.setItemText(1, _translate("XMtool", "dm")) self.sc.setItemText(2, _translate("XMtool", "jc")) self.sc.setItemText(3, _translate("XMtool", "jzrq")) self.sc.setItemText(4, _translate("XMtool", "dwjz")) self.sc.setItemText(5, _translate("XMtool", "ljjz")) self.sc.setItemText(6, _translate("XMtool", "rzdf")) self.sc.setItemText(7, _translate("XMtool", "zzf")) self.sc.setItemText(8, _translate("XMtool", "1yzf")) self.sc.setItemText(9, _translate("XMtool", "3yzf")) self.sc.setItemText(10, _translate("XMtool", "1nzf")) self.sc.setItemText(11, _translate("XMtool", "2nzf")) self.sc.setItemText(12, _translate("XMtool", "3nzf")) self.sc.setItemText(13, _translate("XMtool", "jnzf")) self.sc.setItemText(14, _translate("XMtool", "lnzf")) self.label_13.setText(_translate("XMtool", "排序方式")) self.st.setItemText(0, _translate("XMtool", "desc")) self.st.setItemText(1, _translate("XMtool", "asc")) self.label_14.setText(_translate("XMtool", "基金類型")) self.ft.setItemText(0, _translate("XMtool", "all")) self.ft.setItemText(1, _translate("XMtool", "gp")) self.ft.setItemText(2, _translate("XMtool", "hh")) self.ft.setItemText(3, _translate("XMtool", "zs")) self.ft.setItemText(4, _translate("XMtool", "qdii")) self.ft.setItemText(5, _translate("XMtool", "zq")) self.ft.setItemText(6, _translate("XMtool", "lof")) self.ft.setItemText(7, _translate("XMtool", "fof")) self.label_15.setText(_translate("XMtool", "是否可購")) self.dx.setItemText(0, _translate("XMtool", "1")) self.dx.setItemText(1, _translate("XMtool", "0")) self.label_16.setText(_translate("XMtool", "季度選擇")) self.season.setItemText(0, _translate("XMtool", "1")) self.season.setItemText(1, _translate("XMtool", "2")) self.season.setItemText(2, _translate("XMtool", "3")) self.season.setItemText(3, _translate("XMtool", "4")) self.sample.setText(_translate("XMtool", "15000")) self.label_17.setText(_translate("XMtool", "四四三三法則參數:"))
運行以後,須要填一些參數,以下。網絡
肯定以後,除了爬下來了咱們後面所要用到的所有數據以外,咱們還利用 4433 法則,對於基金進行了一個初步的分析和篩選。數據結構
第二步:股票增持計算
有了上面爬下來的原始數據以後,咱們就能夠統計:單股票被基金公司持有的數量、單股票被基金公司持有的市值和持有單股票基金公司的數目。對於不一樣的相鄰季度,咱們能夠計算這三個量的增加,又獲得三個新的指標。對於不一樣的指標進行降排序,咱們能夠獲得股票在基金公司中的受歡迎程度,以此獲得股票好壞度,指標值做爲權重。不一樣的指標獲得的不一樣的股票排序還能夠拿前幾取交集。從而咱們就獲得了基金公司們期待值比較高的股票。app
我所用的代碼以下:工具
#!/usr/bin/env python # coding: utf-8 # In[]: import pandas as pd #import os import tkinter as tk from tkinter import filedialog def getLocalFile(): root=tk.Tk() root.withdraw() filePath=filedialog.askopenfilename() print('文件路徑:',filePath) return filePath #if __name__ == '__main__': # In[]: file1 = getLocalFile() file2 = getLocalFile() #sheet1 = pd.read_csv('./all_1/股票被持有信息統計.csv') sheet1 = pd.read_csv(file1) sheet1 #sheet2 = pd.read_csv('./all_2/股票被持有信息統計.csv') sheet2 = pd.read_csv(file2) sheet3 = pd.merge(sheet1,sheet2,how='inner',on='股票簡稱') sheet3 sheet3['增持股數'] = sheet3['被持股數_萬_x'] - sheet3['被持股數_萬_y'] # In[]: sheet3['增持市值'] = sheet3['被持倉市值_萬_x'] - sheet3['被持倉市值_萬_y'] #sheet3['增持佔比'] = sheet3['平均佔比_x'] - sheet3['平均佔比_y'] sheet3['增持基金數量'] = sheet3['所屬基金數目_x'] - sheet3['所屬基金數目_y'] sheet3.to_csv('增持狀況統計.csv',encoding="utf_8_sig")
第三步:好股基金選取
第二步中,咱們其實已經獲得了被基金公司看重的股票,若是炒股,直接取其前幾,按其權重進行金額配置便可。如今問題是,國內股票交易,一手起步,選出來的股票很貴,好比說茅臺,你不必定買得起。這時候,咱們仍是寄但願於買基金。咱們但願選出的基金的持倉和咱們選出的好股票集合的「類似度」儘量高。類似度的衡量又不少方法。好比說:基金持有的十大重倉含有好股的數目、基金持有的十大重倉含有好股的市值、基金持有的十大重倉含有好股的佔比、基金持有的十大重倉含有好股的加權佔比(加權基於增持市值或增持基金數量)等等。學習
下面是我所用到的代碼,細節可看。
#!/usr/bin/env python # coding: utf-8 # In[]: import pandas as pd #import os # In[]: import tkinter as tk from tkinter import filedialog def getLocalFile(): root=tk.Tk() root.withdraw() filePath=filedialog.askopenfilename() print('文件路徑:',filePath) return filePath #if __name__ == '__main__': # In[] print('請輸入增持狀況統計:') increase_hold_add = getLocalFile() inc = pd.read_csv(increase_hold_add,index_col = 0) inc # In[]: #print('請輸入比率:') str_num = input("Enter your number: ") rate = int(str_num) rate # In[]: inc_sort_zcgs = inc.sort_values(by=["增持股數"], ascending=False, axis=0) inc_sort_zcsz = inc.sort_values(by=["增持市值"], ascending=False, axis=0) inc_sort_zcjjsl = inc.sort_values(by=["增持基金數量"], ascending=False, axis=0) inc_sort_zcgs inc_sort_zcgs = inc_sort_zcgs.head(rate) inc_sort_zcsz = inc_sort_zcsz.head(rate) inc_sort_zcjjsl = inc_sort_zcjjsl.head(rate) inc_merge = pd.merge(inc_sort_zcsz,inc_sort_zcjjsl,how='inner',on='股票簡稱') inc_merge intersec = inc_merge['股票簡稱'] intersec print('選出來的前{}股票交集爲:'.format(rate)) print(intersec) print('共{}只!'.format(len(intersec))) # In[]: print('請選擇基金持倉:') funds_hold_add = getLocalFile() funds_hold = pd.read_csv(funds_hold_add,index_col = 0) stock_funds = funds_hold stock_funds intersec intersec_ex = pd.merge(intersec,inc,how='inner',on='股票簡稱') intersec_ex['權重_增持市值'] = intersec_ex['增持市值']/intersec_ex['增持市值'].sum() intersec_ex['權重_增持基金數量'] = intersec_ex['增持基金數量']/intersec_ex['增持基金數量'].sum() intersec_ex.to_csv("./好股.csv", encoding="utf_8_sig") # In[ ]: result = []# pd.DataFrame() for row in stock_funds.iterrows(): tenpos = row[1]['十大重倉'] exec('tps='+tenpos) fund_jc = row[1]['基金簡稱'] #tmp = [i[0] for i in tps] #rate = [r[1] for r in tps] list_tmp = [[i[0],i[1]] for i in tps] df_stock_rate = pd.DataFrame(list_tmp,columns=['股票簡稱','股票佔比']) # good_stock_rate # df_stock_funds = pd.DataFrame(tmp,columns=['股票簡稱']) # print(df_stock_funds) good_stock = pd.merge(intersec_ex,df_stock_rate,how='inner',on='股票簡稱')#.iloc[:,0] count = good_stock['股票簡稱'].size rate_vector = good_stock['股票佔比'] total_rate = rate_vector.sum() tmp = (rate_vector.mul(good_stock['權重_增持市值']))#.sum tmp = tmp.sum() total_rate_weighted_zcsz = tmp tmp = (rate_vector.mul(good_stock['權重_增持基金數量']))#.sum tmp = tmp.sum() total_rate_weighted_zcjjsl = tmp #good_stock_jc = good_stock['基金簡稱'] result.append([fund_jc,count,total_rate,total_rate_weighted_zcsz,total_rate_weighted_zcjjsl]) pd_result = pd.DataFrame(result,columns = ['基金簡稱','好股數目','好股佔比','加權好股佔比_增持市值','加權好股佔比_增持基金數量']) pd_result = pd_result.sort_values(by='加權好股佔比_增持市值',ascending=False) pd_result = pd.merge(pd_result,stock_funds,how='inner',on='基金簡稱') # In[]: pd_result.to_csv("./基金持好股狀況統計.csv", encoding="utf_8_sig") print('完成!按任意鍵退出!') stop = input()
使用以往的數據作個測試驗證,以下:
從上圖可看出,用個人基金選擇策略,選出來的基金一個月漲跌爲 15 個點,兩個指數基金翻車,只有百分之五,勉強跑得贏上證。
「風險越高,收益越高」老是不變的鐵律,從這個角度來看,彷佛就沒必要糾結於哪一種方案或者策略收益是最高的,差很少就好了。
在這裏推薦下個人Python開發學習羣:883888997,羣裏都是學Python開發的,若是你想學或者正在學習Python ,歡迎你加入,你們都是軟件開發黨,不按期分享乾貨(只有Python軟件開發相關的),包括我本身整理的一份最新的Python進階資料和高級開發教程,歡迎進階中和進想深刻Python的小夥伴!
免責聲明:本文內容來源於網絡,文章版權歸原做者全部,意在傳播相關技術知識&行業趨勢,供你們學習交流,若涉及做品版權問題,請聯繫刪除或受權事宜。