2017-10-20 91 views
0

我創建了一個循環來迭代函數。該功能只是通過一系列代碼從雅虎財經獲取數據。但是,有些代碼在雅虎財務中沒有數據,有時會有錯誤,所以我需要在出現此錯誤時重新運行該函數。跳過錯誤並在循環中獲取3個錯誤後繼續運行 - 從Pandas獲取價格數據

基本上,重新運行可以解決這個錯誤,但是如果數據庫中沒有數據,它也無能爲力。所以,我想使用一個循環定義,如果有錯誤,然後重新運行,但是如果該錯誤出現錯誤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 
+4

你在'if attempts <3'之前設置了'attempts = 0' ...有效地,你只是做了'如果0 <3',那麼粗略的總是爲真。 –

+0

你在所有異常中設置了0 。 –

+0

另外,如果您希望腳本獨立處理每個報價器,則需要分別跟蹤每個報價器的故障。有很多方法可以做到這一點。一種好的方法是使用字典:'{'ticker_a':0,'ticker_b:1,...}' – DaveL17

回答

1

您必須在while循環外定義變量嘗試才能使其工作。

+0

謝謝。我嘗試在While循環外面放置attempts = 0,但它似乎不起作用。我認爲這與通過論證有關。即使我使用下面的代碼,它不起作用。它沒有通過沒有數據的股票。 而真: 嘗試: get_data_from_yahoo() 除外: 通 其他: 休息 – MKYJ

+0

我已經解決了這個問題。該解決方案是類似於[鏈接](https://stackoverflow.com/questions/36249835/python-how-to-avoid-error-exceptions-in-pandas-while-still-getting-data) – MKYJ

+0

真棒,你可以將我的答案標記爲解決方案 – mgracer