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

从Yahoo Finance下载DataFrame报错问题求助

解决yahoo_fin下载股票数据导出CSV的两个错误

错误原因分析

第一个错误:AttributeError: 'dict' object has no attribute 'to_csv'

  • historical_datas是Python字典,仅用于存储各股票对应的DataFrame,而to_csv是Pandas DataFrame专属方法,字典没有该属性,直接调用必然报错。

第二个错误:If using all scalar values, you must pass an index

  • pd.DataFrame(historical_datas)默认要求字典的值是标量数据(如单个数值、字符串),但你的字典中每个值都是带日期索引的二维DataFrame,这种场景下无法直接构造DataFrame,必须使用专门的合并方法。

两种正确的解决方案

方案1:合并为多层列结构的DataFrame(适合对比不同股票同期数据)

该方式将每个股票的字段(open、high等)设为列的第二层,日期作为索引:

import yahoo_fin.stock_info as si
import pandas as pd

ticker_list = ["amzn", "aapl", "ba"]
historical_datas = {}

for ticker in ticker_list: 
    historical_datas[ticker] = si.get_data(ticker, start_date="12/04/2009", end_date="12/04/2019", index_as_date=True, interval="1mo")

# 按列合并所有股票的DataFrame,生成多层列结构
combined_df = pd.concat(historical_datas, axis=1)
# 替换为你的实际路径后导出
combined_df.to_csv("C:\\Users\\your_username\\Documents\\stock_data.csv")

方案2:合并为堆叠结构的DataFrame(适合按股票筛选分析)

该方式将所有股票的数据行堆叠,新增ticker列标识所属股票:

import yahoo_fin.stock_info as si
import pandas as pd

ticker_list = ["amzn", "aapl", "ba"]
all_stock_data = []

for ticker in ticker_list: 
    df = si.get_data(ticker, start_date="12/04/2009", end_date="12/04/2019", index_as_date=True, interval="1mo")
    df["ticker"] = ticker  # 添加股票代码标识列
    all_stock_data.append(df)

# 按行合并所有DataFrame
combined_df = pd.concat(all_stock_data, axis=0)
# 替换为你的实际路径后导出
combined_df.to_csv("C:\\Users\\your_username\\Documents\\stock_data_stacked.csv")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 06:45:29