Skip to main content
QUICK REVIEW

[论文解读] Automatic Historical Stock Price Dataset Generation Using Python

Arunima Mandal, Yuanhang Shao|arXiv (Cornell University)|Aug 25, 2023
Stock Market Forecasting MethodsDecision Sciences被引用 3
一句话总结

本文提出了一种基于 Python 的框架,利用 yfinance 库和直接 URL 查询,从 S&P 500 和纳斯达克等主要指数自动生成全面的历史股价数据集。该框架自动化了数据收集过程,通过调整价格处理公司行为,并以公司名称命名的 CSV 格式保存每个公司的独立数据,显著减少了研究人员的重复工作量。

ABSTRACT

With the dynamic political and economic environments, the ever-changing stock markets generate large amounts of data daily. Acquiring up-to-date data is crucial to enhancing predictive precision in stock price behavior studies. However, preparing the dataset manually can be challenging and time-demanding. The stock market analysis usually revolves around specific indices such as S&P500, Nasdaq, Dow Jones, the New York Stock Exchange (NYSE), etc. It is necessary to analyze all the companies of any particular index. While raw data are accessible from diverse financial websites, these resources are tailored for individual company data retrieval and there is a big gap between what is available and what is needed to generate large datasets. Python emerges as a valuable tool for comprehensively collecting all constituent stocks within a given index. While certain online sources offer code snippets for limited dataset generation, a comprehensive and unified script is yet to be developed and publicly available. Therefore, we present a comprehensive and consolidated code resource that facilitates the extraction of updated datasets for any particular time period and for any specific stock market index and closes the gap. The code is available at https://github.com/amp1590/automatic_stock_data_collection.

研究动机与目标

  • 解决手动从金融指数汇编大规模、最新历史股价数据集所耗费的时间和重复性问题。
  • 通过提供统一、可重用的 Python 脚本,消除对零散或不完整代码片段的依赖。
  • 通过支持自动化、可扩展且准确的数据收集,为研究人员在股价预测方面提供帮助,适用于任意所需时间段和指数。
  • 提供两种实现方式——一种使用 yfinance 库,另一种通过直接 URL 查询——确保在不同环境中的灵活性和兼容性。

提出的方法

  • 该方法使用 Python 和 yfinance 库,程序化地下载指定指数(如 S&P 500 或纳斯达克)所有成分股的历史股价数据。
  • 从 Wikipedia 获取 S&P 500 的股票代码列表,其他指数则使用替代数据源,确保公司代码的准确性和实时性。
  • 针对每个股票代码,使用 yfinance 的 download() 函数下载日频、周频或月频数据,并自动调整拆股和股息。
  • 将日期索引转换为列,并添加包含股票代码的 'Name' 列,将每只股票的数据以独立的 CSV 文件形式保存至指定目录。
  • 另一种方法绕过 yfinance,通过直接构造指向 Yahoo Finance API 端点的查询字符串,使用时间戳和 URL 参数,借助 pandas read_csv 获取数据。
  • 系统包含错误处理机制,可跳过在请求时间段内无数据的公司,并记录成功获取的股票数量。

实验结果

研究问题

  • RQ1如何使用 Python 自动且高效地生成主要指数的历史股价数据集?
  • RQ2在数百甚至数千只股票中,收集调整后历史股价的最可靠、最可扩展的方法是什么?
  • RQ3如何将数据集生成过程与手动输入和零散代码片段解耦,以提升可复现性?
  • RQ4在大规模数据收集中,使用 yfinance 库与直接基于 URL 的数据获取在性能和可靠性方面有何差异?

主要发现

  • 所提出的脚本成功为 S&P 500 和纳斯达克指数中的每只股票生成了完整的独立 CSV 文件,包含调整后收盘价在内的所有财务指标。
  • 系统通过 yfinance 库的自动调整功能正确处理了股票拆分和股息等公司行为,确保了数据完整性。
  • 脚本能够识别并排除在请求时间段内不存在的股票,防止错误并提升系统鲁棒性。
  • 替代的直接 URL 方法在无需 yfinance 库的情况下实现了相同结果,为受限环境提供了轻量级替代方案。
  • 该框架显著减少了构建大规模历史数据集所需的时间和精力,使研究人员能将重点放在分析而非数据获取上。
  • 代码已公开发布于 GitHub,支持代码复用、功能扩展,并可集成至研究工作流中。

更好的研究,从现在开始

从阅读论文到最终审阅,大幅缩短您的研究时间。

无需绑定信用卡

本解读由 AI 生成,并经人工编辑审核。