当前位置: 首页 > news >正文

调用AkShare获取A股股票基本信息

文章目录

  • 调用AkShare获取A股股票基本信息
    • 安装`akshare`
    • 获取A股股票列表
    • 查询股票基本信息
    • 构造个股查询代码
    • 获取沪深股票的基本信息
    • 小结

调用AkShare获取A股股票基本信息

akshare

安装akshare

  • 使用pip
pip install akshare
  • 使用uv
uv add akshare
import akshare as ak

获取A股股票列表

使用stock_zh_a_spot_em()方法,获取股票列表,并保存起来。

# 获取所有A股实时行情数据(包含代码、名称等字段)
stock_spot_df = ak.stock_zh_a_spot_em()# 提取股票代码和名称列表
stock_list = stock_spot_df[["代码", "名称"]]# 去除重复的股票代码和名称
stock_list = stock_spot_df[["代码", "名称"]].drop_duplicates()# 保存为CSV文件
stock_list.to_csv("stock_list.csv", index=False, encoding="utf-8-sig")
  0%|          | 0/57 [00:00<?, ?it/s]

查询股票列表stock_list中某个股票的数据:

selected_stock = stock_list.loc[stock_list["代码"] == "000001", :]  # 选择某个股票作为示例
print(selected_stock)
          代码    名称
1417  000001  平安银行
query = stock_list.query("代码 == '000001'")  # 查询某个股票
print(query)
          代码    名称
1417  000001  平安银行

查询股票基本信息

通过stock_individual_basic_info_xq()方法,调用雪球数据,获取个股基本信息。

注意:股票代码需要带上交易所简写,否则会得到空数据。

# 获取股票的基本信息
stock_individual_basic_info_xq_df = ak.stock_individual_basic_info_xq(symbol="BJ920088")
print(stock_individual_basic_info_xq_df)
# 不带交易所缩写会获得空数据
empty_info_df = ak.stock_individual_basic_info_xq(symbol="920088")
print(empty_info_df)
empty_info_dict = empty_info_df.set_index("item")["value"].to_dict()
# 打印空数据字典
print(empty_info_dict)
                            item  \
