Python量化学习-提取证券数据

505 阅读4分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 2 月更文挑战」的第 30 天,点击查看活动详情

不知道公众号有多少读者买基金或者炒股,分享一下如何用python获取证券信息

1、网易财经

import requestsfrom lxml import etree
headers = {    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36'}

def parse_url(url):    response = requests.get(url, headers=headers)    if response.status_code == 200:        return etree.HTML(response.content)    return False

def get_date(response):    # 得到股票代码,开始和结束的日期    start_date = ''.join(response.xpath('//input[@name="date_start_type"]/@value')[0].split('-'))    end_date = ''.join(response.xpath('//input[@name="date_end_type"]/@value')[0].split('-'))    code = response.xpath('//h1[@class="name"]/span/a/text()')[0]    return code, start_date, end_date

def download(code, start_date, end_date):    download_url = "http://quotes.money.163.com/service/chddata.html?code=1" + code + "&start=" + start_date + "&end=" + end_date + \                   "&fields=TCLOSE;HIGH;LOW;TOPEN;LCLOSE;CHG;PCHG;TURNOVER;VOTURNOVER;VATURNOVER;TCAP;MCAP"    print(download_url)    data = requests.get(download_url, headers=headers)    f = open(code + '.csv', 'wb')    for chunk in data.iter_content(chunk_size=10000):        if chunk:            f.write(chunk)    print('股票---', code, '历史数据正在下载')

download('000002', '20210401', '20210516')

提取的数据结果如下

图片

2、新浪财经API

2.1股票

from urllib import requestimport jsonimport pandas as pd

def get_stock_data(id, scale, data_len):    '''    symnol = 股票代码    scale = 5,15,30,60 时间间隔    datalen = 获取数据长度,最大1023    '''    # 拼接API的url    url = 'http://quotes.sina.cn/cn/api/json_v2.php/CN_MarketDataService.getKLineData?symbol={0}&scale={1}&datalen={2}'.format(        id, scale, data_len)    # 发起请求    req = request.Request(url)    # 获取响应    rsp = request.urlopen(req)    # 读取响应结果    res = rsp.read()    # 将json序列转换为Python对象    res_json = json.loads(res)    # bar列表    bar_list = []    # 将结果逆序    res_json.reverse()    # 遍历列表    for dict in res_json:        bar = {}        bar['date'] = dict['day']        bar['open'] = float(dict['open'])        bar['high'] = float(dict['high'])        bar['low'] = float(dict['low'])        bar['close'] = float(dict['close'])        bar['vol'] = int(dict['volume'])        bar_list.append(bar)    # 将结果转换为DataFrame对象    df = pd.DataFrame(data=bar_list)    print(df)    return df

df = get_stock_data('sz002415', 5, 30)df.head()

图片

2.2 期货

from urllib import requestimport jsonimport pandas as pd

def get_future_data(id, scale):    # 拼接API的url    url = 'http://stock2.finance.sina.com.cn/futures/api/json.php/IndexService.getInnerFuturesMiniKLine{0}m?symbol={1}'.format(scale, id)    # 发起请求    req = request.Request(url)    # 获取响应    rsp = request.urlopen(req)    # 读取响应结果    res = rsp.read()    # 将json序列转换为Python对象    res_json = json.loads(res)    # bar列表#     print(res_json)    bar_list = []    # 将结果逆序    res_json.reverse()    # 遍历列表    for line in res_json:        bar = {}        bar['date'] = line[0]        bar['open'] = float(line[1])        bar['high'] = float(line[2])        bar['low'] = float(line[3])        bar['close'] = float(line[4])        bar['vol'] = int(line[5])        bar_list.append(bar)    # 将结果转换为DataFrame对象    df = pd.DataFrame(data=bar_list)    print(df)    return df

df = get_future_data('rb1910', 5)df.head()

图片

3、其他的股票接口

3.1 东方财富接口

pdfm.eastmoney.com/EM_UBG_PDTI…

rtntype = 返回数据格式,支持:1,2,3,4,5,6id = 股票代码,后面多加个1type = k线类型,m5k,m15k,m30k,m60k

返回结果,注意结果为jsonp格式,需要去掉前后括号

[{"time":"2018-11-21 10:00","open":"3187.10","close":"3214.17","high":"3221.20","low":"3185.24","volume":"24250345","amount":"244亿","amplitude":"-","turnoverrate":"0"},{"time":"2018-11-21 10:30","open":"3213.24","close":"3213.52","high":"3230.12","low":"3210.60","volume":"13652304","amount":"138亿","amplitude":"0.61%","turnoverrate":"0"}]

凤凰网接口

api.finance.ifeng.com/akmin?scode…

  • scode = 股票代码
  • type = k线类型
{  "record": [    [      "2018-10-31 11:00:00", # 日期      "3146.23", # 开盘价      "3146.23", # 最高价      "3130.41", # 收盘价      "3130.21", # 最低价      107709,    # 成交量      "-15.82",  # 价格变动      -0.5,      # 涨跌幅      "3130.04", # 5日均价      "3119.8",  # 10日均价      "3109.55", # 20日均价      159535,    # 5日均量      150064,    # 10日均量      138100,    # 20日均量      0          # 换手率[注:指数无此项]    ],    [      "2018-10-31 11:30:00",      "3130.19",      "3144.97",      "3143.7",      "3126.95",      105828,      "13.51",      0.43,      "3132.92",      "3126.49",      "3107.94",      160857,      147627,      137719,      0    ]  ]}

证券之星

cq.ssajax.cn/interact/ge…

  • 000300 股票代码
  • 1 标识沪,2 标识深
  • 周期,1: 每分钟,2:5分钟K线,4:30分钟K线,6:日K线,7:周K线,8:月K线

结果数据与同花顺数据存在差异

{  "type": 'ThirtyMinutesK',  "code": '000300',  "picWidth": 630,  "left": 46,  "right": 46,  "top": 18,  "bottom": 3,  "mainHeight": 137.6087,  "count": 80,  "IsIndex": true,  "datas": [ ['2019-1-2', '3017.07', '3018.78', '2976.94', '2977.05', '-33.61', '-1.12%', '1830.1744万手', '2099974.5988亿元', ''] ['2019-1-2', '2977.90', '2982.50', '2972.32', '2975.34', '-1.71', '-0.06%', '870.7015万手', '1014299.3089亿元', ''] ['2019-1-2', '2975.13', '2979.70', '2968.10', '2976.03', '0.70', '0.02%', '662.5779万手', '774487.0416亿元', ''] ['2019-1-2', '2975.48', '2975.77', '2969.99', '2972.75', '-3.28', '-0.11%', '512.8981万手', '561504.6466亿元', ''] ['2019-1-2', '2973.24', '2974.20', '2963.05', '2963.05', '-9.70', '-0.33%', '520.6500万手', '555401.0954亿元', ''] ['2019-1-2', '2963.28', '2968.06', '2958.49', '2959.38', '-3.66', '-0.12%', '652.6460万手', '706160.9067亿元', ''] ['2019-1-2', '2959.49', '2976.24', '2958.53', '2976.24', '16.86', '0.57%', '777.2934万手', '814835.7428亿元', ''] ['2019-1-2', '2976.06', '2976.49', '2967.92', '2969.54', '-6.71', '-0.23%', '873.9827万手', '892372.3176亿元', ''] ['2019-1-3', '2963.02', '2986.05', '2953.50', '2984.97', '15.43', '0.52%', '1644.8468万手', '1847877.8024亿元', ''] ['2019-1-3', '2985.19', '3000.23', '2979.27', '2981.37', '-3.60', '-0.12%', '1368.3392万手', '1468697.7891亿元', ''] ['2019-1-3', '2980.99', '2982.08', '2968.90', '2969.30', '-12.07', '-0.40%', '732.6996万手', '773648.5164亿元', ''] ['2019-1-3', '2969.35', '2969.70', '2959.27', '2968.37', '-0.92', '-0.03%', '652.7249万手', '736984.9307亿元', ''] ['2019-1-3', '2968.24', '2968.24', '2957.01', '2966.63', '-1.75', '-0.06%', '505.6024万手', '588579.1725亿元', ''] ['2019-1-3', '2966.86', '2970.24', '2961.55', '2968.43', '1.80', '0.06%', '625.2699万手', '628144.8810亿元', ''] ['2019-1-3', '2968.56', '2968.70', '2957.19', '2959.19', '-9.24', '-0.31%', '643.2986万手', '673772.6590亿元', ''] ['2019-1-3', '2959.17', '2964.84', '2953.94', '2964.84', '5.65', '0.19%', '913.9289万手', '948774.1302亿元', '']]}

和讯网

webstock.quote.hermes.hexun.com/a/kline?cod…

5,15,30,60 统计时间和其他不一样

{  "KLine": [    {      "Time": "时间"    },    {      "LastClose": "前收盘价"    },    {      "Open": "开盘价"    },    {      "Close": "收盘价"    },    {      "High": "最高价"    },    {      "Low": "最低价"    },    {      "Volume": "成交量"    },    {      "Amount": "成交额"    }  ],  "TABLE": [    {      "KLine[]": "K线列表"    },    {      "BeginTime": "最早时间"    },    {      "EndTime": "最后时间"    },    {      "Total": "总数"    },    {      "PriceWeight": "价格倍数"    }  ],  "Data": [    [       [        20181226140000,        300240,        300224,        300750,        301374,        300163,        770036600,        6793688860      ]          ],    20181109130000,    20190103143000,    300,    100  ]}