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

Python循环处理股票代码时重复当前项的实现方法

解决yfinance拉取股票数据时重复重试空DataFrame的问题

你可以通过为单个股票代码添加循环重试逻辑实现需求,既可以手动编写重试逻辑(无额外依赖),也可以用第三方库简化代码,以下是两种可行方案:

方案1:手动实现重试逻辑(推荐,无额外依赖)

将每个股票代码的下载与处理逻辑嵌套在while循环中,设置最大重试次数避免死循环,检测到空DataFrame或异常时自动重试当前代码:

import yfinance as yf

wdir = "./your_work_dir/"  # 替换为你的实际工作目录
trade_sym = ["AAPL", "MSFT", "AMZN"]  # 你的股票代码列表
MAX_RETRIES = 5  # 自定义最大重试次数

for sym in trade_sym:
    o_file = wdir + sym + ".csv"
    retries = 0
    download_success = False
    
    while not download_success and retries < MAX_RETRIES:
        try:
            print(f'获取 {sym} 数据(重试次数: {retries})...')
            p_data = yf.download(sym, auto_adjust=True)
            
            # 检测空DataFrame
            if p_data.empty:
                print(f'{sym} 返回空数据,准备重试')
                retries += 1
                continue
            
            # 数据处理逻辑(替换为你的实际代码)
            print(f'处理 {sym} 数据...')
            # processed_df = p_data[["Open", "High", "Low", "Close"]].copy()
            # ... 你的数据操作 ...
            
            # 保存到CSV
            # processed_df.to_csv(o_file)
            print(f'{sym} 数据处理完成并保存\n')
            download_success = True
            
        except Exception as e:
            print(f'{sym} 下载出错: {str(e)},准备重试')
            retries += 1
    
    if not download_success:
        print(f'{sym} 超过最大重试次数 {MAX_RETRIES},放弃处理\n')

方案2:用tenacity库简化重试逻辑

如果需要更灵活的重试规则(比如指定重试间隔、特定异常类型),可以使用tenacity库的装饰器封装重试逻辑:

  1. 先安装依赖:
pip install tenacity
  1. 实现代码:
import yfinance as yf
from tenacity import retry, stop_after_attempt, retry_if_exception_type, retry_if_result

wdir = "./your_work_dir/"
trade_sym = ["AAPL", "MSFT", "AMZN"]
MAX_RETRIES = 5

# 定义重试条件:空DataFrame时触发重试
def is_empty_dataframe(result):
    return result.empty

@retry(
    stop=stop_after_attempt(MAX_RETRIES),  # 最大重试次数
    retry=(retry_if_exception_type(Exception) | retry_if_result(is_empty_dataframe))  # 重试触发条件
)
def fetch_and_process_ticker(sym):
    o_file = wdir + sym + ".csv"
    print(f'获取 {sym} 数据...')
    p_data = yf.download(sym, auto_adjust=True)
    
    # 空DataFrame主动抛出异常触发重试
    if p_data.empty:
        raise ValueError(f"{sym} 返回空数据")
    
    # 数据处理逻辑
    print(f'处理 {sym} 数据...')
    # processed_df = p_data.copy()
    # ... 你的数据操作 ...
    
    # processed_df.to_csv(o_file)
    print(f'{sym} 处理完成\n')
    return p_data

# 遍历股票代码列表
for sym in trade_sym:
    try:
        fetch_and_process_ticker(sym)
    except Exception as e:
        print(f'{sym} 所有重试失败: {str(e)}\n')

两种方案都能实现「失败时重复当前股票代码的下载流程」,手动方案无需额外依赖,适合简单场景;tenacity方案更灵活,适合复杂重试规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 01:18:21