How to Retrieve Real-Time Minute-Level Stock Data with Python
This guide explains how to use Python, pandas, and requests to fetch minute‑by‑minute K‑line data for Chinese stocks from Eastmoney's API, generate the required secid, handle different market codes, and continuously save the data until market close.
Code Demonstration
Fetch Daily Minute‑Line Data
from urllib.parse import urlencode
import pandas as pd
import requests
def gen_secid(rawcode: str) -> str:
'''Generate Eastmoney‑specific secid.
Parameters
----------
rawcode : 6‑digit stock code
Returns
-------
str: formatted secid string
'''
# Shanghai market index
if rawcode[:3] == '000':
return f'1.{rawcode}'
# Shenzhen market index
if rawcode[:3] == '399':
return f'0.{rawcode}'
# Shanghai A‑share stocks
if rawcode[0] != '6':
return f'0.{rawcode}'
# Shenzhen A‑share stocks
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.
Parameters
----------
code : 6‑digit stock code
beg : start date, e.g., 20200101
end : end date, e.g., 20200201
klt : K‑line interval (1‑minute, 5‑minute, daily=101, weekly=102, etc.)
fqt : adjustment type (0: none, 1: forward, 2: backward)
Returns
-------
DataFrame: stock 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: dict = requests.get(url, headers=EastmoneyHeaders).json()
data = json_response.get('data')
if data is None:
if secid[0] == '0':
secid = f'1.{code}'
else:
secid = 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:
kline = _kline.split(',')
rows.append(kline)
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 文件中')Fetch Current Day Minute Data (Run Every Minute Until Close)
from urllib.parse import urlencode
import pandas as pd
import requests
import time
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.'''
# (same implementation as above, omitted for brevity)
...
if __name__ == "__main__":
for _ in range(1000):
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 文件中')
if len(df) >= 240:
print('已收盘')
break
time.sleep(60)Runtime Environment
Python version requirement
Python 3
Required libraries
pandas requests
Install the libraries by opening a command prompt and running: pip install pandas requests Press Enter and wait until the installation finishes successfully.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
