python 实时股票行情_python 实时获取股票行情脚本

本人股坛菜鸡,15年股灾全身而退,是不可能的,亲身上场体验1.0,2.0,3.0版本股灾。终身难忘。

优秀的我最近又兴起了畅游股海的念头,但是为了避免又一次卖血下海的后果,这次打算运用一点python小知识做行情分析,以做波段为主,决不轻易割肉。

一. 数据来源准备

想爬取收集目前A股所有股票的每日行情做分析,首先要找到很全的上市公司股票代码信息,然后通过市面上已有的免费的股票数据api接口获取,接着将获取到的数据进行存储,最后数据存储到一定量后,就可以对数据进行分析。

1. 股票代码

沪市:

http://www.sse.com.cn/assortment/stock/list/share/

深市:

http://www.szse.cn/market/companys/company/index.html

以上交易所网站可以获取到目前A股上所有上市公司股票代码信息。

2. api接口

我所知的接口有新浪、和讯、东方财富网,本文中使用的是东方财富网提供的接口,挺好用的,数据也很全。

测试一下(浏览器输入):

http://nuff.eastmoney.com/EM_Finance2015TradeInterface/JS.ashx?id=6000001

会得到返回结果:

二. 主要模块

这次主要涉及到的模块有requests、pymysql、json这3个。

requests库是一个常用的用于http请求的模块,可以方便的对网页进行爬取,是学习python爬虫的较好的http请求模块。

pymysql是在Python3.x版本中用于连接MySQL服务器的一个库。

Json模块则是提供了把内存中的对象序列化的方法。例如:loads()、dumps()

三. 实现

1. get请求获取数据

import requests

import json

##get方法发送http请求

response = requests.get(url='http://nuff.eastmoney.com/EM_Finance2015TradeInterface/JS.ashx?id=6000001')

##得到response返回信息

shares = response.text

share = json.loads(shares[9:-1])

print(type(share)) ## print(share)

json.loads(shares[9:-1]):由于返回的是string字符类型数据callback(...),所以通过切片将里面的看起来像是字典样式的数据截取出来,再通过json.loads方法转化为dict类型数据。

执行结果:

2. 数据库操作

import pymysql

dbconf = {'host':'127.0.0.1',

'port':3306,

'user':'root',

'password':'root',

'db':'shares', ##库名

'charset':'utf8mb4',

'cursorclass':pymysql.cursors.DictCursor}

def execsql(sql, databaseconf):

'''connect mysql return result'''

try:

conn = pymysql.connect(**databaseconf)

with conn.cursor() as cursor:

try:

cursor.execute(sql)

##执行增删改操作后需要commit

conn.commit()

except Exception as e:

print(e)

cursor.close()

conn.close()

except Exception as e:

print(e)

conn.cursor()游标

需要提前将数据库以及表结构,提前创建好。

执行insert语句即可将数据插入到数据库中:

sql = 'insert into share(name,code) values("浦发银行","600000")'

execsql(sql,dbconf)

3. 其他操作

1) 读取所有股票代码

预先将交易所网上的股票代码下载下来汇总到一个文件中

def share_code():

with open('sh_info.txt', 'rU') as file:

for code in file.readlines():

code_list.append(code.strip())

print(code_list)

2) 处理接口url

由于这个接口分为沪市与深市,区别就在接口url的最后一个字符,1表示沪市、2表示深市。所以需要判断代码前2个字符,为60则是沪市,使用1,其余均使用2。

http://nuff.eastmoney.com/.../JS.ashx?id=6000001

http://nuff.eastmoney.com/.../JS.ashx?id=0000022

if code[:2] == '60':

sh_url = 'http://nuff.eastmoney.com/EM_Finance2015TradeInterface/JS.ashx?id={code}1'.format(code=code)

else:

sz_url = 'http://nuff.eastmoney.com/EM_Finance2015TradeInterface/JS.ashx?id={code}2'.format(code=code)

四. 完成

##所有代码

import requests

import json

import pymysql

code_list = []

dbconf = {'host':'127.0.0.1',

'port':3306,

'user':'root',

'password':'root',

'db':'shares',

'charset':'utf8mb4',

'cursorclass':pymysql.cursors.DictCursor}

def execsql(sql, databaseconf):

'''connect mysql return result'''

try:

conn = pymysql.connect(**databaseconf)

with conn.cursor() as cursor:

try:

cursor.execute(sql)

conn.commit()

except Exception as e:

print(e)

cursor.close()

conn.close()

except Exception as e:

print(e)

def share_code():

with open('sh_info.txt', 'rU') as file:

for code in file.readlines():

code_list.append(code.strip())

print(code_list)

def insert_db(url):

response = requests.get(url)

shares = response.text

share = json.loads(shares[9:-1])

data = share["Value"]

date = data[49][:-9]

sql = 'insert into share(name,code,now,rise,changehands,amplitude,priceearnings,marketrate,date) values("{name}","{code}","{now}","{rise}","{changehands}","{amplitude}","{priceearnings}","{marketrate}","{date}")'.format(name=data[2],code=data[1],now=data[25],rise=data[29],changehands=data[37],amplitude=data[50],priceearnings=data[38],marketrate=data[43],date=date)

execsql(sql,dbconf)

print(sql)

def main():

share_code()

for code in code_list:

if code[:2] == '60':

sh_url = 'http://nuff.eastmoney.com/EM_Finance2015TradeInterface/JS.ashx?id={code}1'.format(code=code)

try:

insert_db(sh_url)

except Exception as e:

print(e)

else:

sz_url = 'http://nuff.eastmoney.com/EM_Finance2015TradeInterface/JS.ashx?id={code}2'.format(code=code)

try:

insert_db(sz_url)

except Exception as e:

print(e)

if __name__=="__main__":

main()

美化封装以上代码,每日下午3点收盘后执行一遍,就可以得到以下结果:

经过一段时间的抓取后,就可以根据喜好分析数据了。

其实这个接口是获取实时数据的,所以,有兴趣的同学可以将获取股票代码的步骤完善一下,直接从交易所网站爬取再处理,达到一键式存储数据,之后再使用numpy、pandas等数据分析模块进行趋势分析。完美。

选自公众号:py知识库,更多内容请关注公众号获取。

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值