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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (163)

我目前正在使用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循环'修改为以下内容:

for i in Ticker:
  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
提问于
用户回答回答于
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
用户回答回答于
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))

扫码关注云+社区

领取腾讯云代金券

玩转腾讯云 有奖征文活动