Big Data 8 min read

Python Script for Retrieving Minute‑Level Stock K‑Line Data from Eastmoney

This article provides a Python tutorial that explains how to generate Eastmoney‑specific security IDs, request minute‑level K‑line data for a given stock code via the Eastmoney API, process the response into a pandas DataFrame, and continuously fetch and save data until market close.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python Script for Retrieving Minute‑Level Stock K‑Line Data from Eastmoney

This guide demonstrates how to fetch minute‑level K‑line (candlestick) data for Chinese stocks using Python. It includes functions to construct the required Eastmoney security identifier (secid) and to request historical K‑line data with customizable parameters such as start/end dates, interval (klt), and adjustment type (fqt).

The gen_secid function determines the correct prefix based on the stock code prefix, handling Shanghai and Shenzhen markets. The get_k_history function builds request parameters, sends an HTTP GET request to the Eastmoney API, parses the JSON response, and converts the raw K‑line strings into a pandas DataFrame with appropriate column names.

from urllib.parse import urlencode
import pandas as pd
import requests

def gen_secid(rawcode: str) -> str:
    '''Generate Eastmoney-specific secid'''
    if rawcode[:3] == '000':
        return f'1.{rawcode}'
    if rawcode[:3] == '399':
        return f'0.{rawcode}'
    if rawcode[0] != '6':
        return f'0.{rawcode}'
    return f'1.{rawcode}'

def get_k_history(code: str, beg: str = '16000101', end: str = '20500101', klt: int = 1, fqt: int = 1) -> pd.DataFrame:
    '''Fetch K‑line data'''
    EastmoneyKlines = {
        'f51': '日期', 'f52': '开盘', 'f53': '收盘', 'f54': '最高',
        'f55': '最低', 'f56': '成交量', 'f57': '成交额',
        'f58': '振幅', 'f59': '涨跌幅', 'f60': '涨跌额', 'f61': '换手率'
    }
    EastmoneyHeaders = {
        'Host': '19.push2.eastmoney.com',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; Touch; rv:11.0) like Gecko',
        'Accept': '*/*',
        'Accept-Language': 'zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2',
        'Referer': 'http://quote.eastmoney.com/center/gridlist.html'
    }
    fields = list(EastmoneyKlines.keys())
    columns = list(EastmoneyKlines.values())
    fields2 = ",".join(fields)
    secid = gen_secid(code)
    params = (
        ('fields1', 'f1,f2,f3,f4,f5,f6,f7,f8,f9,f10,f11,f12,f13'),
        ('fields2', fields2), ('beg', beg), ('end', end),
        ('rtntype', '6'), ('secid', secid), ('klt', f'{klt}'), ('fqt', f'{fqt}')
    )
    params = dict(params)
    base_url = 'https://push2his.eastmoney.com/api/qt/stock/kline/get'
    url = base_url + '?' + urlencode(params)
    json_response = requests.get(url, headers=EastmoneyHeaders).json()
    data = json_response.get('data')
    if data is None:
        # retry with opposite market prefix
        secid = f'1.{code}' if secid[0] == '0' else f'0.{code}'
        params['secid'] = secid
        url = base_url + '?' + urlencode(params)
        json_response = requests.get(url, headers=EastmoneyHeaders).json()
        data = json_response.get('data')
        if data is None:
            print('股票代码:', code, '可能有误')
            return pd.DataFrame(columns=columns)
    klines = data['klines']
    rows = []
    for _kline in klines:
        rows.append(_kline.split(','))
    df = pd.DataFrame(rows, columns=columns)
    return df

if __name__ == "__main__":
    code = '600519'
    df = get_k_history(code)
    df.to_csv(f'{code}.csv', encoding='utf-8-sig', index=None)
    print(f'股票代码:{code} 的 k线数据已保存到代码目录下的 {code}.csv 文件中')

The script requires Python 3 and the external libraries pandas and requests , which can be installed via pip install pandas requests . It can be run repeatedly (e.g., every minute) until the DataFrame reaches 240 rows, indicating market close, after which the loop exits.

Overall, this tutorial offers a practical example of data acquisition and preprocessing for financial time‑series analysis, suitable for developers working with stock market data pipelines.

PythonAPIpandasRequestsfinancial datastock datakline
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.