抓取K线数据

# -*- coding: utf-8 -*-
from os import makedirs
from os.path import join
import json

import requests
from pandas import DataFrame

def download_k(stock_code):
    if stock_code[0] == '6':
        tag = 'sh'
    else:
        tag = 'sz'
    full_code = "%s%s" % (tag, stock_code)

    # 可以自己指定其它时间。其中2019-12-31是起始时间,2020-12-01是结束时间,
    # 300是天数(其实没有用,但是还必须有个数,否则返回数据有问题)
    url = "http://web.ifzq.gtimg.cn/appstock/app/fqkline/get?param=%s,day,2019-12-31,2020-12-01,300,qfq" % (full_code)
    html = requests.get(url)
    data = json.loads(html.text)

    # 有一些公司有分红或者拆股,价格会出现前复权(qfq)的标记,所以需要做一个识别
    if 'qfqday' in data['data'][full_code]:
        key = 'qfqday'
    elif 'day' in data['data'][full_code]:
        key = 'day'
    else:
        key = 'day'

    df = DataFrame(data['data'][full_code][key][:][:])
    df = DataFrame(df[[0, 1, 2, 3, 4, 5]])
    df.columns = ['date', 'start', 'end', 'high', 'low', 'volume']

    dir_path = "./csv/%s" % stock_code
    makedirs(dir_path, exist_ok=True)
    file_path = join(dir_path, "%s_%s.csv" % (stock_code, 'kline'))
    df.to_csv(file_path, index=False, encoding="gbk")
本文链接地址:https://const.net.cn/679.html

标签: none

添加新评论