Home > Blockchain >  Expect block not executing
Expect block not executing

Time:04-04

import yfinance as yf
import numpy as np
import pandas as pd
import matplotlib as ptl
import investpy as invpy

stock_data = invpy.stocks.get_stocks("Brazil")
ticker_list = []
for i in range(len(stock_data["symbol"])):
    string_ticker = str(stock_data["symbol"][i])
    ticker = f"{string_ticker}.SA"
    ticker_list.append(ticker)
all_data = pd.DataFrame()

for ticker in ticker_list:
    try:
        data = yf.download(ticker, period = "max")
    except:
        ticker_list.remove(ticker)

I'm capturing all the tickers listed on the Brazilian stock exchange with investpy and because some symbols are delisted or give errors when running the finance.download function, I have to do a try and except block. But, for some reason, when the errors occur it doesn't delete the ticker that gave me the error. What I'm doing wrong and how can i make it work ?

CodePudding user response:

based on this code

download function will not raise an exception, therefore you cannot catch it in except block. although you can check the content in your data variable and if it was not valid, you can remove that ticker from your list.

after I tried to reproduce your problem, found out that you can easily do this by checking len(data) and if it was 0, you can remove the ticker from list.

CodePudding user response:

The source code doesn't appear to raise an Exception of any kind. You can validate that the size of the data is 0 to get around this. However, there is a bug that you will introduce.

You are modifying your list during iteration, which can cause the place you are pointing at in the list to change.

Try one of the following approaches:

  1. Creating a new_ticker_list with only tickers that download:
new_ticker_list = []

for ticker in ticker_list:
    data = yf.download(ticker, period = "max")
    
    if not data:
        continue
    else:
        new_ticker_list.append(ticker)
  1. Iterating indirectly using an index:
idx = 0

while idx < len(ticker_list):
    data = yf.download(ticker, period = "max")
    
    if not data:
        _ = ticker_list.pop(idx)
    else:
        idx  = 1
  • Related