股票数据API
python获取股票数据方法

python获取股票数据方法(原创版2篇)目录(篇1)1.获取股票数据的重要性2.Python 在获取股票数据中的应用3.使用 Python 获取股票数据的常用库和 API4.获取股票数据的具体步骤和示例代码5.总结和展望正文(篇1)1.获取股票数据的重要性在金融领域,尤其是股票投资中,获取及时、准确的数据至关重要。
股票市场的变化瞬息万变,投资者需要根据各种信息来分析市场趋势,以便做出明智的投资决策。
Python 作为一种广泛应用于金融领域的编程语言,可以有效地帮助投资者获取和处理股票数据。
2.Python 在获取股票数据中的应用Python 拥有丰富的库和 API,可以轻松地从各种来源获取股票数据。
例如,可以使用 pandas 库处理数据,使用 numpy 库进行数值计算,使用 matplotlib 库绘制图表等。
此外,Python 还支持多种获取股票数据的 API,如 Yahoo Finance、Alpha Vantage、IEX Cloud 等。
3.使用 Python 获取股票数据的常用库和 API(1)pandas 库:pandas 是一个强大的数据处理库,可以轻松地处理股票数据,如读取 CSV 文件、处理缺失值、进行数据合并等。
(2)numpy 库:numpy 是一个数值计算库,可以用于处理股票数据中的数值计算问题,如计算移动平均线、涨跌幅等。
(3)matplotlib 库:matplotlib 是一个绘图库,可以用于绘制股票数据的各种图表,如 K 线图、收盘价走势图等。
(4)Yahoo Finance:Yahoo Finance 是一个提供股票数据的网站,可以通过 Python 的 requests 库获取实时股票数据。
(5)Alpha Vantage:Alpha Vantage 是一个提供免费 API 的网站,可以获取实时和历史股票数据,如收盘价、成交量、市盈率等。
(6)IEX Cloud:IEX Cloud 是一个提供免费 API 的网站,可以获取实时股票数据,如买卖盘口、成交记录等。
python获取a股票数据方法

python获取a股票数据方法(中英文实用版)Title: Python: A Share Data Acquisition MethodIn recent years, Python has become an increasingly popular programming language for financial data analysis, especially when it comes to acquiring stock data.There are numerous libraries and APIs available that can help you retrieve stock data, making it easier than ever to access this valuable information.In this article, we will explore a method for acquiring A-share data using Python.近年来,Python已成为金融数据分析中越来越受欢迎的编程语言,尤其是在获取股票数据方面。
有许多库和API可用,可以帮助您检索股票数据,使获取这些有价值的信息变得比以往任何时候都更加容易。
本文将介绍使用Python获取A股数据的方法。
To acquire A-share data using Python, one popular method is to utilize the Tushare library.Tushare is a free, open-source Python package that provides convenient access to Chinese stock market data.To get started, you"ll first need to install the Tushare library by running the following command in your terminal or command prompt: 使用Python获取A股数据的一种流行方法是利用Tushare库。
python获取股票数据方法

python获取股票数据方法
1.使用 tushare
Tushare是一个免费、开源的python财经数据接口包,它能够为用户提供便捷的获取股票数据的方法。
Tushare支持大量的股票数据,包括股票列表、股票细节数据、历史价格数据、技术行情数据等。
使用Tushare,只需要简单的函数调用即可获得数据,非常方便快捷。
使用tushare可以很容易获取各类股票数据,以下是一些核心函数的使用示例:
1.获取股票的基本信息:
ts.get_stock_basic
2.获取历史上只股票价格:
3.获取股票历史行情:
4.获取当日实时行情:
ts.get_today_all
使用tushare获取股票数据,需要先安装tushare模块,安装方法如下:
pip install tushare
安装完成后,就可以使用tushare模块来获取股票数据了。
2.使用 Wind Python
Wind Python是Wind财经研究院推出的python接口,用于获取全球财经数据信息,包括国内主板、中小板、创业板的历史价格、财务指标、市场交易数据等。
使用 Wind Python 可以方便的获取港股、美股和A股数据。
使用Wind Python获取股票数据,只需要简单的函数调用即可,以下是一些常用的核心函数的使用示例:
1.获取指定时间段只股票数据:
2.获取指定期间只股票的日收益。
股票实时数据接口

