011:获取上证50的所有股票代码,并下载各个股K线数到excel表中

2023-10-12 06:52

本文主要是介绍011:获取上证50的所有股票代码,并下载各个股K线数到excel表中,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

我们结合《获取上证50的所有股票代码》,《根据股票代码和起始日期获取K线数据到excel表》两文中的脚本,搞出新的脚本:
 

import tkinter as tk
from tkinter import messagebox
from tkcalendar import Calendar
import pandas as pd
import requests
from urllib.parse import urlencode
import requests
from bs4 import BeautifulSoup
import os
import shutildef gen_secid(rawcode: str) -> str:'''生成东方财富专用的secidParameters----------rawcode : 6 位股票代码Return------str: 指定格式的字符串'''# 沪市指数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, end: str, klt: int = 101, fqt: int = 1) -> pd.DataFrame:'''功能获取k线数据-参数code : 6 位股票代码beg: 开始日期 例如 20200101end: 结束日期 例如 20200201klt: k线间距 默认为 101 即日kklt:1 1 分钟klt:5 5 分钟klt:101 日klt:102 周fqt: 复权方式不复权 : 0前复权 : 1后复权 : 2 '''EastmoneyKlines = {'f51': '日期','f52': '开盘','f53': '收盘','f54': '最高','f55': '最低','f56': '成交量','f57': '成交额','f58': '振幅','f59': '涨跌幅','f60': '涨跌额','f61': '换手率',}EastmoneyHeaders = {'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'] = secidurl = base_url+'?'+urlencode(params)json_response: dict = 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 dfdef select_start_date():def on_date_selected():selected_date = cal.selection_get()start_date_entry.delete(0, tk.END)start_date_entry.insert(0, selected_date.strftime('%Y%m%d'))top.destroy()top = tk.Toplevel(root)cal = Calendar(top, selectmode='day')cal.pack()confirm_button = tk.Button(top, text='确认', command=on_date_selected)confirm_button.pack()def select_end_date():def on_date_selected():selected_date = cal.selection_get()end_date_entry.delete(0, tk.END)end_date_entry.insert(0, selected_date.strftime('%Y%m%d'))top.destroy()top = tk.Toplevel(root)cal = Calendar(top, selectmode='day')cal.pack()confirm_button = tk.Button(top, text='确认', command=on_date_selected)confirm_button.pack()def get_kline_data(code,index):# code = stock_code_entry.get()start_date = start_date_entry.get()end_date = end_date_entry.get()# 修改文件保存的位置save_path = os.path.join('sz50_all_k_data', f'{code}.csv')try:df = get_k_history(code, start_date, end_date)df.to_csv(save_path, encoding='utf-8-sig', index=None)print(index,'提示', f'股票代码:{code} 的 k线数据已保存到代码目录下的 {code}.csv 文件中')except:print(index,'错误',{code}, '获取K线数据失败')def get_sz50_all_data():url = "https://q.stock.sohu.com/cn/bk_4272.shtml"response = requests.get(url)soup = BeautifulSoup(response.text, "html.parser")# 找到包含class为'e1'的元素elements = soup.find_all(class_="e1")# 提取数据并剔除非数字的成员data_list = [element.text for element in elements if element.text.isdigit()]# 打印list最终的成员print(data_list)#遍历所有成员,并调用get_kline_data# 检查并创建目录if not os.path.exists('sz50_all_k_data'):os.makedirs('sz50_all_k_data')else:shutil.rmtree('sz50_all_k_data')os.makedirs('sz50_all_k_data')index=0for code_tmp in data_list:index += 1get_kline_data(code_tmp,index)print(">>>>>>>>>>>>>>>>完成")root = tk.Tk()
root.title('上证50所有个股数据获取')# stock_code_label = tk.Label(root, text='股票代码')
# stock_code_label.pack()
# stock_code_entry = tk.Entry(root)
# stock_code_entry.pack()start_date_label = tk.Label(root, text='起始日期')
start_date_label.pack()
start_date_entry = tk.Entry(root)
start_date_entry.pack()select_start_date_button = tk.Button(root, text='选择日期', command=select_start_date)
select_start_date_button.pack()end_date_label = tk.Label(root, text='结束日期')
end_date_label.pack()
end_date_entry = tk.Entry(root)
end_date_entry.pack()select_end_date_button = tk.Button(root, text='选择日期', command=select_end_date)
select_end_date_button.pack()get_data_button = tk.Button(root, text='获取K线数据', command=get_sz50_all_data)
get_data_button.pack()root.mainloop()