0                         org_id   
1                    org_name_cn   
2              org_short_name_cn   
3                    org_name_en   
4              org_short_name_en   
5        main_operation_business   
6                operating_scope   
7                district_encode   
8            org_cn_introduction   
9           legal_representative   
10               general_manager   
11                     secretary   
12              established_date   
13                     reg_asset   
14                     staff_num   
15                     telephone   
16                      postcode   
17                           fax   
18                         email   
19                   org_website   
20                reg_address_cn   
21                reg_address_en   
22             office_address_cn   
23             office_address_en   
24               currency_encode   
25                      currency   
26                   listed_date   
27               provincial_name   
28             actual_controller   
29                   classi_name   
30                   pre_name_cn   
31                      chairman   
32               executives_nums   
33              actual_issue_vol   
34                   issue_price   
35             actual_rc_net_amt   
36              pe_after_issuing   
37  online_success_rate_of_issue   
38            affiliate_industry   value  
0                                          T003003664  
1                                     新疆科力新技术发展股份有限公司  
2                                                科力股份  
3   Xinjiang Keli New Technology Development Co.,Ltd.  
4                                                None  
5            油田生产过程中的技术服务、方案设计、油田化学助剂产品和油田专用设备的生产与销售。  
6     道路普通货物运输;总险货物运输;与石油天然气开采有关的辅助活动;化工产品、机械设备生产、...  
7                                              650203  
8   新疆科力新技术发展股份有限公司的主营业务是油田生产过程中的技术服务、方案设计、油田化学助剂产...  
9                                                  赵波  
10                                                 赵波  
11                                                宋小青  
12                                      1101571200000  
13                                         88071500.0  
14                                                581  
15                                     86-13999519990  
16                                             834000  
17                                     86-990-6866201  
18      songxiaoqing@xjkeli.com;klgf873234@xjkeli.com  
19                                      www.xkeli.com  
20                          新疆维吾尔自治区克拉玛依市克拉玛依区友谊路138号  
21                                               None  
22                          新疆维吾尔自治区克拉玛依市克拉玛依区友谊路138号  
23                                               None  
24                                             019001  
25                                                CNY  
26                                      1730131200000  
27                                           新疆维吾尔自治区  
28                                        赵波 (24.66%)  
29                                               民营企业  
30                                               None  
31                                                 赵波  
32                                                 15  
33                                         24150000.0  
34                                               7.32  
35                                        149887900.0  
36                                              14.26  
37                                               0.06  
38      {'ind_code': 'BK0007', 'ind_name': '油气开采及服务'}  item value
0                         org_id  None
1                    org_name_cn  None
2              org_short_name_cn  None
3                    org_name_en  None
4              org_short_name_en  None
5        main_operation_business  None
6                operating_scope  None
7                district_encode  None
8            org_cn_introduction  None
9           legal_representative  None
10               general_manager  None
11                     secretary  None
12              established_date  None
13                     reg_asset  None
14                     staff_num  None
15                     telephone  None
16                      postcode  None
17                           fax  None
18                         email  None
19                   org_website  None
20                reg_address_cn  None
21                reg_address_en  None
22             office_address_cn  None
23             office_address_en  None
24               currency_encode  None
25                      currency  None
26                   listed_date  None
27               provincial_name  None
28             actual_controller  None
29                   classi_name  None
30                   pre_name_cn  None
31                      chairman  None
32               executives_nums  None
33              actual_issue_vol  None
34                   issue_price  None
35             actual_rc_net_amt  None
36              pe_after_issuing  None
37  online_success_rate_of_issue  None
{'org_id': None, 'org_name_cn': None, 'org_short_name_cn': None, 'org_name_en': None, 'org_short_name_en': None, 'main_operation_business': None, 'operating_scope': None, 'district_encode': None, 'org_cn_introduction': None, 'legal_representative': None, 'general_manager': None, 'secretary': None, 'established_date': None, 'reg_asset': None, 'staff_num': None, 'telephone': None, 'postcode': None, 'fax': None, 'email': None, 'org_website': None, 'reg_address_cn': None, 'reg_address_en': None, 'office_address_cn': None, 'office_address_en': None, 'currency_encode': None, 'currency': None, 'listed_date': None, 'provincial_name': None, 'actual_controller': None, 'classi_name': None, 'pre_name_cn': None, 'chairman': None, 'executives_nums': None, 'actual_issue_vol': None, 'issue_price': None, 'actual_rc_net_amt': None, 'pe_after_issuing': None, 'online_success_rate_of_issue': None}
# 将股票基本信息转换为JSON格式
info_json = stock_individual_basic_info_xq_df.to_json(orient="records", force_ascii=False)
print(info_json)
[{"item":"org_id","value":"T003003664"},{"item":"org_name_cn","value":"新疆科力新技术发展股份有限公司"},{"item":"org_short_name_cn","value":"科力股份"},{"item":"org_name_en","value":"Xinjiang Keli New Technology Development Co.,Ltd."},{"item":"org_short_name_en","value":null},{"item":"main_operation_business","value":"油田生产过程中的技术服务、方案设计、油田化学助剂产品和油田专用设备的生产与销售。"},{"item":"operating_scope","value":"  道路普通货物运输;总险货物运输;与石油天然气开采有关的辅助活动;化工产品、机械设备生产、销售及租赁;房屋及厂房租赁;技术推广服务;化工石油设各管道安装工程、机电设备安装工程、防腐保温工程、管道工程、化工石油工程、房屋建筑工程、钢结构工程;货物与技术的进出口业务;污水处理及其再生利用;水污染治理。(依法须经批准的项目,经相关部门批准后方可开展经营活动)"},{"item":"district_encode","value":"650203"},{"item":"org_cn_introduction","value":"新疆科力新技术发展股份有限公司的主营业务是油田生产过程中的技术服务、方案设计、油田化学助剂产品和油田专用设备的生产与销售。公司的主要产品是技术服务、产品销售、设备销售、其他业务。公司是国家高新技术企业、国家级专精特新“小巨人”企业。"},{"item":"legal_representative","value":"赵波"},{"item":"general_manager","value":"赵波"},{"item":"secretary","value":"宋小青"},{"item":"established_date","value":1101571200000},{"item":"reg_asset","value":88071500.0},{"item":"staff_num","value":581},{"item":"telephone","value":"86-13999519990"},{"item":"postcode","value":"834000"},{"item":"fax","value":"86-990-6866201"},{"item":"email","value":"songxiaoqing@xjkeli.com;klgf873234@xjkeli.com"},{"item":"org_website","value":"www.xkeli.com"},{"item":"reg_address_cn","value":"新疆维吾尔自治区克拉玛依市克拉玛依区友谊路138号"},{"item":"reg_address_en","value":null},{"item":"office_address_cn","value":"新疆维吾尔自治区克拉玛依市克拉玛依区友谊路138号"},{"item":"office_address_en","value":null},{"item":"currency_encode","value":"019001"},{"item":"currency","value":"CNY"},{"item":"listed_date","value":1730131200000},{"item":"provincial_name","value":"新疆维吾尔自治区"},{"item":"actual_controller","value":"赵波 (24.66%)"},{"item":"classi_name","value":"民营企业"},{"item":"pre_name_cn","value":null},{"item":"chairman","value":"赵波"},{"item":"executives_nums","value":15},{"item":"actual_issue_vol","value":24150000.0},{"item":"issue_price","value":7.32},{"item":"actual_rc_net_amt","value":149887900.0},{"item":"pe_after_issuing","value":14.26},{"item":"online_success_rate_of_issue","value":0.06},{"item":"affiliate_industry","value":{"ind_code":"BK0007","ind_name":"油气开采及服务"}}]
# 将股票基本信息转换为字典格式,并根据K-V对进行转换,形成一个json(字典)对象。
info_dict = stock_individual_basic_info_xq_df.set_index("item")["value"].to_dict()
print(info_dict)
{'org_id': 'T003003664', 'org_name_cn': '新疆科力新技术发展股份有限公司', 'org_short_name_cn': '科力股份', 'org_name_en': 'Xinjiang Keli New Technology Development Co.,Ltd.', 'org_short_name_en': None, 'main_operation_business': '油田生产过程中的技术服务、方案设计、油田化学助剂产品和油田专用设备的生产与销售。', 'operating_scope': '\u3000\u3000道路普通货物运输;总险货物运输;与石油天然气开采有关的辅助活动;化工产品、机械设备生产、销售及租赁;房屋及厂房租赁;技术推广服务;化工石油设各管道安装工程、机电设备安装工程、防腐保温工程、管道工程、化工石油工程、房屋建筑工程、钢结构工程;货物与技术的进出口业务;污水处理及其再生利用;水污染治理。(依法须经批准的项目,经相关部门批准后方可开展经营活动)', 'district_encode': '650203', 'org_cn_introduction': '新疆科力新技术发展股份有限公司的主营业务是油田生产过程中的技术服务、方案设计、油田化学助剂产品和油田专用设备的生产与销售。公司的主要产品是技术服务、产品销售、设备销售、其他业务。公司是国家高新技术企业、国家级专精特新“小巨人”企业。', 'legal_representative': '赵波', 'general_manager': '赵波', 'secretary': '宋小青', 'established_date': 1101571200000, 'reg_asset': 88071500.0, 'staff_num': 581, 'telephone': '86-13999519990', 'postcode': '834000', 'fax': '86-990-6866201', 'email': 'songxiaoqing@xjkeli.com;klgf873234@xjkeli.com', 'org_website': 'www.xkeli.com', 'reg_address_cn': '新疆维吾尔自治区克拉玛依市克拉玛依区友谊路138号', 'reg_address_en': None, 'office_address_cn': '新疆维吾尔自治区克拉玛依市克拉玛依区友谊路138号', 'office_address_en': None, 'currency_encode': '019001', 'currency': 'CNY', 'listed_date': 1730131200000, 'provincial_name': '新疆维吾尔自治区', 'actual_controller': '赵波 (24.66%)', 'classi_name': '民营企业', 'pre_name_cn': None, 'chairman': '赵波', 'executives_nums': 15, 'actual_issue_vol': 24150000.0, 'issue_price': 7.32, 'actual_rc_net_amt': 149887900.0, 'pe_after_issuing': 14.26, 'online_success_rate_of_issue': 0.06, 'affiliate_industry': {'ind_code': 'BK0007', 'ind_name': '油气开采及服务'}}