[36] 成交量(手)
[37] 成交额(万)
[38] 换手率
[39] 市盈率
[40]
[41] 最高
[42] 最低
[43] 振幅
[44] 流通市值
[45] 总市值
[46] 市净率
[47] 涨停价
[48] 跌停价
[49] 量比
[50]
[51] 均价
[52] 市盈率(动)
[53] 市盈率(静)
[54]
[55]
说明
对双引号内的字符串按“~”进行分割,数据项依次为:
[0] 证券所代码
[1] 股票简称
[2] 股代码
[3] 当前价格
[4] 昨收
[5] 今开
[6] 成交量(手)
[7] 外盘
[8] 内盘
[9] 买一
[10] 买一量(手)
[11] 买二
[12] 买二量
[13] 买三
[14] 买三量
[15] 买四
[16] 买四量
股票实时数据接口
请求
举例
/q=sh600660
说明
sh600600是股票代码,将其更换为其他股票代码即可。上证股票代码前加“sh”,深圳股票代码前加“sz”。
响应
举例
v_sh600660="1~福耀玻璃~600660~18.81~18.92~18.92~86578~39928~46619~18.81~3083~18.80~4095~18.79~505~18.78~858~18.77~437~18.82~280~18.83~271~18.84~97~18.85~214~18.86~224~15:00:04/18.81/1473/S/2770713/26114|14:57:02/18.82/9/B/16581/25808|14:56:57/18.81/2/S/3762/25802|14:56:55/18.82/28/B/52696/25800|14:56:52/18.81/35/S/65847/25794|14:56:48/18.81/86/S/161836/25789~20200422153002~-0.11~-0.58~18.92~18.71~18.82/85105/159982368~86578~16275~0.43~14.72~~18.92~18.71~1.11~376.76~471.87~2.26~20.81~17.03~0.58~7892~18.80~15.08~11.45~~~1.06~16275.3081~0.0000~0~ ~GP-A~-21.59~~3.99~15.34~7.97";
基于C#的股票查询api调用代码实例

基于C#的股票查询api调用代码实例代码描述:基于C#的股票查询api调用代码实例代码平台:聚合数据using System;using System.Collections.Generic;using System.Linq;using System.Text;using ;using System.IO;using ;using System.Diagnostics;using System.Web;//----------------------------------// 股票查询调用示例代码-聚合数据// 在线接口文档:/docs/81// 代码中JsonObject类下载地址:/download/gcm32060 21155665/7458439//----------------------------------namespace ConsoleAPI{class Program{static void Main(string[] args){string appkey = "*******************"; //配置您申请的appkey//1.股票查询string url1 = "/onebox/stock/query ";var parameters1 = new Dictionary<string, string>();parameters1.Add("key", appkey);//你申请的keyparameters1.Add("dtype", ""); //返回数据的格式,xml或json,默认jsonparameters1.Add("stock", ""); //股票名称string result1 = sendPost(url1, parameters1, "get");JsonObject newObj1 = new JsonObject(result1);String errorCode1 = newObj1["error_code"].Value;if(errorCode1 == "0"){Debug.WriteLine("成功");Debug.WriteLine(newObj1);}else{//Debug.WriteLine("失败");Debug.WriteLine(newObj1["error_code"].Value+":"+newObj1 ["reason"].Value);}}/// <summary>/// Http (GET/POST)/// </summary>/// <param name="url">请求URL</param>/// <param name="parameters">请求参数</param>/// <param name="method">请求方法</param>/// <returns>响应内容</returns>static string sendPost(string url, IDictionary<string, string> p arameters, string method){if(method.ToLower() == "post"){HttpWebRequest req = null;HttpWebResponse rsp = null;System.IO.Stream reqStream = null;try{req = (HttpWebRequest)WebRequest.Create(url);req.Method = method;req.KeepAlive = false;req.ProtocolVersion = HttpVersion.Version10;req.Timeout = 5000;req.ContentType = "application/x-www-form-urlencode d;charset=utf-8";byte[] postData = Encoding.UTF8.GetBytes(BuildQuery (parameters, "utf8"));reqStream = req.GetRequestStream();reqStream.Write(postData, 0, postData.Length);rsp = (HttpWebResponse)req.GetResponse();Encoding encoding = Encoding.GetEncoding(rsp.Charac terSet);return GetResponseAsString(rsp, encoding);}catch(Exception ex){return ex.Message;}finally{if(reqStream != null) reqStream.Close();if(rsp != null) rsp.Close();}}else{//创建请求HttpWebRequest request = (HttpWebRequest)WebRequest.Cre ate(url + "?"+ BuildQuery(parameters, "utf8"));//GET请求request.Method = "GET";request.ReadWriteTimeout = 5000;request.ContentType = "text/html;charset=UTF-8";HttpWebResponse response = (HttpWebResponse)request.Get Response();Stream myResponseStream = response.GetResponseStream();StreamReader myStreamReader = new StreamReader(myRespons eStream, Encoding.GetEncoding("utf-8"));//返回内容string retString = myStreamReader.ReadToEnd();return retString;}}/// <summary>/// 组装普通文本请求参数。
eoLinker-API_Shop_股票行情数据_API接口_Python调用示例代码

