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

Python实现股票行情接收V001

2014-04-03 18:22 387 查看
为什么Python,因为Python简单,用更少的代码实现更多的功能;

为什么要实现股票行情接收,纯属学习Python,如果能为我炒股的朋友提供帮助就更好了;

为什么是V001,学习python过程中,不可能一次将该功能做完,想到什么功能就做什么,慢慢更新。

背景:股票行情源使用sina的web行情源:"http://hq.sinajs.cn/list=sh000001,sz000002" (其中股票代码部分可以改变), 详细信息参考:http://blog.sina.com.cn/s/blog_540f22560100ba2k.html

首先,定义一个股票基本信息的数据结构:

class QuoteData:
def __init__(self):
self.stockid = ''
self.stockName = ''
self.lastPrice = ''
self.preClose = ''
self.openPrice = ''
self.lowPrice = ''
self.highPrice = ''
self.avgPrice = ''

def Print(self):
print "%s(%s)       %s  %s  %s %s %s %s" % (self.stockName, self.stockid, self.lastPrice, self.preClose, self.openPrice, self.lowPrice, self.highPrice, self.avgPrice)


为了以后扩展,定义一个行情接收基类,并且实现一个只打印行情的Listener:

class QuoteListener:
def OnQuoteRecv(self, quoteData):pass
class QuotePrinter:
def OnQuoteRecv(self, quoteData):
quoteData.Print()


同时还定义一个行情源基类,为了以后扩展多个行情源:

class QuoteSource:
def __init__(self, stocks, listener):
self.stocks = stocks
self.listener = listener
def queryStock(self):pass


实现一个sina行情源接收器:

class QuoteSourceSina(QuoteSource):
def queryStock(self):
host="http://hq.sinajs.cn/list="
url = host + self.stocks
req = urllib2.Request(url)
res_data = urllib2.urlopen(req)
res = res_data.read()
d = QuoteData()
for line in res.split('\n'):
#print line
if len(line) < 50 :
continue
stkid = line[13: 19]
info = line[21:]
vargs = info.split(',')
#print vargs
d.stockName = vargs[0]
d.stockid = stkid
d.lastPrice = vargs[3]
d.preClose = vargs[2]
d.openPrice = vargs[1]
d.lowPrice = vargs[5]
d.highPrice = vargs[4]
d.avgPrice = ''
self.listener.OnQuoteRecv(d)


实现主函数入口部分了:

def runCommandQuote(stockids):
lst = QuotePrinter()
s = QuoteSourceSina(stockids, lst)
print 'Stock          Last   PreClose    Open'
while True:
s.queryStock()
sleep(3)
if __name__ == '__main__':
runCommandQuote('sh510300,sh000300,sh600006')


代码就不做多解释了,很简单,python就是为了简单而设计的,希望大家多多提建议和意见,最后再上个运行的效果图吧:

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