#获取所有A股股票最新数据并写入 Excel 文件
import akshare as ak
import pandas as pd
import os
import schedule
import time
import logging
# 获取某只股票历史数据并写入 Excel 文件
stock_data = ak.stock_zh_a_hist(
symbol="000937",
start_date="20220101",
end_date="20250512",
# 设置复权类型,可选前复权(qfq)、后复权(hfq)或不复权,此处注释掉表示暂不设置
# adjust="qfq" # 可选前复权、后复权或不复权
)
# 定义要写入数据的 Excel 文件路径
excel_path = "stock_data_000937.xlsx"
# 将 Excel 文件路径与当前脚本所在目录拼接,确保文件保存在脚本同目录下
excel_path = os.path.join(os.path.dirname(__file__), excel_path)
try:
# 将获取到的股票数据写入 Excel 文件,不包含索引列
stock_data.to_excel(excel_path, index=False)
# 打印成功信息,提示数据已成功写入指定文件
print(f"数据已成功写入到 {excel_path} 文件中!")
except Exception as e:
# 若写入过程中出现异常,打印错误信息
print(f"写入 Excel 文件时出错: {e}")
#定义一个函数,用于获取并保存股票最新股价数据
def get_and_save_stock_data():
"""
从东方财富获取最新的 A 股股票数据,并将其保存到一个 Excel 文件中。
文件名包含时间戳,且文件会存储在脚本所在的同一目录下。
记录操作成功或失败的日志信息。
"""
try:
# 调用 akshare 库的函数获取 A 股实时行情数据
data = ak.stock_zh_a_spot_em()
# 打印获取到的数据的前几行,用于调试查看数据结构
print(data.head())
# 使用 time.strftime 函数生成当前时间的字符串,格式为年月日时分秒
current_time = time.strftime("%Y%m%d%H%M%S")
# Generate a file name with a timestamp
file_name = f'stock_data_{current_time}.xlsx'
# Create a full file path by combining the directory of the current script and the file name
file_path = os.path.join(os.path.dirname(__file__), file_name)
# Write the data to an Excel file, without including the index
data.to_excel(file_path, index=False)
# Log the successful retrieval and storage of the stock data
logging.info(f"Successfully retrieved stock data and saved to {file_path} at {time.strftime('%Y-%m-%d %H:%M:%S')}")
except Exception as e:
# Log any errors that occur during the retrieval or storage of the stock data
logging.error(f"An error occurred while retrieving or saving stock data: {e}")
# Configure logging to record events at the INFO level
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
# Schedule the function to run every 10 or(0.5) minutes
schedule.every(1).minutes.do(get_and_save_stock_data)
# Start the scheduling loop,Ctrl+C to stop 终止运行
try:
# Continuously check and run scheduled tasks
while True:
# Check if any scheduled tasks are due and run them
schedule.run_pending()
# Pause the loop for 1 second to avoid excessive CPU usage
time.sleep(1)
except KeyboardInterrupt:
logging.info("Program terminated by user.结束")