Search code examples
python-3.xsleep

Adding sleep function in python


Is it possible to add .sleep() to this:

data = web.DataReader(ticker, 'yahoo', start, end)

I would like the sleep function to start every 10 seconds for a duration of 5 seconds. I want to do this because I think there is a problem with yahoo finance connection, which seems cuts out when I download bulk data. It works fine when I query just 1 symbol but gives and error such as

SymbolWarning: Failed to read symbol: 'BRK.B', replacing with NaN.
warnings.warn(msg.format(sym), SymbolWarning)

Full code :

start = datetime.date(2008,11,1)
end = datetime.date.today()
# df = web.get_data_yahoo(tickers, start, end)
df = web.DataReader(tickers, 'yahoo', start, end)

enter image description here


Solution

  • You don't have "tickers" defined. One way to do it is to make a list of stockSymbols you want to loop through:

    tickers= ['AAPL', 'MSFT', 'AABA', 'DB', 'GLD']
    

    Next, you will have to add the loop to implement a sleep timer.

    start = datetime.date(2008,11,1)
    end = datetime.date.today()
    for stockSymbol in tickers:
        time.sleep(5) #Sleep 5 seconds
        webData[stockSymbol] = web.DataReader(stockSymbol, data_source='yahoo',start= start, end= end, retry_count= 10)   
        time.sleep(5) # Sleep for 5 more seconds, total of 10s waited.
        print(webData[stockSymbol])