【问题标题】:skip the error and continue to run after getting 3 errors in a loop - Getting Price data from Pandas跳过错误并在循环中出现 3 个错误后继续运行 - 从 Pandas 获取价格数据
【发布时间】:2017-10-21 23:56:29
【问题描述】:

我正在创建一个循环来迭代一个函数。该功能只是通过代码列表从 yahoo Finance 获取数据。但是,有些股票在 yahoo Finance 中没有数据,有时会出现错误,所以每当我遇到此错误时,我都需要重新运行该功能。

基本上re-run可以解决bug,但是如果数据库中没有数据就无济于事了。所以,我想使用一个循环来定义如果有错误,然后重新运行,但如果该代码出现 3 次错误,则跳过该代码。

我认为我在循环中做错了什么,它没有通过该代码,并且它继续重新运行,即使该代码已经出现错误超过 3 次。请问我该如何解决?

谢谢!

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import pickle
import datetime as dt
import os
import pandas as pd
import pandas_datareader.data as web

def save_hsci_tickers():
    driver = webdriver.Chrome(r"C:/Users/kman/Downloads/chromedriver_win32/chromedriver.exe")
    wait = WebDriverWait(driver, 10)
    driver.get("https://www.hsi.com.hk/HSI-Net/HSI-Net?cmd=tab&pageId=en.indexes.hscis.hsci.constituents&expire=false&lang=en&tabs.current=en.indexes.hscis.hsci.overview_des%5Een.indexes.hscis.hsci.constituents&retry=false")
    tickers = []
    for name in wait.until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "table.greygeneraltxt td.greygeneraltxt,td.lightbluebg"))):
        data = str(name.get_attribute('textContent'))
        tickers.append(data)
    edit = [x for x in tickers if x != '']
    final = edit[::2]
    driver.quit()

    def yahoo_ticker(data):
        if len(data) <= 4:
            return data.zfill(4) + '.HK'
        else:
            return data[0:] + '.HK'
    yahoo_tickers = [yahoo_ticker(data) for data in final]
    with open("hscitickers.pickle","wb") as f:
        pickle.dump(yahoo_tickers, f)

    print(yahoo_tickers)
    return yahoo_tickers

save_hsci_tickers()

def get_data_from_yahoo (reload_hscitickers=False):
    if reload_hscitickers:
        tickers = save_hsci_tickers()
    else:
        with open("hscitickers.pickle","rb") as f:
            tickers = pickle.load(f)

    if not os.path.exists('stock_dfs'):
        os.makedirs('stock_dfs')

    start = dt.datetime(2009,6,30)
    end = dt.datetime(2017,6,30)

    for ticker in tickers:
        print(ticker)
        if not os.path.exists('stock_dfs/{}.csv'.format(ticker)):
            df =web.DataReader(ticker,'yahoo',start,end)
            df.to_csv('stock_dfs/{}.csv'.format(ticker))
        else:
            print('Already have {}'.format(ticker))

attempts = 0
while True:
    try:
        get_data_from_yahoo()
    except:
        if attempts < 3:
            attempts += 1
            continue
        if attempts >= 3:
            pass
    else:
        break

【问题讨论】:

  • 你在 if attempts &lt; 3 之前设置了 attempts=0 ... 实际上你刚刚做了 if 0 &lt; 3 粗略总是 True ..
  • 您在每个引发的异常中都将尝试设置为 0。
  • 另外,如果您希望脚本独立处理每个代码,您需要单独跟踪每个代码的故障。有很多方法可以做到这一点。一种好方法是使用字典:{'ticker_a': 0, 'ticker_b: 1, ...}
  • 感谢您的所有帮助。明白了。我尝试将尝试 = 0 放在 While 循环之外,但它似乎也不起作用。
  • 我刚刚更新了脚本。我不确定它是否与前面公式中的其他问题有关,因为 Pass 参数不适用于跳过没有数据的股票代码,即 1551.HK

标签: python pandas while-loop yahoo-finance skip


【解决方案1】:

您必须在 while 循环之外定义变量尝试才能使其工作。

【讨论】:

  • 谢谢。我尝试将尝试 = 0 放在 While 循环之外,但它似乎也不起作用。我认为这与 pass 参数有关。即使我使用下面的代码,它也没有用。它没有通过没有数据的股票代码。 while True: try: get_data_from_yahoo() except: pass else: break
  • 我已经解决了这个问题。解决方法类似于这个link
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多