import akshare as ak
import pandas as pd
import os
import schedule
import time
import logging
def get_and_save_stock_data():
"""
Fetches the latest A-share stock data from Eastmoney and saves it to an Excel file.
The file is named with a timestamp and stored in the same directory as the script.
Logs the success or failure of the operation.
"""
try:
# 获取股票数据
# data = ak.stock_zh_a_spot_em()
data = ak.stock_zh_a_spot()
print(data.head(150))
# 打印数据的基本信息
print("数据基本信息:")
data.info()
# 打印数据行数和列数
rows, columns = data.shape
if rows < 3000:
print("数据可能未获取完整,请检查网络连接或稍后重试。")
else:
print("数据获取完整。")
# 打印数据行数
print("数据行数:", rows)
# 生成带时间的文件名
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 1 minute
schedule.every(0.5).minutes.do(get_and_save_stock_data)
# Start the scheduling loop
try:
import msvcrt # Import msvcrt module for Windows key detection
import keyboard # Import the keyboard library
logging.info("Press 'Q' or 'q' to terminate the program.")
while True:
schedule.run_pending()
time.sleep(.5)
# Check if the 'Q' key is pressed
if msvcrt.kbhit() and msvcrt.getch().decode('utf-8').upper() == 'Q':
logging.info("Program terminated by user.")
break
# Check if the 'q' key is pressed
if keyboard.is_pressed('q'):
logging.info("Program terminated by user.")
break
except KeyboardInterrupt:
logging.info("Program terminated by user.结束")