在For循环中重试单个迭代(Python)

2024-04-19 04:11:49 发布

您现在位置:Python中文网/ 问答频道 /正文

这里是Python新手(如果这是一个愚蠢的问题,很抱歉)!我目前正在使用for循环来下载和操作数据。不幸的是,我偶尔会遇到一些简单的网络问题,导致部分循环失败。在

最初,我是这样做的:

# Import Modules
import fix_yahoo_finance as yf
import pandas as pd
from stockstats import StockDataFrame as sdf

# Stock Tickers to Gather Data For - in my full code I have thousands of tickers
Ticker = ['MSFT','SPY','GOOG']

# Data Start and End Data
Data_Start_Date = '2017-03-01'
Data_End_Date = '2017-06-01'

# Create Data List to append
DataList = pd.DataFrame([])

# Initialize Loop
for i in Ticker:
    # Download Data
    data = yf.download(i, Data_Start_Date, Data_End_Date)
    # Create StockDataFrame
    stock_df = sdf.retype(data)
    # Calculate RSI
    data['rsi'] = stock_df['rsi_14']
    DataList.append(pd.DataFrame(data))

DataList.to_csv('DataList.csv',header=True,index=True)

在这个基本布局中,每当我遇到网络错误时,它都会导致整个程序停止并发出错误。在

我做了一些研究,并尝试将“for循环”修改为以下内容:

^{pr2}$

这样,代码运行时总是没有问题,但是每当我遇到网络错误时,它会跳过它所在的所有代码(无法下载它们的数据)。在

我希望这个下载每个股票的数据一次。如果失败,我希望它再试一次,直到成功一次,然后继续下一个股票。我尝试使用while True及其变体,但它导致循环多次下载同一个ticker!在

如有任何帮助或建议,我们将不胜感激!谢谢您!在


Tags: to数据import网络truefordatadate
2条回答

如果您在遇到故障后可以继续(有些协议支持),那么最好不要使用这种方法。但是对于一种稍微暴力的方法:

for i in Ticker:
  incomplete = True
  tries = 10
  while incomplete and tries > 0:
    try:
      # Download Data
      data = yf.download(i, Data_Start_Date, Data_End_Date)
      incomplete = False
    except:
      tries -= 1
  # Create StockDataFrame
  if incomplete:
    print("Oops, it is really failing a lot, skipping: %r" % (i,))
    continue # not technically needed, but in case you opt to add
             # anything afterward ...
  else:
    stock_df = sdf.retype(data)
    # Calculate RSI
    data['rsi'] = stock_df['rsi_14']
    DataList.append(pd.DataFrame(data))

这与Prune的稍有不同,它在10次尝试后停止。。。如果它失败了那么多次,这表明您可能需要转移一些精力来解决另一个问题,例如网络连接。在

如果它到了那一步,它将继续出现在Ticker的列表中,所以也许您可以得到您所需要的大部分内容。在

您可以使用包装器循环继续,直到获得良好的结果。在

for i in Ticker:
  fail = True

  while fail:     # Keep trying until it works
    try:
      # Download Data
      data = yf.download(i, Data_Start_Date, Data_End_Date)
      # Create StockDataFrame
      stock_df = sdf.retype(data)
      # Calculate RSI
      data['rsi'] = stock_df['rsi_14']
      DataList.append(pd.DataFrame(data))
    except:
      continue
    else:
      fail = False

相关问题 更多 >