Python爬取所有股票数据并进行数据分析_python爬取股票数据并分析

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        #股票当天所有数据的保存编号
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="+item[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()

get_gp_detail.py程序正确运行之后,D盘中将会出现我们所需要的数据,如下图:

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))

效果图:

4、对所有股票数据进行简单的筛选和分析,筛选出2019-04-12,当天下午两点到三点之间,突然拉伸超过3%的所有股票并且保存进数据库find_feature.py:

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))


### 最后

Python崛起并且风靡,因为优点多、应用领域广、被大牛们认可。学习 Python 门槛很低,但它的晋级路线很多,通过它你能进入机器学习、数据挖掘、大数据,CS等更加高级的领域。Python可以做网络应用,可以做科学计算,数据分析,可以做网络爬虫,可以做机器学习、自然语言处理、可以写游戏、可以做桌面应用…Python可以做的很多,你需要学好基础,再选择明确的方向。这里给大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!

#### 👉Python所有方向的学习路线👈

Python所有方向的技术点做的整理,形成各个领域的知识点汇总,它的用处就在于,你可以按照上面的知识点去找对应的学习资源,保证自己学得较为全面。

![](https://img-blog.csdnimg.cn/img_convert/604bae65027d4d67fb62410deb210454.png)

#### 👉Python必备开发工具👈

工欲善其事必先利其器。学习Python常用的开发软件都在这里了,给大家节省了很多时间。

![](https://img-blog.csdnimg.cn/img_convert/fa276175617e0048f79437bd30465479.png)



#### 👉Python全套学习视频👈

我们在看视频学习的时候,不能光动眼动脑不动手,比较科学的学习方法是在理解之后运用它们,这时候练手项目就很适合了。

![](https://img-blog.csdnimg.cn/img_convert/16ac689cb023166b2ffa9c677ac40fc0.png)



#### 👉实战案例👈



学python就与学数学一样,是不能只看书不做题的,直接看步骤和答案会让人误以为自己全都掌握了,但是碰到生题的时候还是会一筹莫展。



因此在学习python的过程中一定要记得多动手写代码,教程只需要看一两遍即可。

![](https://img-blog.csdnimg.cn/img_convert/0d8c31c50236a205928a1d8ae8a0b883.png)



#### 👉大厂面试真题👈

我们学习Python必然是为了找到高薪的工作,下面这些面试题是来自阿里、腾讯、字节等一线互联网大厂最新的面试资料,并且有阿里大佬给出了权威的解答,刷完这一套面试资料相信大家都能找到满意的工作。

![](https://img-blog.csdnimg.cn/img_convert/99461e47e58e503d2bc1dc6f4668534a.png)

**[需要这份系统化学习资料的朋友,可以戳这里无偿获取](https://bbs.csdn.net/topics/618317507)**

**一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!**
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值