从互联网获取股票数据(历史数据,Python + MySQL)
来源:SegmentFault
2023-02-16 15:34:14
0浏览
收藏
对于一个数据库开发者来说,牢固扎实的基础是十分重要的,golang学习网就来带大家一点点的掌握基础知识点。今天本篇文章带大家了解《从互联网获取股票数据(历史数据,Python + MySQL)》,主要介绍了MySQL、python、股票接口,希望对大家的知识积累有所帮助,快点收藏起来吧,否则需要时就找不到了!
目标
从互联网(网易数据接口)获取股票历史数据,包括开盘价、最高价、最低价、收盘价等等
环境
Python 3.6
MySQL 5.6.34
table: stock_list

记录数:3592 条,以该表为基础,制作 mission 清单。
table: stock_list_20190209( mission list )

从这个表里,每次读取一定数量的记录,依次从互联网上获取。
code: getStockData.py
''' 《获取股票历史市值》 Created on 2018年2月12日 @author: Livon # 读取 股票列表,含代码及 上市日期、终止上市日期 (1)列表 每次执行前,手工新建一个当前日期的表,如果存在就删除重建(可能是执行一个存储过程) 表名:stock_list_20180212 // 股票列表 表字段:id, 股票代码, 是否顺利完成,获取记录数量 每次取一条记录,依次执行,中断了,下次可以从中断处继续。 (2) 每条记录,按指定日期范围进行获取 再建 # 从网易数据接口拉取市值数据 # 存入表 stock_his_marketCap 中 ''' import util import urllib import csv import time import datetimeUtil from urllib import request jobListTable = 'stock_list_20180209' def p( msg ): print( '%s - %s' % ( datetimeUtil.getDatetime(), msg )) def startJob(): # 从数据池中读取 n 记录 missionList = util.getMissionList( jobListTable ) # 循环处理上述的 n 条记录 for mission in missionList: # for value in row: # print( value ) # 根据记录生成一条 url,一个 url 可以获取几千条日记录 url = util.genUrl( mission ) # url = 'http://quotes.money.163.com/service/chddata.html?code=1000001&start=19910401&end=19910409' # url += '&fields=LCLOSE;TOPEN;HIGH;LOW;TCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP' # print( dt(), ' - ', url ) p( 'url: %s' % url ) # 从互联网上获取股票数据 dataList = util.getStockDataList( url ) if( dataList != None ): # 将数据保存在目标表:股票历史数据表中 insertedRows = util.insertTable( dataList ) # 更新 mission List 状态标志列 util.updateJobList( jobListTable, mission, insertedRows ) else : p( 'csv 文件无数据。' ) p('standby a moment for next mission( you can terminal the program at this time).') time.sleep(3) # main for i in range( 0, 2 ): p( 'startJob: %s' % str(i) ) startJob() # done print( '= = = = = = = = = = = = = = = = = = = = = = ' ) p( 'all done !') print( '= = = = = = = = = = = = = = = = = = = = = = ' )
code: util.py
''' Created on 2018年2月11日 @author: Livon ''' import urllib.request import re import pymysql from urllib import request # from stock.获取股票历史市值 import datetimeUtil import datetimeUtil def p( msg ): print( '%s - %s' % ( datetimeUtil.getDatetime(), msg )) # 任务清单,每一次任务会领一份任务清单,清单中的第一项,是一个股票 # 任务:job - 大循环 # 目标:mission - 小目标 # missionList - 目标清单 # getMissionList # 参数:tableName 表名 def getMissionList( tableName ): rowsCount = '5' ; conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='root', db='stock', charset='utf8') # 创建游标 # cursor = conn.cursor() cursor = conn.cursor() # sql='select * from '+ tableName +' where doneTime is NULL limit ' + rowsCount sql = 'select * from %s where doneTime is NULL limit %s' % ( tableName, rowsCount ) cout = cursor.execute(sql) # print("数量: "+str(cout)) rows = cursor.fetchall(); # rows = conn.cursor().execute( sql ).fetchall() # for row in rows: # print("stockCode: "+str(row[0])+' stockName: '+row[1]+" startDate: "+ str(row[2])) cursor.close() # # try: # #获取一个游标 # with conn.cursor() as cursor: # sql='select * from '+ tableName +' where doneTime is NULL limit 1' # cout=cursor.execute(sql) # print("数量: "+str(cout)) # # for row in cursor.fetchall(): # #print('%s\t%s\t%s' %row) # #注意int类型需要使用str函数转义 # print("stockCode: "+str(row[0])+' stockName: '+row[1]+" startDate: "+ str(row[2])) # # conn.commit() # # finally: # print( 'done' ) cursor.close() conn.close() # print( datetimeUtil.getDatetime(), ' - 任务清单装载完毕!任务数量:', str( len( rows )) ) # print( '%s - %s missons loaded.' % ( datetimeUtil.getDatetime(), str( len( rows )) ) ) p( '%s missons loaded.' % str( len( rows ) )) return rows # 生成网址 def genUrl( row ): stockCode = row[0] startDate = str( row[2] ).replace('-','') # endDate = ( row[3] == 'None' )? '': row[3] # endDate = ( row[3] == None ) and '' or row[3] endDate = ( row[3] == None ) and row[3] or '' dataSource = row[4] # True and "Fire" or "Water" # print( row[3] is 'None') # print( row[3] is None ) # print( row[3] is '' ) # print( type( row[3] ) ) # print( type( row[3] ) is None ) # print( type( row[3] ) is 'NoneType' ) url = 'http://quotes.money.163.com/service/chddata.html?code=%s%s&start=%s&end=%s' url = url % ( dataSource, stockCode, startDate, endDate ) url += '&fields=LCLOSE;TOPEN;LOW;HIGH;TCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP' return url def getCsv( url ): # csv = csv.decode('gbk') # # csv_str = str(csv) # lines = csv_str.split("\\n") # # print( len( lines)) return '' # 从互联网上获取数据 def getStockDataList( url ): print( datetimeUtil.getDatetime(), ' - ', '准备从互联网获取数据 ...' ) # http = urllib3.PoolManager() # r = http.request('GET', url ) # url="http://www.example.com/" # headers={"User-Agent":"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1"} # try: # req = urllib3.request(url, headers ) # # req=urllib2.Request(url,headers=headers) # response = urllib3.request2.urlopen(req) # except urllib3.exceptions,e: # print e.reason dataList = None try: response = request.urlopen( url ) csv = response.read() csv = csv.decode('gbk') # csv = csv.decode('iso-8859-1') csv_str = str(csv) # print( type( csv )) if( len( csv_str ) 0 ): insertedRows += 1 print( datetimeUtil.getDatetime(), ' - 数据数量:', insertedRows ) # # 提交,不然无法保存新建或者修改的数据 conn.commit() # 关闭游标 cursor.close() # 关闭连接 conn.close() # arr_values = [] # arr_columns = [] # # for j in range( 0, len( properties) ): # # # print( 'propertie['+ str(j)+']: ' + properties[j] ) # # key_value = properties[j].split(':') # # print( key_value[0] + ' -> ' + key_value[1] ) # key = properties[j][:properties[j].find(':')] # value = properties[j][properties[j].find(':')+1:] # value = value.replace('"', '') # # print( key + ' -> ' + value ) # # sql += '"' + value + '"' # arr_columns.append( '`' + key + '`' ) # # arr_columns.append( key ) # arr_values.append( '"' + value + '"' ) # # sql = 'insert into stock_sina ' # sql = sql + ' ( ' + ','.join( arr_columns ) + ' ) VALUES ( ' + ','.join( arr_values ) + ' ) ' # print( sql ) # effect_row = cursor.execute( sql ) return insertedRows
code: datetimeUtil.py
''' Created on 2018年2月14日 @author: Livon ''' import time def getDatetime(): timeArray = time.localtime( time.time() ) otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", timeArray) return otherStyleTime
最终得到的数据:table: stock_his_data

