2024年最新Python爬取所有股票数据并进行数据分析

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 =

  • 24
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值