eoLinker-API Shop 股票行情数据 Python调用示例代码股票行情数据支持证券全市场行情数据,实时数据,K线数据,分笔数据,市场股票代码信息,历史数据等等,满足证券投资分析使用。
该产品拥有以下APIs:1.股票k线2.实时行情查询3.查询股票列表4.查询股票市场5.分笔6.分时查询7.指数实时报价8.组合行情查询9.综合排名注意,该示例代码仅适用于网站下API使用该产品前,您需要通过https:///#/api/detail/?productID=168申请API服务1.股票k线#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers)elif method == 'GET':return requests.get(url=url, params=params, headers=headers)else:return Nonemethod = "POST"url = "https:///mlhexpsz/stock/kline"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"stock_code":"" #股票代码"period":"" #1:1分钟 2:5分钟 3:15分钟 4:30分钟 5:60分钟 6:日k 线 7:周k线 8:月k线"request_num":"" #请求行数"position_str":"" #定位串,默认-1 从头开始}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')2.实时行情查询#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers)elif method == 'GET':return requests.get(url=url, params=params, headers=headers)else:return Nonemethod = "POST"url = "https:///mlhexpsz/stock/realtime"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"stock_code":"" #股票代码}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')3.查询股票列表#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers)elif method == 'GET':return requests.get(url=url, params=params, headers=headers)else:return Nonemethod = "POST"url = "https:///mlhexpsz/stock/list"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"stock_type":"" #市场类别"request_num":"" #定位串,传空默认为20"position_str":"" #起始位空,从应答中获取}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')4.查询股票市场#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers) elif method == 'GET':return requests.get(url=url, params=params, headers=headers) else:return Nonemethod = "POST"url = "https:///mlhexpsz/stock/market"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')5.分笔#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers)elif method == 'GET':return requests.get(url=url, params=params, headers=headers)else:return Nonemethod = "POST"url = "https:///mlhexpsz/stock/tick"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"stock_code":"" #股票代码"request_num":"" #请求参数}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')6.分时查询#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers)elif method == 'GET':return requests.get(url=url, params=params, headers=headers)else:return Nonemethod = "POST"url = "https:///mlhexpsz/stock/trend"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"stock_code":"" #股票代码}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')7.指数实时报价#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers)elif method == 'GET':return requests.get(url=url, params=params, headers=headers)else:return Nonemethod = "POST"url = "https:///mlhexpsz/stock/index"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"stock_code":"" #代码}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')8.组合行情查询#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers)elif method == 'GET':return requests.get(url=url, params=params, headers=headers)else:return Nonemethod = "POST"url = "https:///mlhexpsz/stock/comb"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"stock_code":"" #股票代码}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')9.综合排名#!/usr/bin/env python# -*- coding: utf-8 -*-# 测试环境: python2.7# 安装requests依赖 => pip install requests/ easy_install requests# 导入requests依赖import requestsimport jsonimport sysreload(sys)sys.setdefaultencoding('utf-8')def apishop_send_request(method, url, params=None, headers=None):'''转发请求到目的主机@param method str 请求方法@param url str 请求地址@param params dict 请求参数@param headers dict 请求头'''method = str.upper(method)if method == 'POST':return requests.post(url=url, data=params, headers=headers) elif method == 'GET':return requests.get(url=url, params=params, headers=headers) else:return Nonemethod = "POST"url = "https:///mlhexpsz/stock/sort"headers = Noneparams = {"apiKey":"your_api_key", #需要从获取"stock_type":"" #股票类别,参考市场查询返回值"sort_type":"" #排序类别}result = apishop_send_request(method=method, url=url, params=params, he aders=headers)if result:body = result.textresponse = json.loads(body)status_code = response["statusCode"]if (status_code == '000000'):# 状态码为000000, 说明请求成功print('请求成功:%s' % (body,))else:# 状态码非000000, 说明请求失败print('请求失败: %s' % (body,))else:# 返回内容异常,发送请求失败print('发送请求失败')。
python获取股票数据接口

