公开笔记
2 条公开笔记
百样代码知识
2024-07-08 21:53
Python爬虫实战:股票数据定向爬虫 功能简介 目标: 获取上交所和深交所所有股票的名称和交易信息。 输出: 保存到文件中。 技术路线: requests—bs4–re 语言:python3.5 说明 网站选择原则: 股票信息静态存在于html页面中,非js代码生成,没有Robbts协议限制。 选取方法: 打开网页,查看源代码,搜索网页的股票价格数据是否存在于源代码中。 步骤1: 从东方财富网获取股票列表; 步骤2: 逐一获取股票代码,并增加到百度股票的链接中,***对这些链接进行逐个的访问获得股票的信息; 因此,在我们存储每只股票的信息时,可以参考上图中html代码的存储方式。每一个信息源对应一个信息值,即采用键值对的方式进行存储。在python中键值对的方式可以用字典类型。因此,在本项目中,使用字典来存储每只股票的信息,然后再用字典把所有股票的信息记录起来,***将字典中的数据输出到文件中。 代码编写 首先是获得html网页数据的程序,在这里不多做介绍了,代码如下: #获得html文本 def getHTMLText(url): try: r = requests.get(url) r.raise_for_status() r.encoding = r.apparent_encoding return r.text except: return "" 1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.1 首先是获得html网页数据的程序,在这里不多做介绍了,代码如下: 步骤3: 将结果存储到文件。 接着查看百度个股信息网页的源代码,发现每只股票的信息在html代码中的存储方式如下: 由上图可以看到,a标签的href属性中的网址链接里面有每只股票的对应的号码,因此我们只要把网址里面对应股票的号码解析出来即可。解析步骤如下: ***步,获得一个页面: 复制 html = getHTMLText(stockURL) 1. 1 2 第二步,解析页面,找到所有的a标签: 复制 soup = BeautifulSoup(html, 'html.parser') a = soup.find_all('a') 1.2.3. 1 2 3 4 第三步,对a标签中的每一个进行遍历来进行相关的处理。处理过程如下: [ or i in a: href = i.attrs['href'] lst.append(re.findall(r"[s][hz]\d{6}", href)[0]) 1.2.3.4.5. 2.由于在html中有很多的a标签,但是有些a标签中没有href属性,因此上述程序在运行的时候出现异常,所有对上述的程序还要进行try…except来对程序进行异常处理,代码如下: for i in a: try: href = i.attrs['href'] lst.append(re.findall(r"[s][hz]\d{6}", href)[0]) except: continue 1.2.3.4.5.6.7.8.9.10.11. 1 1 2 3 4 5 6 2.由于在html中有很多的a标签,但是有些a标签中没有href属性,因此上述程序在运行的时候出现异常,所有对上述的程序还要进行try…except来对程序进行异常处理,代码如下: ef getStockList(lst, stockURL): html = getHTMLText(stockURL) soup = BeautifulSoup(html, 'html.parser') a = soup.find_all('a') for i in a: try: href = i.attrs['href'] lst.append(re.findall(r"[s][hz]\d{6}", href)[0]) except: continue 1.2.3.4.5.6.7.8.9.10.11.12.13.14.15.16.17.18.19.

展开全部

