感谢您提供furas的剩余部分,下面是解决方案
def get_data():
# Every stock can loop on every periods
stocks = ['A', 'B', 'C', 'D', 'E','F','G','H']
periods = [0,178,356,534,712]
for x in stocks:
for n in periods:
tws.reqHistoricalData(x)
for _ in range(10): # repeat it only 10 times
today = datetime.datetime.today()
delta = datetime.timedelta(days=n)
data = pd.DataFrame(reqHistoricalData(today-delta).strftime("%Y%m%d %H:%M:%S %Z"))
if not data.empty:
data.to_csv("filename{}@{}.csv".format(x, n))
break # exit `for _` loop so it doesn't read again for the same period
print("empty data for", x, str(n), '... reading again')
tws.reqHistoricalData(x) # read again for the same period