使用python的akshare库读取股票实时数据并保存

这段代码的主要功能是定时(1,5,10分钟等)获取 A 股股票数据并保存到 Excel 文件中,同时记录操作日志。具体步骤如下:

  1. 导入必要的库:导入 aksharepandasosscheduletimelogging 库,用于获取股票数据、数据处理、文件路径操作、定时任务、时间处理和日志记录。
  2. 定义获取并保存股票数据的函数get_and_save_stock_data 函数从东方财富获取最新的 A 股股票数据,生成带有时间戳的文件名,将数据保存为 Excel 文件,并记录操作成功或失败的日志。
  3. 配置日志记录:使用 logging.basicConfig 配置日志记录,设置日志级别为 INFO,并指定日志格式。
  4. 设置定时任务:使用 schedule 库设置定时任务,每 10 分钟调用一次 get_and_save_stock_data 函数。
  5. 循环检查并执行定时任务:使用 while True 循环不断检查是否有定时任务到期,并执行到期的任务。每次循环暂停 1 秒,以避免过度占用 CPU 资源。

通过以上步骤,代码实现了定时获取和保存股票数据的功能,并记录了操作日志。

​ 使用 try-except 块包裹了 while 循环,当用户按下 Ctrl+C 时,会触发 KeyboardInterrupt 异常,程序会捕获这个异常并记录一条日志信息,然后正常退出。

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()
            print(data.head())
            # 生成带时间的文件名
            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(0.5).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.结束")

在这里插入图片描述

要实现一个利用Tushare和Akshare接口的Python债券数据爬虫程序,数据进行分析处理,你需要关注以下几个步骤: 参考资源链接:[Python债券数据爬取技巧与Tushare及Akshare接口应用](https://wenku.youkuaiyun.com/doc/857543hrnw) 1. 环境准备:确保Python环境已经安装,以及安装了所需的,如requests、tushare、akshare、pandas等。 2. 注册获取API密钥:前往Tushare官网以及Akshare的GitHub页面注册账户,获取相应的API密钥,以便使用接口服务。 3. 编写爬虫代码:使用Python调用Tushare和Akshare提供的接口来获取债券数据。示例代码如下: ```python import tushare as ts import akshare as ak import pandas as pd # 设置Tushare接口 ts.set_token('你的Tushare Token') ts_pro = ts.pro_api() # 设置Akshare接口 ak债券接口 = ak.bond_zh_a_hist_df # 使用Tushare获取债券数据 df_ts = ts_pro.bond_basic(ts_code='100004.XSHG', list_date='***', end_date='***') # 使用Akshare获取债券数据 df_ak = ak债券接口(symbol='100004', start_date='***', end_date='***', period='daily', adjust='qfq') # 数据处理 df_bond = pd.concat([df_ts, df_ak], axis=1) # 进行数据清洗和保存 df_bond.to_csv('bond_data.csv', index=False) ``` 4. 数据分析:利用pandas对抓取的数据进行分析处理,例如计算平均价格、波动率等。以下是一个简单的数据分析示例: ```python # 读取数据 df = pd.read_csv('bond_data.csv') # 假设数据中有'close'列表示收盘价 df['day_return'] = df['close'].pct_change() df['volatility'] = df['day_return'].rolling(window=5).std() # 输出平均价格和波动率 print(df[['close', 'volatility']].describe()) ``` 以上步骤展示了如何编写债券数据爬虫程序,获取数据进行简单的统计分析。《Python债券数据爬取技巧与Tushare及Akshare接口应用》将会为你提供更多细节和高级技巧,帮助你高效地完成债券数据的自动化爬取和深入分析。 参考资源链接:[Python债券数据爬取技巧与Tushare及Akshare接口应用](https://wenku.youkuaiyun.com/doc/857543hrnw)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值