【Python】通过Baostock轻松获取股票数据

 【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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

William数据分析

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值