python获取股票数据接⼝# encoding: utf8#部分⽹站api数据有bug,这个bug问题不是⾃⾝程序的问题,⽽是第三⽅公司股票的问题__author__ = 'nooper'import refrom math import ceilimport datetimefrom httpGet import httpGetContentfrom common import decimaldef _get_content(content):"处理腾讯股票数据接⼝信息"regex = pile(r'"(.*)"')result = regex.findall(content)if result:return result[0].split('~')def getStockPosition(code, market):"""处理股票盘⼝数据分析,分析所占的百分⽐率/q=s_pksz000858v_s_pksz000858="0.196~0.258~0.221~0.325";以 ~ 分割字符串中内容,下标从0开始,依次为:0: 买盘⼤单1: 买盘⼩单2: 卖盘⼤单3: 卖盘⼩单所占有的百分⽐百分⽐率"""if code and market:url = "/q=s_pk%s%s" % (market, code)content = httpGetContent(url)if content:result_list = _get_content(content)if result_list:stock_dict = {}stock_dict["code"] = codestock_dict["market"] = marketstock_dict["buy_big_percent"] = float(result_list[0]) # 买盘⼤单所占百分⽐stock_dict["buy_small_percent"] = float(result_list[1]) # 买盘⼩单所占百分⽐stock_dict["sell_big_percent"] = float(result_list[2]) # 卖盘⼤单所占⽐重stock_dict["sell_small_percent"] = float(result_list[3]) # 买盘⼩单所占⽐重stock_dict["date"] = datetime.date.today()return stock_dict# todo 数据对不上def getStockCashFlow(code, market):"""得到股票是资⾦流⼊流出/q=ff_sz000858v_ff_sz000858="sz000858~41773.67~48096.67~-6322.99~-5.53~10200.89~14351.02~-4150.13~-3.63~114422.25~53015.90~59770.57~五粮液~20121221";以 ~ 分割字符串中内容,下标从0开始,依次为:0: 代码1: 主⼒流⼊2: 主⼒流出3: 主⼒净流⼊4: 主⼒净流⼊/资⾦流⼊流出总和5: 散户流⼊6: 散户流出7: 散户净流⼊8: 散户净流⼊/资⾦流⼊流出总和9: 资⾦流⼊流出总和1+2+5+610: 未知11: 未知12: 名字13: ⽇期"""if code and market:url = "/q=ff_%s%s" % (market, code)content = httpGetContent(url)if content:result_list = _get_content(content)if result_list:stock_dict = {}stock_dict["code"] = codestock_dict["main_outflow"] = float(result_list[2]) # 主⼒流出stock_dict["main_netflow"] = float(result_list[3]) # 主⼒净流⼊stock_dict["small_inflow"] = float(result_list[5]) # 散户流⼊stock_dict["small_outflow"] = float(result_list[6]) # 散户流出stock_dict["small_netflow"] = float(result_list[7]) # 散户净流⼊income = stock_dict["main_inflow"] + stock_dict["small_inflow"]outcome = stock_dict["main_outflow"] + stock_dict["main_outflow"]print incomeprint outcomeprint income - outcomestock_dict["unknown_1"] = float(result_list[10])stock_dict["unknwon_2"] = float(result_list[11])stock_dict["date"] = result_list[13] # ⽇期return stock_dictdef getStockCurrentDay(code, Market):'''获取股票当⽇数据腾讯APIAPI地址:/q=sh600383sh:上海sz:深圳返回当天成交数据code:股票代码market:股票市场数据返回@return dict'''if code and Market:url = '/q=%s%s' % (Market, code)headers = {'Content-type': 'application/x-javascript; charset=GBK'}result = httpGetContent(url=url, headers=headers, charset='gbk')if result:stocklist = _get_content(result)if stocklist:stockdict = {}stockdict['code'] = code # 股票代码stockdict['name'] = unicode(stocklist[1], 'utf8') # 股票名称stockdict['last_closing'] = float(stocklist[4]) # 昨⽇收盘价格stockdict['start'] = float(stocklist[5]) # 开盘价格stockdict['end'] = float(stocklist[3]) # 当前收盘价格(可以是当前价格) stockdict['high'] = float(stocklist[33]) # 最⾼价格stockdict['low'] = float(stocklist[34]) # 最低价格stockdict['buyvol'] = int(stocklist[7]) # 外盘 todo 数据对不上stockdict["sellvol"] = int(stocklist[8]) # 内盘 todo 数据对不上stockdict['range_price'] = float(stocklist[31]) # 涨跌价格stockdict['range_percent'] = float(stocklist[32]) # 涨跌⽐%stockdict['volume'] = int(stocklist[6]) # 成交量(⼿)stockdict['total_price'] = int(stocklist[37]) # 成交额(万元)stockdict['change_rate'] = decimal(stocklist[38]) # 换⼿率stockdict['pe'] = decimal(stocklist[39]) # 市盈率stockdict['swing'] = float(stocklist[43]) # 振幅stockdict['pb'] = float(stocklist[46]) # 股票市净率stockdict['date'] = stocklist[30][:8] # 时间stockdict["block"] = False if stockdict["start"] else True #股票是否停牌return stockdictdef getStockMarket(code):"""⼤盘数据接⼝信息上证:code:000001 set=zs深证:code:399001 set=zs中⼩板:code:399005 set=zs创业板: code:399006 set=zs/qp/hq?type=snapshot&code=000001&set=zs"""url = "/qp/hq?type=snapshot&code=%s&set=zs" % coderesult = httpGetContent(url=url, charset="gbk")if result:result = eval(result)stock_dict = {}stock_dict["date"] = result[0][:10] #⽇期stock_dict["name"] = unicode(result[2], 'utf8') #名称stock_dict["range_price"] = float(result[4]) #上涨价格stock_dict["start"] = float(result[9]) #开盘价格stock_dict["high"] = float(result[11]) #最⾼价格stock_dict["low"] = float(result[13]) #最低价格stock_dict["last_closing"] = float(result[7]) #昨⽇收stock_dict["end"] = float(result[3]) #收盘价格stock_dict["total_sum"] = int(result[18]) #多少万元stock_dict["volume"] = int(result[14]) #多少⼿return stock_dicttonghuashun_headers = {"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Encoding": "gzip,deflate,sdch","Accept-Language": "zh-CN,zh;q=0.8","Cache-Control": "no-cache","Connection": "keep-alive","Host": "","User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36"}# def getstockBlock():# """# 新浪股票⿊名单数据# ”需要得到单点登录信息“## 新浪股票⿊名单个股# /stock/disallowStock# """# headers = {# 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',# 'Cache-Control': "max-age=0",# 'Host': '',# 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36', # 'Cookie': "PHPSESSID=c32fbi3m3sf0he8v1rdem3t006; gxqSignId=02d9c361fe5fc1ab; WBStore=d6acd6adea5a82d3|undefined"## }# url = "/stock/disallowStock"# content = httpGetContent(url=url, headers=headers)# if content:# soup = BeautifulSoup(content)# td_list = soup.find_all(text=pile('\d+'))# return td_listdef__convert_MIN(content):content = content.split('=')[1]content_list = content.split('|')stock_dict = {}for sub in content_list:if sub:items = sub.split('~')date = items[0]price_list = items[1].split(';')price_dict = {}for a in price_list:b = a.split(',')start = float(b[0]) #开盘价high = float(b[1]) #最⾼价格low = float(b[2]) #最低价格end = float(b[3]) #结束价格volum = int(ceil(float(b[4]))) #成交量多少买⼊total_price = int(ceil(float(b[5]))) #成交额time = b[6] #时间格式是1030,11:30,1400,1500price_dict[time] = {"high": high,'low': low,"end": end,"start": start,"volumn": volum,"total_price": total_price}stock_dict[date] = price_dictreturn stock_dictdef getStock60MIN(code, market, type=''):"""不推荐向后复权得到股票60分钟数据线API接⼝数据/api.php?p=stock_min60&info=k_sz_000005&fq=qq是向前复权b事项后复权q= 空是不复权"""if market not in ('sz', 'sh'):returnurl = "/api.php?p=stock_min60&info=k_%s_%s&fq=%s" % (market, code, type) content = httpGetContent(url=url)if content:return__convert_MIN(content)def getStock30MIN(code, market, type=''):"""30分钟数据接⼝信息/api.php?p=stock_min30&info=k_sz_000005&fq="""if market not in ('sz', 'sh'):returnurl = "/api.php?p=stock_min30&info=k_%s_%s&fq=%s" % (market, code, type) content = httpGetContent(url=url)if content:return__convert_MIN(content)def getStock15MIN(code, market, type=''):"""15分钟数据接⼝/api.php?p=stock_min15&info=k_sz_000005&fq="""if market not in ('sz', 'sh'):returnurl = "/api.php?p=stock_min15&info=k_%s_%s&fq=%s" % (market, code, type) content = httpGetContent(url=url)if content:return__convert_MIN(content)def__convert_inner(stock, stock_dict={}):stock_day = stock.split(',')if all(stock_day):date = stock_day[0] #⽇期start = float(stock_day[1]) #开盘价格high = float(stock_day[2]) #最⾼价格low = float(stock_day[3]) #最低价格end = float(stock_day[4]) #收盘价格volume = int(ceil(float(stock_day[5]))) #成交量total = int(ceil(float(stock_day[6]))) #成交额stock_dict[date] = {"date": date,'start': start,'high': high,'low': low,'end': end,'volume': volume,'total': total,}return stock_dictdef__convert_day(content):stock_list = content.split('=')[1].split('|')stock_dict = {}for stock in stock_list:if stock and stock.strip():__convert_inner(stock, stock_dict)# stock_day = stock.split(',')# date = stock_day[0] #⽇期# start = stock_day[1] #开盘价格# high = stock_day[2] #最⾼价格# low = stock_day[3] #最低价格# end = stock_day[4] #收盘价格# volume = int(ceil(float(stock_day[5]))) #成交量# total = int(ceil(float(stock_day[6]))) #成交额# stock_dict[date] = {# "date": date,# 'start': start,# 'high': high,# 'low': low,# 'end': end,# 'volume': volume,# 'total': total,# }return stock_dictdef__convert_week(content):content_list = content.split(';')regex = pile('=(.*)$')stock_dict = {}for s in content_list:p = regex.findall(s)[0]stock_list = p.split('|')for week in stock_list:if week:__convert_inner(week, stock_dict)return stock_dict#todo 测试完成def getStockDayHistory(code, market, year='2013', type=''):"""/api.php?p=stock_day&info=k_sz_000005&year=2012,2013&fq=sz:深证sh:上海return dict"""url = "/api.php?p=stock_day&info=k_%s_%s&year=%s&fq=%s" % (market, code, year, type) content = httpGetContent(url=url)if content:return__convert_day(content)#todo 测试完成def getStockWeekHistory(code, market, year='2012,2013', type=''):"""x/api.php?p=stock_week&info=k_sz_000005&year=2011,2012,2013&fq=pass"""url = "/api.php?p=stock_week&info=k_%s_%s&year=%s&fq=%s" % (market, code, year, type ) content = httpGetContent(url, tonghuashun_headers)if content:return__convert_week(content)def__convertMonth(content):passdef getStockMonthHistory(code, market, type=''):"""/api.php?p=stock_month&info=k_sz_000671&fq="""url = "/api.php?p=stock_month&info=k_%s_%s&fq=%s" % (market, code, type)content = httpGetContent(url)if content:passdef main():# g = getStock60MIN('600847', 'sh')# for k in g:# print k# print g[k]# g = getStockDayHistory("600198", "sh")# print g# import config## print getStockMarket(config.SHANGHAI)print getStockCurrentDay("600383", "sh")if__name__ == "__main__":main()。
沪深、香港、美国股票数据接口

