You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过yfinance获取指定格式的股票历史月度收盘价

解决yfinance获取股票历史价格并转换为指定格式的问题

目标格式

[
  {'AMZN': [
    {'Sep 2022': 113},
    {'Oct 2022': 102},
    {'Nov 2022': 92}
  ]},
  {'AAPL': [
    {'Sep 2022': 137},
    {'Oct 2022': 153},
    {'Nov 2022': 147}
  ]},
  {'MSFT': [
    {'Sep 2022': 232},
    {'Oct 2022': 231},
    {'Nov 2022': 241}
  ]}
]

问题说明

yfinance无法直接通过参数配置输出上述格式,需要对下载后的DataFrame做针对性转换。原代码已按股票分组下载月度数据,但dataframe.to_dict("records")无法保留日期信息并生成目标结构。

转换步骤及代码实现

1. 提取收盘价数据

下载的DataFrame包含开盘价、最高价等多类数据,我们只需要收盘价(Close),先筛选出这部分内容:

from datetime import date
import yfinance as yf

tickers = ['AMZN', 'AAPL', 'MSFT']
data = yf.download(
        tickers=tickers,
        start="2019-01-01",
        end=date.today().replace(day=2),
        interval="1mo",
        group_by='ticker'
    )

# 提取各股票的收盘价数据
close_data = {ticker: data[ticker]['Close'] for ticker in tickers}

2. 转换为目标格式

遍历每个股票的收盘价数据,将日期格式转为"Mon YYYY",并构建目标结构:

result = []
for ticker, prices in close_data.items():
    monthly_prices = []
    for date_idx, price in prices.items():
        # 将日期格式化为缩写月份+年份的样式
        formatted_date = date_idx.strftime('%b %Y')
        # 四舍五入为整数价格(按需可调整精度)
        monthly_prices.append({formatted_date: round(price)})
    # 将当前股票的结果加入最终列表
    result.append({ticker: monthly_prices})

# 打印查看结果
import pprint
pprint.pprint(result)

关键细节说明

  • date_idx.strftime('%b %Y'):把datetime格式的日期转换成Sep 2022这类缩写月份+年份的格式。
  • round(price):将收盘价处理为整数,和目标格式匹配;如果需要保留小数,可改为price.round(2)(保留两位小数)。
  • 最终result变量即为符合要求的列表结构。

内容的提问来源于stack exchange,提问作者Sergey Sypalo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 08:10:28