百样代码知识
2024-07-08 21:48
Python爬取所有股票数据并进行数据分析 一、背景:作为一个程序员,总喜欢在股市里面晃荡,无奈总是当成韭菜收割了。每一次都是卖涨买跌,处处碰壁。但是作为一个有一定阅历的程序员本能告诉自己,只要掌握了大量的股票数据,就可以在信息渠道落后的情况下,分析出机构大概率的在布局哪些股票,从而在机构拉涨停之前,提前进入分一杯羹。于是,开始编写了爬取股票数据并进行数据分析的程序。 二、环境:Anaconda3.3     python3.7.1    三、目标:爬取所有股票每天每一分钟的数据,并且进行数据分析 五、程序代码解析(源代码下载地址及数据库文章底部会提供): 1、把所有股票的基本信息都保存在一个mysql数据库中gp.sql,总过三千六百多条,如下图: 五、程序代码解析(源代码下载地址及数据库文章底部会提供): 1、把所有股票的基本信息都保存在一个mysql数据库中gp.sql,总过三千六百多条,如下图: 2、获取股票当天所有的数据get_gp_detail.py: import pymysql import numpy as np import sys import json import urllib.request import urllib import os import time #连接数据库 db = pymysql.connect(host='127.0.0.1',user='root',password='root',db='gp_db',port=3306) #获取cursor cursor = db.cursor()# 使用 execute() 方法执行 SQL,如果表存在则删除 sql = "select * from gp" cursor.execute(sql) print("SELECT OK") #all_gp = cursor.fetchmany(1) all_gp = cursor.fetchall() #从数据库中获取所有股票的基本信息数据 arr = np.array(all_gp) #转化为numpy数据格式 now = int(time.time()) #转换为其他日期格式,如:"%Y-%m-%d %H:%M:%S" timeStruct = time.localtime(now) strTime = time.strftime("%Y-%m-%d", timeStruct) gp_count = 1 #股票当天所有数据的保存编号 get_gp_detail.py程序正确运行之后,D盘中将会出现我们所需要的数据,如下图: def mkdir(path): #股票保存路径函数 folder = os.path.exists(path) if not folder: #判断是否存在文件夹如果不存在则创建为文件夹 os.makedirs(path) #makedirs 创建文件时如果路径不存在会创建这个路径 print(path) def getData(url): #函数——从接口中获取单只股票当天每分钟的数据 content = "" try: #网络会偶发出现奔溃情况,为了保证不中断和保证数据齐全,休息5秒重新执行 response = urllib.request.urlopen(url) content = response.read().decode('utf-8') except: print("发生网络异常") time.sleep(5) return getData(url) if content != "": return content else: print("内容为空") return getData(url) def csv_create(path, msg): #函数——将单只股票的数据保存进指定文件夹 file = open(path,'w') file.write(msg) print("文件"+path+"创建成功") file.close() def tranformToCSV(content,filepath): #函数——将下载的数据转换为csv数据,以便读取 content = content.replace("(","").replace(")","") json_str = json.loads(content) a_str = json_str.get("data") a_time = json_str.get("info").get("time") a_date = str(a_time).split(" ") mkdir(filepath) array_str = np.array(a_str) csv_str = "time,first,second,third,fourth\n" #time为当天时间点,first为该分钟股票价格 for item in array_str: item = str(item) items = item.split(",") itemss = (str(items[0])).split(" ") items0 = itemss[1] csv_str += '"'+items0+'",'+items[1]+','+items[2]+','+items[3]+','+items[4]+'\n' csv_create(filepath+"/"+a_date[0]+".csv",csv_str) for item in arr: url = "http://pdfm.eastmoney.com/EM_UBG_PDTI_Fast/api/js?rtntype=5&id=%22%20item[3]+item[1]+"&type=r&iscr=false" data = getData(url) item2 = item[2].replace("*","") tranformToCSV(data,"D://gp/"+str(gp_count)+"、"+item2+item[3]) #股票信息的保存路径是(D://pg/序号+股票名字+股票代号/日期.csv) gp_count = gp_count+1; # 使用 DebugLog db.commit() db.close() 3、对数据进行简单呈现plt_show.py: import pandas as pd import numpy as np import matplotlib.pyplot as plt o=open('D:/gp/1045、广州港601228/2019-04-01.csv') table = pd.read_csv(o) plt.plot(table['time'], table['first']) plt.rcParams['figure.figsize'] = (30.0, 20.0) plt.show() pd.to_numeric(table["first"],errors="ignore") #print(table["first"]) max = np.argmax(table["first"],axis=1) min = np.argmin(table["first"],axis=0) wave_price = table["first"][max]-table["first"][min] wave_price_rate = wave_price/table["first"][0] final_wave_price = table["first"][240]-table["first"][0] final_wave_price_rate = final_wave_price/table['first'][0] print("最大值"+str(table["first"][max])) print("最小值"+str(table["first"][min])) print("波动区间"+str(wave_price)) print("波动幅度%.2f%%"% (wave_price_rate * 100)) print("最终价格差距"+str(final_wave_price)) print('最终价格幅度%.2f%%' % (final_wave_price_rate * 100)) import pandas as pd import numpy as np import matplotlib.pyplot as plt o=open('D:/gp/1045、广州港601228/2019-04-01.csv') table = pd.read_csv(o) plt.plot(table['time'], table['first']) plt.rcParams['figure.figsize'] = (30.0, 20.0) plt.show() pd.to_numeric(table["first"],errors="ignore") #print(table["first"]) max = np.argmax(table["first"],axis=1) min = np.argmin(table["first"],axis=0) wave_price = table["first"][max]-table["first"][min] wave_price_rate = wave_price/table["first"][0] final_wave_price = table["first"][240]-table["first"][0] final_wave_price_rate = final_wave_price/table['first'][0] print("最大值"+str(table["first"][max])) print("最小值"+str(table["first"][min])) print("波动区间"+str(wave_price)) print("波动幅度%.2f%%"% (wave_price_rate * 100)) print("最终价格差距"+str(final_wave_price)) print('最终价格幅度%.2f%%' % (final_wave_price_rate * 100)) import pymysql import pandas as pd import numpy as np import matplotlib.pyplot as plt #连接数据库 db = pymysql.connect(host='127.0.0.1',user='root',password='root',db='gp_db',port=3306) #获取cursor cursor = db.cursor() time = "2019-04-12" def find_feature(path,name,gpid): o=open(path) table = pd.read_csv(o) table['time'] = pd.to_datetime(table["time"]) table = table.set_index('time',drop=False) #排序之后,日期会是当前日期加上时间 table = table["2019-04-12 14:00:00":"2019-04-12 15:00:00"] #print(table) if(table['first'].empty): return try: #print(table['first']) max = np.argmax(table["first"]) min = np.argmin(table["first"]) wave_price = table["first"][max]-table["first"][min] final_wave_price = table["first"][60]-table["first"][0] wave_price_rate = 0 final_wave_price_rate = 0 if table["first"][0] != 0: wave_price_rate = wave_price/table["first"][0] final_wave_price_rate = final_wave_price/table['first'][0] if final_wave_price_rate > 0.03: print(name+gpid) print("波动幅度%.2f%%"% (wave_price_rate * 100)) print('最终价格幅度%.2f%%' % (final_wave_price_rate * 100)) cursor.execute('insert into special_gp(gpfeature,gpname,gpid,gptime) values(%s,%s,%s,%s)',(1,str(gp_count)+"、"+name,gpid,time)) except: pass sql = "select * from gp" cursor.execute(sql) print("SELECT OK") #all_gp = cursor.fetchmany(1) all_gp = cursor.fetchall() arr = np.array(all_gp) gp_count = 1 for item in arr: item2 = item[2].replace("*","") path = "D://gp/"+str(gp_count)+"、"+item2+item[3]+"/"+time+".csv" find_feature(path,item2,item[3]) gp_count = gp_count+1; db.commit() db.close() 以上即为股票当天数据爬取及数据分析,注意:每天股票的详细数据必须在第二天开市之前进行抓取,否则便再也抓取不到。

展开全部

足迹加载中...