沪深、香港、美国股票数据接口在即将到来的双十二,在聚合数据平台上的股票数据接口将参与活动,首先我们将分享下股票数据接口代码文档及返回示例,提供沪深、香港、美国股市信息。
接口名称:股票数据接口接口平台:聚合数据接口地址::8080/finance/stock/hs支持格式:json请求方式:get请求示例::8080/finance/stock/hs?gid=sh601009&key=您申请的APPKEY 调用样例及调试工具:API测试工具请求参数说明:名称类型必填说明gid string 是股票编号,上海股市以sh开头,深圳股市以sz开头如:sh601009(type为0或者1时gid不是必须)key String 是APP Keytype int 否0代表上证指数,1代表深证指数返回参数说明:名称类型说明见JSON返回示例- -JSON返回示例:{"resultcode":"200", /*返回码,200:正常*/ "reason":"SUCCESSED!","result":[{"data":{"gid":"sh601009", /*股票编号*/"name":"南京银行", /*股票名称*/"todayStartPri":"8.26", /*今日开盘价*/"yestodEndPri":"8.26", /*昨日收盘价*/"nowPri":"8.37", /*当前价格*/"todayMax":"8.55", /*今日最高价*/"todayMin":"8.25", /*今日最低价*/"competitivePri":"8.37", /*竞买价*/"reservePri":"8.38", /*竞卖价*/"traNumber":"34501453", /*成交量*/"traAmount":"290889560", /*成交金额*/"buyOne":"10870", /*买一*/"buyOnePri":"8.37", /*买一报价*/"buyTwo":"177241", /*买二*/"buyTwoPri":"8.36", /*买二报价*/"buyThree":"92600", /*买三*/"buyThreePri":"8.35", /*买三报价*/"buyFour":"87200" /*买四*/"buyFourPri":"8.34", /*买四报价*/"buyFive":"113700", /*买五*/"buyFivePri":"8.42", /*买五报价*/"sellOne":"47556", /*卖一*/"sellOnePri":"8.38", /*卖一报价*/"sellTwo":"103057", /*卖二*/"sellTwoPri":"8.39", /*卖二报价*/"sellThree":"186689", /*卖三*/"sellThreePri":"8.40", /*卖三报价*/"sellFour":"49000", /*卖四*/"sellFourPri":"8.41", /*卖四报价*/"sellFive":"214535", /*卖五*/"sellFivePri":"15.21", /*卖五报价*/"date":"2012-12-11", /*日期*/"time":"15:03:06", /*时间*/},"dapandata":{"name":"南京银行", /*大盘指数名称*/"dot":"8.37" /*大盘当前点数*/"nowPic":"0.11", /*大盘当前价格*/"rate":"1.33", /*大盘涨跌率*/"traNumber":"345014", /*大盘成交量(手)*/"traAmount":"29088", /*大盘成交金额(万元)*/ },"gopicture":{"minurl":"/newchart/min/n/sh601009.gif",/*分时K线图*/ "dayurl":"/newchart/daily/n/sh601009.gif",/*日K线图*/"weekurl":"/newchart/weekly/n/sh601009.gif",/*周K线图*/"monthurl":"/newchart/monthly/n/sh601009.gif"/*月K线图*/ }}]}----------------------------------深(上)证指数示例------------------------------------------------------------------{"error_code": 0"reason": "SUCCESSED!","result": {"dealNum": "24388041799",/*成交量*/"dealPri": "340674441059.270",/*成交额*/"highPri": "10357.417",/*最高*/"lowpri": "10121.741",/*最低*/"name": "深证成指",/*名称*/"nowpri": "10270.855",/*当前价格*/"openPri": "10200.547",/*今开*/"time": "2015-09-22 14:45:25",/*时间*/"yesPri": "10176.727"/*昨收*/},}数据接口API服务也是大数据企业的重要方向,数据API是每一个开发者必备的,也是需求量最大的数据产品。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
股票数据的获取目前有如下两种方法可以获取:1. http/javascript接口取数据2. web-service接口1.http/javascript接口取数据1.1Sina股票数据接口以大秦铁路(股票代码:601006)为例,如果要获取它的最新行情,只需访问新浪的股票数据接口:/list=sh601006这个url会返回一串文本,例如: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,26.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开始。
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″,时间;一个简单的JavaScript应用例子:script type="text/javascript" src="/list=sh601006" charset="gb2312">/script> /javascript">var elements=hq_str_sh601006.split(",");document.write("current price:"+elements[3]);这段代码输出大秦铁路(股票代码:601006)的当前股价current price:14.20如果你要同时查询多个股票,那么在URL最后加上一个逗号,再加上股票代码就可以了;比如你要一次查询大秦铁路(601006)和大同煤业(601001)的行情,就这样使用URL:/list=sh601003,sh601001查询大盘指数,比如查询上证综合指数(000001):/list=s_sh000001服务器返回的数据为:var hq_str_s_sh000001="上证指数,3094.668,-128.073,-3.97,436653,5458126";数据含义分别为:指数名称,当前点数,当前价格,涨跌率,成交量(手),成交额(万元);查询深圳成指数:/list=s_sz399001对于股票的K线图,日线图等的获取可以通过请求/…./…/*.gif此URL 获取,其中*代表股票代码,详见如下:查看日K线图:/newchart/daily/n/sh601006.gif分时线的查询:/newchart/min/n/sh000001.gif日K线查询:/newchart/daily/n/sh000001.gif周K线查询:/newchart/weekly/n/sh000001.gif月K线查询:/newchart/monthly/n/sh000001.gif1.2 Baidu&Google的财经数据在baidu, google中搜索某只股票代码时,将会在头条显示此股票的相关信息,例如在google 搜索601006时,第一条搜索结果如下图:通过点击左边的图片我们发现会将此图片链接到sina财经频道上,也就是说google股票数据的获取也是从sina获取。
后经抓包分析,发现google也是采用1.1中介绍的接口。
Baidu的股票数据来自baidu的财经频道/1.3 其他方式除了sina,baidu等网站提供股票信息外,其他网站也有类似的接口。
我们分析了一款论坛上采用的股票插件,其中有关于实时股票数据获取的介绍,详见如下代码,其中可以看到有些数据来自sina。
以下是ASP示例:=5 thenstockdata=gethttp("/list=sh"&code&"")if not len(stockdata)=0 then stockdata=split(stockdata,chr(34))(1)end ifif len(stockdata)=0 thenstockdata="0,0,0,0,0,0,0,0,0,0,0,0"elsestockdatasplit=split(stockdata,",")stockdata=""&exstock.checkstr(stockdatasplit(0))&","&stockdatasplit(1)&","&stockdatasplit(2)&", "&stockdatasplit(3)&","&stockdatasplit(4)&","&stockdatasplit(5)&","&formatdatetime(""&stockd atasplit(30)&" "&stockdatasplit(31)&"",0)&""end if‘0=股票名称,1=开盘价格,2=昨收盘价格,3=当前价格,4=最高价,5=最低价,6=更新时间getstockdata=stockdataend functionfunction getstockimg(code)dim rndnum,addnum,checkcode,imgsourceif len(code)=5 thengetstockimg="/newchart/daily/n/sh"&code&".gif"end ifimgsource=""case 3getstockimg="/stockchart/realline.chart?"&code&"&1003&SZ 500 330" imgsource=""case 4getstockimg="/chartserver?code="&code&""imgsource="/"end selectgetstockimg=split(""&getstockimg&"||"&imgsource&"","||")end functionfunction getastockimg()dim rndnum,addnum,checkcodedim getastockimgb,imgsourceaddnum=6randomize:rndnum=cint(rnd*addnum)select case rndnumcase 0getastockimg="http://202.109.106.1/gifchartse/gif/000001.gif"getastockimgb="http://202.109.106.1/gifchartse/gif/399001.gif"imgsource="/"case 1getastockimg="/special/100.gif?C39"getastockimgb="/special/101.gif?HrS"imgsource=""case 2getastockimg="/curve/realtime/index2.php?code=1a0001&w=180&h =140"getastockimgb="/curve/realtime/index2.php?code=399001&w=180& h=140"imgsource=""case 3getastockimg="/stockchart/realline.chart?1a0001&1002&SZ 180 140" getastockimgb="/stockchart/realline.chart?399001&1002&SZ 180 140" imgsource="/"case 4getastockimg="/newchart/small/ish000001.gif?1189176558328" getastockimgb="/newchart/small/isz399001.gif?1189176558328" imgsource=""case 5getastockimg="http://218.1.72.66/cgi/pic/sh/realtime/JA000001164143.png" getastockimgb="http://218.1.72.66/cgi/pic/sz/realtime/JA399001164143.png"imgsource="/"case 6getastockimg="http://222.73.29.85/img/000001.png"getastockimgb="http://222.73.29.85/img/399001.png"imgsource="/"end selectgetastockimg=split(""&getastockimg&"||"&getastockimgb&"||"&imgsource&"","||")end function%>2. web-service接口2.1 CHINAstock的web-service:/WebServices/ChinaStockWebService.asmx中国股票行情数据WEB 服务(支持深圳和上海股市的全部基金、债券和股票),数据即时更新。