Python3获取股票行情数据(中国个股/中国指数/全球指数)
#!/usr/local/bin/python3 #coding=utf-8 #source http://www.cnblogs.com/txw1958/ import os, io, sys, re, time, json, base64 import webbrowser, urllib.request period_All_List = [ "min", #分时线 "daily", #日K线 "weekly", #周K线 "monthly" #月K线 ] period_min = period_All_List[0] period_daily = period_All_List[1] ChinaStockIndexList = [ "000001", # sh000001 上证指数 "399001", # sz399001 深证成指 "000300", # sh000300 沪深300 "399005", # sz399005 中小板指 "399006", # sz399006 创业板指 "000003", # sh000003 B股指数 ] ChinaStockIndividualList = [ "000063", # 中兴通讯 "600036", # 招商银行 ] WorldStockIndexList = [ {'code':"000001", 'yahoo':"000001.SS",'name':{'chinese':"中国上证指数", 'english':"CHINA SHANGHAI COMPOSITE INDEX"}}, {'code':"399001", 'yahoo':"399001.SZ",'name':{'chinese':"中国深证成指", 'english':"SZSE COMPONENT INDEX"}}, {'code':"DJI", 'yahoo':"^DJI",'name':{'chinese':"美国道琼斯工业平均指数", 'english':"Dow Jones Industrial Average"}}, {'code':"IXIC", 'yahoo':"^IXIC",'name':{'chinese':"美国纳斯达克综合指数", 'english':"NASDAQ Composite"},}, {'code':"GSPC", 'yahoo':"^GSPC",'name':{'chinese':"美国标准普尔500指数", 'english':"S&P 500"}}, {'code':"N225", 'yahoo':"^N225",'name':{'chinese':"日本日经225指数", 'english':"NIKKEI 225"}}, {'code':"TWII", 'yahoo':"^TWII",'name':{'chinese':"*台北加权指数", 'english':"TSEC weighted index"}}, {'code':"HSI", 'yahoo':"^HSI",'name':{'chinese':"香港恒生指数", 'english':"HANG SENG INDEX"}}, {'code':"FCHI", 'yahoo':"^FCHI",'name':{'chinese':"法国CAC40指数", 'english':"CAC 40"}}, {'code':"FTSE", 'yahoo':"^FTSE",'name':{'chinese':"英国富时100指数", 'english':"FTSE 100"}}, {'code':"GDAXI", 'yahoo':"^GDAXI",'name':{'chinese':"德国法兰克福DAX指数", 'english':"DAX"} } ] WorldStockIndexList_SP500 = WorldStockIndexList[7] #国内股票数据:指数 def getChinaStockIndexInfo(stockCode, period): try: exchange = "sz" if (int(stockCode) // 100000 == 3) else "sh" #http://hq.sinajs.cn/list=s_sh000001 dataUrl = "http://hq.sinajs.cn/list=s_" + exchange + stockCode stdout = urllib.request.urlopen(dataUrl) stdoutInfo = stdout.read().decode('gb2312') tempData = re.search('''(")(.+)(")''', stdoutInfo).group(2) stockInfo = tempData.split(",") #stockCode = stockCode, stockName = stockInfo[0] stockEnd = stockInfo[1] #当前价,15点后为收盘价 stockZD = stockInfo[2] #涨跌 stockLastEnd= str(float(stockEnd) - float(stockZD)) #开盘价 stockFD = stockInfo[3] #幅度 stockZS = stockInfo[4] #总手 stockZS_W = str(int(stockZS) / 100) stockJE = stockInfo[5] #金额 stockJE_Y = str(int(stockJE) / 10000) content = "#" + stockName + "#" + "(" + str(stockCode) + ")" + " 收盘:" \ + stockEnd + ",涨跌:" + stockZD + ",幅度:" + stockFD + "%" \ + ",总手:" + stockZS_W + "万" + ",金额:" + stockJE_Y + "亿" + " " imgPath = "http://image.sinajs.cn/newchart/" + period + "/n/" + exchange + str(stockCode) + ".gif" twitter = {'message': content, 'image': imgPath} except Exception as e: print(">>>>>> Exception: " + str(e)) else: return twitter finally: None #国内股票数据:个股 def getChinaStockIndividualInfo(stockCode, period): try: exchange = "sh" if (int(stockCode) // 100000 == 6) else "sz" dataUrl = "http://hq.sinajs.cn/list=" + exchange + stockCode stdout = urllib.request.urlopen(dataUrl) stdoutInfo = stdout.read().decode('gb2312') tempData = re.search('''(")(.+)(")''', stdoutInfo).group(2) stockInfo = tempData.split(",") #stockCode = stockCode, stockName = stockInfo[0] #名称 stockStart = stockInfo[1] #开盘 stockLastEnd= stockInfo[2] #昨收盘 stockCur = stockInfo[3] #当前 stockMax = stockInfo[4] #最高 stockMin = stockInfo[5] #最低 stockUp = round(float(stockCur) - float(stockLastEnd), 2) stockRange = round(float(stockUp) / float(stockLastEnd), 4) * 100 stockVolume = round(float(stockInfo[8]) / (100 * 10000), 2) stockMoney = round(float(stockInfo[9]) / (100000000), 2) stockTime = stockInfo[31] content = "#" + stockName + "#(" + stockCode + ")" + " 开盘:" + stockStart \ + ",最新:" + stockCur + ",最高:" + stockMax + ",最低:" + stockMin \ + ",涨跌:" + str(stockUp) + ",幅度:" + str(stockRange) + "%" \ + ",总手:" + str(stockVolume) + "万" + ",金额:" + str(stockMoney) \ + "亿" + ",更新时间:" + stockTime + " " imgUrl = "http://image.sinajs.cn/newchart/" + period + "/n/" + exchange + str(stockCode) + ".gif" twitter = {'message': content, 'image': imgUrl} except Exception as e: print(">>>>>> Exception: " + str(e)) else: return twitter finally: None #全球股票指数 def getWorldStockIndexInfo(stockDict): try: #http://download.finance.yahoo.com/d/quotes.csv?s=^IXIC&f=sl1c1p2l yahooCode = stockDict['yahoo'] dataUrl = "http://download.finance.yahoo.com/d/quotes.csv?s=" + yahooCode + "&f=sl1c1p2l" stdout = urllib.request.urlopen(dataUrl) stdoutInfo = stdout.read().decode('gb2312') tempData = stdoutInfo.replace('"', '') stockInfo = tempData.split(",") stockNameCn = stockDict['name']['chinese'] stockNameEn = stockDict['name']['english'] stockCode = stockDict['code'] stockEnd = stockInfo[1] #当前价,5点后为收盘价 stockZD = stockInfo[2] #涨跌 stockLastEnd= str(float(stockEnd) - float(stockZD)) #开盘价 stockFD = stockInfo[3] #幅度 percent = float(stockFD.replace("%", "")) matchResult = re.search("([\w?\s?:]*)(\-)", stockInfo[4]) #日期和最新值 stockDate = matchResult.group(1) content = "#" + stockNameCn + "# " + stockNameEn + "(" + stockCode + ")" \ + " 当前:" + stockEnd + ", 涨跌:" + stockZD + ", 幅度:" + stockFD \ + ", 最后交易时间:" + stockDate twitter = content except Exception as err: print(">>>>>> Exception: " + yahooCode + " " + str(err)) else: return twitter finally: None def test_china_index_data(): for stockCode in ChinaStockIndexList: twitter = getChinaStockIndexInfo(stockCode, period_daily) print(twitter['message'] + twitter['image']) def test_china_individual_data(): for stockCode in ChinaStockIndividualList: twitter = getChinaStockIndividualInfo(stockCode, period_min) print(twitter['message'] + twitter['image']) def test_global_index_data(): for stockDict in WorldStockIndexList: print(getWorldStockIndexInfo(stockDict)) def main(): "main function" print(base64.b64decode(b'Q29weXJpZ2h0IChjKSAyMDEyIERvdWN1YmUgSW5jLiBBbGwgcmlnaHRzIHJlc2VydmVkLg==').decode()) test_china_index_data() test_china_individual_data() test_global_index_data() if __name__ == '__main__': main()
原文出处: http://www.cnblogs.com/txw1958/
*** Python 3.2.2 (default, Sep 4 2011, 09:51:08) [MSC v.1500 32 bit (Intel)] on win32. *** >>> #上证指数#(000001) 收盘:2128.765,涨跌:2.761,幅度:0.13%,总手:5207.69万,金额:466.8022亿 http://image.sinajs.cn/newchart/daily/n/sh000001.gif #深证成指#(399001) 收盘:9087.130,涨跌:5.232,幅度:0.06%,总手:626366.6万,金额:475.5102亿 http://image.sinajs.cn/newchart/daily/n/sz399001.gif #沪深300#(000300) 收盘:2349.108,涨跌:1.620,幅度:0.07%,总手:3109.05万,金额:330.4818亿 http://image.sinajs.cn/newchart/daily/n/sh000300.gif #中小板指#(399005) 收盘:4289.397,涨跌:-28.691,幅度:-0.66%,总手:40025.33万,金额:52.3716亿 http://image.sinajs.cn/newchart/daily/n/sz399005.gif #创业板指#(399006) 收盘:703.581,涨跌:-3.144,幅度:-0.44%,总手:18349.6万,金额:30.0858亿 http://image.sinajs.cn/newchart/daily/n/sz399006.gif #B股指数#(000003) 收盘:217.495,涨跌:-0.164,幅度:-0.08%,总手:23.23万,金额:1.2213亿 http://image.sinajs.cn/newchart/daily/n/sh000003.gif #中兴通讯#(000063) 开盘:11.35,最新:11.48,最高:11.58,最低:11.30,涨跌:0.14,幅度:1.23%,总手:11.01万,金额:1.26亿,更新时间:15:05:51 http://image.sinajs.cn/newchart/min/n/sz000063.gif #招商银行#(600036) 开盘:9.62,最新:9.75,最高:9.86,最低:9.62,涨跌:0.16,幅度:1.67%,总手:53.18万,金额:5.18亿,更新时间:15:02:09 http://image.sinajs.cn/newchart/min/n/sh600036.gif #中国上证指数# CHINA SHANGHAI COMPOSITE INDEX(000001) 当前:2128.765, 涨跌:+2.761, 幅度:+0.13%, 最后交易时间:3:01am #中国深证成指# SZSE COMPONENT INDEX(399001) 当前:9087.13, 涨跌:+5.231, 幅度:+0.06%, 最后交易时间:3:00am >>>>>> Exception: ^DJI list index out of range None #美国纳斯达克综合指数# NASDAQ Composite(IXIC) 当前:2930.03, 涨跌:+36.78, 幅度:+1.27%, 最后交易时间:12:03pm #美国标准普尔500指数# S&P 500(GSPC) 当前:1374.55, 涨跌:+14.53, 幅度:+1.07%, 最后交易时间:12:03pm #日本日经225指数# NIKKEI 225(N225) 当前:8566.64, 涨跌:+123.54, 幅度:+1.46%, 最后交易时间:2:28am #*台北加权指数# TSEC weighted index(TWII) 当前:7124.49, 涨跌:+153.80, 幅度:+2.21%, 最后交易时间:1:33am #香港恒生指数# HANG SENG INDEX(HSI) 当前:19274.961, 涨跌:+382.172, 幅度:+2.02%, 最后交易时间:4:01am #法国CAC40指数# CAC 40(FCHI) 当前:3280.19, 涨跌:+73.07, 幅度:+2.28%, 最后交易时间:11:59am #英国富时100指数# FTSE 100(FTSE) 当前:5627.21, 涨跌:+54.05, 幅度:+0.97%, 最后交易时间:11:35am #德国法兰克福DAX指数# DAX(GDAXI) 当前:6689.40, 涨跌:+106.44, 幅度:+1.62%, 最后交易时间:11:45am >>>
#Sina 数据
# http://hq.sinajs.cn/list=sh600000
# http://hq.sinajs.cn/list=sz000913
#var hq_str_sh601006="大秦铁路, 27.55, 27.25, 26.91, 27.55, 26.20, 26.91, 26.92,
# 22114263, 589824680, 4695, 26.91, 57590, 26.90, 14700, 26.89,
# 14300,6.88, 15100, 26.87, 3100, 26.92, 8900, 26.93, 14230,
# 26.94, 25150, 26.95, 15220, 26.96, 2008-01-11, 15:05:32";
0:”大秦铁路”,股票名字;
1:”27.55″,今日开盘价;
2:”27.25″,昨日收盘价;
3:”26.91″,当前价格;//时间结束后也就是收盘价了
4:”27.55″,今日最高价;
5:”26.20″,今日最低价;
6:”26.91″,竞买价,即“买一”报价;
7:”26.92″,竞卖价,即“卖一”报价;
8:”22114263″,成交的股票数,由于股票交易以一百股为基本单位,所以在使用时,通常把该值除以一百;
9:”589824680″,成交金额,单位为“元”,为了一目了然,通常以“万元”为成交金额的单位,所以通常把该值除以一万;
10:”4695″,“买一”申请4695股,即47手;
11:”26.91″,“买一”报价;
12:”57590″,“买二”
13:”26.90″,“买二”
14:”14700″,“买三”
15:”26.89″,“买三”
16:”14300″,“买四”
17:”26.88″,“买四”
18:”15100″,“买五”
19:”26.87″,“买五”
20:”3100″,“卖一”申报3100股,即31手;
21:”26.92″,“卖一”报价 (22, 23), (24, 25), (26,27), (28, 29)分别为“卖二”至“卖四的情况”
30:”2008-01-11″,日期;
31:”15:05:32″,时间;
'''
'''
上证综合指数(000001),
http://hq.sinajs.cn/list=s_sh000001 上证综合指数
http://hq.sinajs.cn/list=s_sz399001 深圳成指
var hq_str_s_sh000001=”上证指数,3094.668,-128.073,-3.97,436653,5458126″;
数据含义分别为: 指数名称,当前点数,当前价格,涨跌率,成交量(手),成交额(万元);
##['上证指数', 000000
##'2377.512', 收盘
##'-5.973', 涨跌:
##'-0.25', 幅度:
##'585346', 总手: /100 万
##'5317351'] 金额:/1000 亿
K线图
http://image.sinajs.cn/newchart/daily/n/sh601006.gif 日K线
http://image.sinajs.cn/newchart/min/n/sh000001.gif 分时线
http://image.sinajs.cn/newchart/daily/n/sh000001.gif 日K线
http://image.sinajs.cn/newchart/weekly/n/sh000001.gif 周K线
http://image.sinajs.cn/newchart/monthly/n/sh000001.gif 月K线
# 和讯网的图片数据
# http://minpic.quote.stock.hexun.com/WebPic/SH/Min/601669_emb.gif
# http://minpic.quote.stock.hexun.com/WebPic/SZ/Min/000063_emb.gif
'''
Yahoo财经频道获取股票数据的API
http://finance.yahoo.com/d/quotes.csv?s=<股票名称>&f=<数据列选项>
参数s — 表示股票名称,多个股票之间使用英文加号分隔,如“XOM+BBDb.TO+JNJ+MSFT”,罗列了四个公司的股票:XOM, BBDb.TO, JNJ, MSFT。 f — 表示返回数据列,如“snd1l1yr”。
示例
http://finance.yahoo.com/d/quotes.csv?s=XOM+BBDb.TO+JNJ+MSFT&f=snd1l1yr
返回:
"XOM","Exxon Mobil Corpo","10/7/2010",63.85,2.69,12.33
"BBD-B.TO","BOMBARDIER INC., ","10/7/2010",5.27,1.90,N/A
"JNJ","Johnson & Johnson","10/7/2010",63.22,3.26,13.06
"MSFT","Microsoft Corpora","10/7/2010",24.53,2.12,11.68
上述是获取当前最新的数据,若需要获得历史数据,请使用下面API。
http://ichart.yahoo.com/table.csv?s=<string>&a=<int>&b=<int>&c=<int>&d=<int>&e=<int>&f=<int>&g=d&ignore=.csv
参
数s — 股票名称 a — 起始时间,月 b — 起始时间,日 c — 起始时间,年 d — 结束时间,月 e — 结束时间,日 f —
结束时间,年 g — 时间周期。Example: g=w, 表示周期是‘周’。d->‘日’(day),
w->‘周’(week),m->‘月’(mouth),v->‘dividends only’
一定注意月份参数,其值比真实数据-1。如需要9月数据,则写为08。
示例 查询浦发银行2010.09.25 – 2010.10.8之间日线数据
http://ichart.yahoo.com/table.csv?s=600000.SS&a=08&b=25&c=2010&d=09&e=8&f=2010&g=d
返回:
Date,Open,High,Low,Close,Volume,Adj Close
2010-09-30,12.37,12.99,12.32,12.95,76420500,12.95
2010-09-29,12.20,12.69,12.12,12.48,79916400,12.48
2010-09-28,12.92,12.92,12.57,12.58,63988100,12.58
2010-09-27,13.00,13.02,12.89,12.94,43203600,12.94
深沪股票代码
yahoo的api是国际性的,是支持国内沪深股市的,但代码稍微变动一下,如浦发银行的代号是:600000.SS。规则是:上海市场末尾加.ss,深圳市场末尾加.sz。
—— EOF ——
参考
http://code.google.com/p/yahoo-finance-managed/
http://finance.yahoo.com/
http://www.gummy-stuff.org/Yahoo-data.htm
Python API Class
http://www.goldb.org/ystockquote.html
附录
雅虎股票API f参数对照表
a Ask a2 Average Daily Volume a5 Ask Size
b Bid b2 Ask (Real-time) b3 Bid (Real-time)
b4 Book Value b6 Bid Size c Change & Percent Change
c1 Change c3 Commission c6 Change (Real-time)
c8 After Hours Change (Real-time) d Dividend/Share d1 Last Trade Date
d2 Trade Date e Earnings/Share e1 Error Indication (returned for symbol changed / invalid)
e7 EPS Estimate Current Year e8 EPS Estimate Next Year e9 EPS Estimate Next Quarter
f6 Float Shares g Day’s Low h Day’s High
j 52-week Low k 52-week High g1 Holdings Gain Percent
g3 Annualized Gain g4 Holdings Gain g5 Holdings Gain Percent (Real-time)
g6 Holdings Gain (Real-time) i More Info i5 Order Book (Real-time)
j1 Market Capitalization j3 Market Cap (Real-time) j4 EBITDA
j5 Change From 52-week Low j6 Percent Change From 52-week Low k1 Last Trade (Real-time) With Time
k2 Change Percent (Real-time) k3 Last Trade Size k4 Change From 52-week High
k5 Percebt Change From 52-week High l Last Trade (With Time) l1 Last Trade (Price Only)
l2 High Limit l3 Low Limit m Day’s Range
m2 Day’s Range (Real-time) m3 50-day Moving Average m4 200-day Moving Average
m5 Change From 200-day Moving Average m6 Percent Change From 200-day Moving Average m7 Change From 50-day Moving Average
m8 Percent Change From 50-day Moving Average n Name n4 Notes
o Open p Previous Close p1 Price Paid
p2 Change in Percent p5 Price/Sales p6 Price/Book
q Ex-Dividend Date r P/E Ratio r1 Dividend Pay Date
r2 P/E Ratio (Real-time) r5 PEG Ratio r6 Price/EPS Estimate Current Year
r7 Price/EPS Estimate Next Year s Symbol s1 Shares Owned
s7 Short Ratio t1 Last Trade Time t6 Trade Links
t7 Ticker Trend t8 1 yr Target Price v Volume
v1 Holdings Value v7 Holdings Value (Real-time) w 52-week Range
w1 Day’s Value Change w4 Day’s Value Change (Real-time) x Stock Exchange
y Dividend Yield