您的位置:首页 > 编程语言 > Python开发

用Python3获取股票数据实例

2016-12-01 00:00 555 查看
闲话少说,直接进入正题!

根据前面介绍的sinajs上获取的股票实时数据格式,定义一个namedtuple:如下(完整代码在后面!):

Stock=namedtuple('Stock',['Name', 'OpenPrice', 'LastClosePrice', 'CurrentPrice', 'Highest', 'Lowest', 'CompeteBuyPrice', 'CompeteSellPrice', 'TotalQuantaty', 'TotalMoney', 'BuyNum1', 'BuyPrice1', 'BuyNum2', 'BuyPrice2', 'BuyNum3', 'BuyPrice3', 'BuyNum4', 'BuyPrice4', 'BuyNum5', 'BuyPrice5', 'SellNum1', 'SellPrice1', 'SellNum2', 'SellPrice2', 'SellNum3', 'SellPrice3', 'SellNum4', 'SellPrice4', 'SellNum5', 'SellPrice5', 'Date', 'Time','Unkonwn'])

这里这个Unknown表示还没用到这个数据。

下面的分割线后面就是完整的代码,可以直接使用

--------------------------------

#!/usr/bin/python3
from urllib.request import urlopen
from collections import namedtuple
Stock=namedtuple('Stock',['Name', 'OpenPrice', 'LastClosePrice', 'CurrentPrice', 'Highest', 'Lowest', 'CompeteBuyPrice', 'CompeteSellPrice', 'TotalQuantaty', 'TotalMoney', 'BuyNum1', 'BuyPrice1', 'BuyNum2', 'BuyPrice2', 'BuyNum3', 'BuyPrice3', 'BuyNum4', 'BuyPrice4', 'BuyNum5', 'BuyPrice5', 'SellNum1', 'SellPrice1', 'SellNum2', 'SellPrice2', 'SellNum3', 'SellPrice3', 'SellNum4', 'SellPrice4', 'SellNum5', 'SellPrice5', 'Date', 'Time','Unkonwn'])
#Constant
SERVER='http://hq.sinajs.cn/list='
test_url=SERVER+'sh600153'
#这里sh600153可以替换为想获取的股票代码,
#深市的用“sz######”,
#沪市的用“sh######”

def getDetail(stock_url,enc = 'utf-8'):
tmpHtml = urlopen(stock_url)
tmpContent=tmpHtml.read().decode(enc).split('=')[1][1:-3].split(',')
return tmpContent
#-----------------------
def main():
d=getDetail(test_url,'gbk')
s=Stock(*d)
print(s.Name,s.CurrentPrice)#以获取当前价格为例
if __name__=='__main__':
main()

----------------代码到结束-------------

下面是获取分时图的链接,可以根据需要自行使用:
http://image.sinajs.cn/newchart/min/n/sh600153.gif


这就是通过该链接获取的分时图。

------------------------------------

文章来自微信公众号:Python高手高手高高手



我们关注的不只是Python
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 股票