构造个股查询代码

从雪球接口的规则来看,输入参数除了股票代码外,还要加上交易所缩写,那么需要先对查询出来的股票列表进行代码转换。

def get_stock_code_for_xq(symbol):"""获取股票代码的函数:param symbol: 股票代码:return: 股票代码"""if symbol.startswith("0") or symbol.startswith("3"):return f"SZ{symbol}"elif symbol.startswith("6"):return f"SH{symbol}" else:return f"BJ{symbol}"

获取沪深股票的基本信息

遍历之前获得的股票列表,逐个获取个股基本信息。

from tqdm.notebook import tqdm
basic_info_list = []
progress_bar = tqdm(total=len(stock_list), desc="Processing stocks")
for index, row in stock_list.iterrows():stock_code = get_stock_code_for_xq(row["代码"])try:stock_info_df = ak.stock_individual_basic_info_xq(symbol=stock_code)stock_info = stock_info_df.set_index("item")["value"].to_dict() if not stock_info_df.empty else {}# 将股票代码和名称与基本信息合并basic_info_list.append({**{"code": row["代码"], "name": row["名称"]}, **stock_info})        progress_bar.update(1)except ValueError:print(f"Error fetching data for stock code: {stock_code}")basic_info_list.append({"code": row["代码"], "name": row["名称"], **empty_info_dict})progress_bar.update(1)continue
Processing stocks:   0%|          | 0/5723 [00:00<?, ?it/s]Error fetching data for stock code: SH603003
Error fetching data for stock code: SZ002750
Error fetching data for stock code: SH600804
Error fetching data for stock code: SZ002336
Error fetching data for stock code: SH603400
Error fetching data for stock code: SZ301678

