【Python】通过Baostock轻松获取股票数据
# 通过baostock获取股票数据
# # 2024-07-26
# author: William 15989775065
import baostock as bs
import pandas as pd
# login to baostock
lg = bs.login()
print('login respond error_code:'+lg.error_code)
print('login respond error_msg:'+lg.error_msg)
# read the stock codes from an Excel file
codes = pd.read_excel("待获取股票代码.xls")['股票代码'].astype(str).tolist()
# pad stock codes with leading zeros if necessary
codes = [code.zfill(6) for code in codes]
# 6 开头的是上证,其他是深证
codes = ['sh.' + code if code.startswith('6') else 'sz.' + code for code in codes]
# create an empty list to store the results
data_list = []
# loop through the stock codes and retrieve the data
for index, code in enumerate(codes):
print(f'{index+1}、{code}',end='')
# retrieve the stock name
rs = bs.query_stock_basic(code)
data = rs.get_row_data()
if data:
name = data[1]
else:
name = ''
print(name)
# retrieve the historical data
rs = bs.query_history_k_data_plus(code,
"date,code,open,close",
start_date='2024-07-22', end_date='2024-07-26',
frequency="d", adjustflag="3")
while (rs.error_code == '0') & rs.next():
data2 = rs.get_row_data()
print(data2)
data2.append(name)
data_list.append(data2)
# convert the list of dictionaries to a pandas DataFrame
result = pd.DataFrame(data_list, columns=['date', 'code','open', 'close', 'name' ])
# write the results to an Excel file
result.to_excel("股票查询结果.xlsx", index=False)
print(result)
# logout from baostock
bs.logout()