记录总数:9045612(九百万)
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于数据库的相关知识,也可关注golang学习网公众号。
版本声明
本文转载于:SegmentFault 如有侵犯,请联系study_golang@163.com删除

- 上一篇
- MysqL应该考虑到的安全策略

- 下一篇
- 自写的使用PDO对mysql数据库的增删改查操作类
评论列表
-
- 悲凉的眼神
- 这篇文章真是及时雨啊,太详细了,真优秀,已加入收藏夹了,关注up主了!希望up主能多写数据库相关的文章。
- 2023-02-20 12:07:11
查看更多
最新文章
-
- 数据库 · MySQL | 8小时前 | 索引 数据类型 字符集 存储引擎 CREATETABLE
- MySQL新建表操作指南与建表技巧
- 462浏览 收藏
-
- 数据库 · MySQL | 1个月前 | 条件判断
- CASEWHEN条件判断的嵌套使用详解与实战场景分析
- 469浏览 收藏
-
- 数据库 · MySQL | 1个月前 | java php
- CSV文件批量导入MySQL的性能优化秘籍大揭秘
- 289浏览 收藏
-
- 数据库 · MySQL | 1个月前 |
- GaleraCluster多主集群配置与冲突解决攻略
- 239浏览 收藏
-
- 数据库 · MySQL | 1个月前 | 窗口函数实战
- MySQL窗口函数实战案例深度剖析
- 315浏览 收藏
-
- 数据库 · MySQL | 1个月前 | 自定义函数
- MySQL插件开发入门:自定义函数(UDF)编写指南
- 184浏览 收藏
-
- 数据库 · MySQL | 1个月前 |
- Windows系统MySQL8.0免安装版配置攻略
- 227浏览 收藏
-
- 数据库 · MySQL | 1个月前 | MySQL错误 数据库诊断
- 深度解析错误代码1045/1217/1205的根本原因及解决方案
- 202浏览 收藏
-
- 数据库 · MySQL | 1个月前 | sql注入 编码规范
- 防范SQL注入必备:编码规范与工具推荐指南
- 140浏览 收藏
-
- 数据库 · MySQL | 1个月前 | 日期函数大全
- MySQL日期函数全集及使用技巧大全
- 111浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 542次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 508次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 497次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 484次学习
查看更多
AI推荐
-
- 笔灵AI生成答辩PPT
- 探索笔灵AI生成答辩PPT的强大功能,快速制作高质量答辩PPT。精准内容提取、多样模板匹配、数据可视化、配套自述稿生成,让您的学术和职场展示更加专业与高效。
- 12次使用
-
- 知网AIGC检测服务系统
- 知网AIGC检测服务系统,专注于检测学术文本中的疑似AI生成内容。依托知网海量高质量文献资源,结合先进的“知识增强AIGC检测技术”,系统能够从语言模式和语义逻辑两方面精准识别AI生成内容,适用于学术研究、教育和企业领域,确保文本的真实性和原创性。
- 22次使用
-
- AIGC检测-Aibiye
- AIbiye官网推出的AIGC检测服务,专注于检测ChatGPT、Gemini、Claude等AIGC工具生成的文本,帮助用户确保论文的原创性和学术规范。支持txt和doc(x)格式,检测范围为论文正文,提供高准确性和便捷的用户体验。
- 30次使用
-
- 易笔AI论文
- 易笔AI论文平台提供自动写作、格式校对、查重检测等功能,支持多种学术领域的论文生成。价格优惠,界面友好,操作简便,适用于学术研究者、学生及论文辅导机构。
- 38次使用
-
- 笔启AI论文写作平台
- 笔启AI论文写作平台提供多类型论文生成服务,支持多语言写作,满足学术研究者、学生和职场人士的需求。平台采用AI 4.0版本,确保论文质量和原创性,并提供查重保障和隐私保护。
- 35次使用
查看更多
相关文章
-
- golang MySQL实现对数据库表存储获取操作示例
- 2022-12-22 499浏览
-
- 搞一个自娱自乐的博客(二) 架构搭建
- 2023-02-16 244浏览
-
- B-Tree、B+Tree以及B-link Tree
- 2023-01-19 235浏览
-
- mysql面试题
- 2023-01-17 157浏览
-
- MySQL数据表简单查询
- 2023-01-10 101浏览