在实际使用的过程中,发现获取上面打印输出的这几个股票时,出现值错误ValueError

import pandas as pd
# 关闭进度条
progress_bar.close()
# 将基本信息列表转换为DataFrame
basic_info_xq_df = pd.DataFrame(basic_info_list)
# 保存为CSV文件
basic_info_xq_df.to_csv("basic_info_xq.csv", index=False, encoding="utf-8-sig")
# 保存为xlsx文件
basic_info_xq_df.to_excel("basic_info_xq.xlsx", index=False)

根据雪球个股简介页内容,重命名表头,让数据更具可读性。

# 重命名列名,并返回一个新的DataFrame
column_mapping = {"code": "代码","name": "名称","org_id": "公司ID","org_name_cn": "公司名称","org_short_name_cn": "公司简称","org_name_en": "公司英文名称","org_short_name_en": "公司英文简称","main_operation_business": "主营业务","operating_scope": "经营范围","district_encode": "地区编码","org_cn_introduction": "公司简介","legal_representative": "法定代表人","general_manager": "总经理","secretary": "董事会秘书","established_date": "成立日期","reg_asset": "注册资本","staff_num": "员工人数","telephone": "联系电话","postcode": "邮政编码","fax": "传真","email": "电子邮箱","org_website": "公司网站","reg_address_cn": "注册地址","reg_address_en": "注册英文地址","office_address_cn": "办公地址","office_address_en": "办公英文地址","currency_encode": "货币编码","currency": "货币","listed_date": "上市日期","provincial_name": "所属省份","actual_controller": "实际控制人","classi_name": "所有制性质名称", "pre_name_cn": "曾用名","chairman": "董事长","executives_nums": "管理层人数","actual_issue_vol": "发行量","issue_price": "发行价格","actual_rc_net_amt": "募集资金","pe_after_issuing": "发行市盈率","online_success_rate_of_issue": "网上中签率","affiliate_industry": "相关行业"
}# 返回新的DataFrame
xq_df_cn = basic_info_xq_df.rename(columns=column_mapping, inplace=False)
xq_df_cn.to_excel("个股基本信息表.xlsx", index=False)

小结

本文通过 AkShare 获取了 A 股市场全部股票的实时行情和基本信息,并实现了批量查询、数据清洗、异常处理和中英文字段映射。最终,整理输出了结构化的个股基本信息表(支持 CSV、Excel 格式),为后续的数据分析和可视化打下数据基础。

相关文章:

  • echarts 地图 tooltip内部添加点击事件
  • 【linux】驱动学习问题及解决方法
  • E10集成登录三方系统
  • 深度学习神经网络架构Transformer深刻理解
  • 砂石骨料数字孪生工厂应用案例:远眺科技三维可视化落地成效
  • Vue3 + Element Plus中el-table加载状态分析
  • 4步使用 vue3 路由
  • Java机器学习全攻略:从基础原理到实战案例详解
  • 【IEEE/EI/Scopus检索】2025年第五届机器学习与大数据管理国际会议 (MLBDM 2025)
  • C# 结构(属性和字段初始化语句和结构是密封的)
  • 机器学习算法_聚类KMeans算法
  • Mac电脑数据恢复工具-Disk 企业版
  • 使用 ollama 在 mac 本地部署一个 qwen3:8b 模型
  • mac安装mvnd结合idea
  • Wi-Fi 6 在 2.4GHz 频段的速率与优化分析
  • 数据可视化——一图胜千言
  • Kafka环境搭建全攻略:从Docker到Java实战
  • Visual Studio Code 1.101.0 官方版
  • 列举开源的模型和推理框架
  • 【Java学习笔记】集合介绍
  • 学校网站风格/鸡西seo
  • 厦门 网站制作/如何自建网站?
  • 有一个做ppt的网站/域名交易
  • 网站建设公司营业执照/海外营销公司
  • 郑州本地做团购的网站/百度权重划分等级
  • 网站开发网站设计素材/大数据营销名词解释