You need to enable JavaScript to run this app. Python循环遍历表格股票代码调用雅虎财经拉取历史数据实现方案
优惠活动
大模型
产品
解决方案
定价
更多

Python循环遍历表格股票代码调用雅虎财经拉取历史数据实现方案

问题根源

你当前的代码每次循环都会重新赋值ticker_data和output变量,前序迭代的结果会被新值覆盖,因此最终只能保留最后一支股票CVS的对应数据。

修改方案

在循环外提前初始化空字典用来承载全量数据,每次循环时将当前股票的代码作为key、拉取到的行情DataFrame作为value存入字典即可,参考代码如下:

import pandas as pd

# 循环外初始化空字典,存储所有ticker对应行情数据
all_stock_data = {}

for ticker in p_ticker:
    # 拼接当前ticker的请求链接
    scrape_string = f"https://query1.finance.yahoo.com/v7/finance/download/{ticker}?period1=1480636740&period2=1606867140&interval=1d&events=history&includeAdjustedClose=true"
    # 拉取数据
    df = pd.read_csv(scrape_string)
    # 存入字典
    all_stock_data[ticker] = df

# 调用示例:查看苹果的历史行情前5行
print(all_stock_data['AAPL'].head())

可选优化(增加异常捕获)

如果遇到部分ticker失效、网络波动等异常情况,可以增加异常捕获逻辑避免程序直接中断:

all_stock_data = {}

for ticker in p_ticker:
    try:
        scrape_string = f"https://query1.finance.yahoo.com/v7/finance/download/{ticker}?period1=1480636740&period2=1606867140&interval=1d&events=history&includeAdjustedClose=true"
        df = pd.read_csv(scrape_string)
        all_stock_data[ticker] = df
        print(f"{ticker} 数据拉取完成")
    except Exception as e:
        print(f"{ticker} 拉取失败,错误原因:{str(e)}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.19 12:54:06