效果:

保存到名为sz50_all_k_data的文件夹中:

这篇关于011:获取上证50的所有股票代码,并下载各个股K线数到excel表中的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/194107

相关文章

Python版本信息获取方法详解与实战

《Python版本信息获取方法详解与实战》在Python开发中,获取Python版本号是调试、兼容性检查和版本控制的重要基础操作,本文详细介绍了如何使用sys和platform模块获取Python的主... 目录1. python版本号获取基础2. 使用sys模块获取版本信息2.1 sys模块概述2.1.1

Java发送SNMP至交换机获取交换机状态实现方式

《Java发送SNMP至交换机获取交换机状态实现方式》文章介绍使用SNMP4J库(2.7.0)通过RCF1213-MIB协议获取交换机单/多路状态,需开启SNMP支持,重点对比SNMPv1、v2c、v... 目录交换机协议SNMP库获取交换机单路状态获取交换机多路状态总结交换机协议这里使用的交换机协议为常

前端导出Excel文件出现乱码或文件损坏问题的解决办法

《前端导出Excel文件出现乱码或文件损坏问题的解决办法》在现代网页应用程序中,前端有时需要与后端进行数据交互,包括下载文件,:本文主要介绍前端导出Excel文件出现乱码或文件损坏问题的解决办法,... 目录1. 检查后端返回的数据格式2. 前端正确处理二进制数据方案 1:直接下载(推荐)方案 2:手动构造

C#利用Free Spire.XLS for .NET复制Excel工作表

《C#利用FreeSpire.XLSfor.NET复制Excel工作表》在日常的.NET开发中,我们经常需要操作Excel文件,本文将详细介绍C#如何使用FreeSpire.XLSfor.NET... 目录1. 环境准备2. 核心功能3. android示例代码3.1 在同一工作簿内复制工作表3.2 在不同

MyBatis/MyBatis-Plus同事务循环调用存储过程获取主键重复问题分析及解决

《MyBatis/MyBatis-Plus同事务循环调用存储过程获取主键重复问题分析及解决》MyBatis默认开启一级缓存,同一事务中循环调用查询方法时会重复使用缓存数据,导致获取的序列主键值均为1,... 目录问题原因解决办法如果是存储过程总结问题myBATis有如下代码获取序列作为主键IdMappe

C#使用iText获取PDF的trailer数据的代码示例

《C#使用iText获取PDF的trailer数据的代码示例》开发程序debug的时候,看到了PDF有个trailer数据,挺有意思,于是考虑用代码把它读出来,那么就用到我们常用的iText框架了,所... 目录引言iText 核心概念C# 代码示例步骤 1: 确保已安装 iText步骤 2: C# 代码程

java读取excel文件为base64实现方式

《java读取excel文件为base64实现方式》文章介绍使用ApachePOI和EasyExcel处理Excel文件并转换为Base64的方法,强调EasyExcel适合大文件且内存占用低,需注意... 目录使用 Apache POI 读取 Excel 并转换为 Base64使用 EasyExcel 处

Spring Boot中获取IOC容器的多种方式

《SpringBoot中获取IOC容器的多种方式》本文主要介绍了SpringBoot中获取IOC容器的多种方式,包括直接注入、实现ApplicationContextAware接口、通过Spring... 目录1. 直接注入ApplicationContext2. 实现ApplicationContextA

Python Excel 通用筛选函数的实现

《PythonExcel通用筛选函数的实现》本文主要介绍了PythonExcel通用筛选函数的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着... 目录案例目的示例数据假定数据来源是字典优化:通用CSV数据处理函数使用说明使用示例注意事项案例目的第一

Java利用Spire.XLS for Java设置Excel表格边框

《Java利用Spire.XLSforJava设置Excel表格边框》在日常的业务报表和数据处理中,Excel表格的美观性和可读性至关重要,本文将深入探讨如何利用Spire.XLSforJava库... 目录Spire.XLS for Java 简介与安装Maven 依赖配置手动安装 JAR 包核心API介