yfinance: Yfinance stops run to get stocks close

Describe bug

Could you help me, please? i’ve receive the issue below when I run my code

Simple code that reproduces your problem

def get_historical_data(tickers, start_date, end_date, output_filename=None): “”" Função para obter dados históricos de preços de vários ativos a partir do Yahoo Finance.

:param tickers: Lista de tickers dos ativos (exemplo: ['KDIF11.SA', 'JURO11.SA']). 
:param start_date: Data de início (formato 'YYYY-MM-DD'). 
:param end_date: Data de fim (formato 'YYYY-MM-DD'). 
:param output_filename: Nome do arquivo de saída para salvar os dados em Excel (opcional). 
:return: DataFrame contendo os dados históricos de todos os ativos.
"""
all_data = []  # Lista para armazenar os dados de todos os tickers

for ticker in tickers:
    # Baixando os dados históricos do Yahoo Finance
    stock = yf.Ticker(ticker)
    
    # Obtenha os dados históricos de preços
    data = stock.history(start=start_date, end=end_date)
    
    # Verificar se o índice é um DatetimeIndex com fuso horário e removê-lo
    if isinstance(data.index, pd.DatetimeIndex) and data.index.tz is not None:
        data.index = data.index.tz_localize(None)  # Removendo o fuso horário se existir
    
    # Selecionando apenas a coluna "Close"
    data = data[['Close']]  # Seleciona apenas a coluna Close
    
    # Adicionando a coluna "Date" com os índices (datas)
    data['Date'] = data.index
    
    # Adiciona a coluna "Ticker" para identificar os dados
    data['Ticker'] = ticker
    
    # Reorganiza as colunas na ordem desejada: 'Date', 'Ticker', 'Close'
    data = data[['Date', 'Ticker', 'Close']]  # Reorganiza as colunas
    
    # Remove a parte '.SA' dos tickers na coluna 'Ticker'
    data['Ticker'] = data['Ticker'].str.replace('.SA', '', regex=False)
    
    # Renomeia os tickers para 'T 10Y' e 'T 2Y'
    if ticker == '%5ETNX':  # Para o ticker %5ETNX
        data['Ticker'] = 'T 10Y'
        # Calcular a Taxa apenas se Close não for NaN
        data['Taxa'] = data['Close'].apply(lambda x: round(x / 100, 6) if pd.notnull(x) else None)
        data = data.drop(columns=['Close'])  # Remove a coluna 'Close'
    elif ticker == '2YY%3DF':  # Para o ticker 2YY%3DF
        data['Ticker'] = 'T 2Y'
        # Calcular a Taxa apenas se Close não for NaN
        data['Taxa'] = data['Close'].apply(lambda x: round(x / 100, 6) if pd.notnull(x) else None)
        data = data.drop(columns=['Close'])  # Remove a coluna 'Close'
    elif ticker == '%5EGSPC':  # Para o ticker %5EGSPC
        data['Ticker'] = 'SPX'
        # Copiar o Close para PU
        data['PU'] = data['Close'].apply(lambda x: round(x, 2) if pd.notnull(x) else None)
        data = data.drop(columns=['Close'])  # Remove a coluna 'Close'
    elif ticker == '%5EBVSP':  # Para o ticker %5EBVSP
        data['Ticker'] = 'IBOV'
        # Copiar o Close para PU
        data['PU'] = data['Close'].apply(lambda x: round(x, 2) if pd.notnull(x) else None)
        data = data.drop(columns=['Close'])  # Remove a coluna 'Close'
    elif ticker == 'BRL%3DX':  # Para o ticker BRL%3DX
        data['Ticker'] = 'USD'
        # Copiar o Close para PU
        data['PU'] = data['Close'].apply(lambda x: round(x, 4) if pd.notnull(x) else None)
        data = data.drop(columns=['Close'])  # Remove a coluna 'Close'
    else:
        # Para os outros tickers, mantém a coluna 'Close' como está
        data['PU'] = data['Close'].apply(lambda x: round(x, 2) if pd.notnull(x) else None)
        data = data.drop(columns=['Close'])  # Remove a coluna 'Close'
    
    # Adiciona os dados para o ticker na lista all_data
    all_data.append(data)

# Concatenando todos os dados em um único DataFrame
final_df = pd.concat(all_data)

# Se um nome de arquivo for fornecido, exporta os dados para Excel
if output_filename:
    final_df.to_excel(output_filename, index=False)
    print(f"Dados salvos em {output_filename}")

return final_df

Debug log

$KDIF11.SA: possibly delisted; no price data found (1d 2025-02-18 -> 2025-02-19) $JURO11.SA: possibly delisted; no price data found (1d 2025-02-18 -> 2025-02-19) $IFRA11.SA: possibly delisted; no price data found (1d 2025-02-18 -> 2025-02-19) $BDIF11.SA: possibly delisted; no price data found (1d 2025-02-18 -> 2025-02-19)

Bad data proof

No response

yfinance version

0.2.50

Python version

No response

Operating system

No response

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 34 (1 by maintainers)

Most upvoted comments

upgrade to latest version

On Tue, Feb 18, 2025 at 5:05 PM davipachani @.***> wrote:

Please see: #2277 https://github.com/ranaroussi/yfinance/pull/2277

how can i fix, please? i don’t know what and how to do it.

— Reply to this email directly, view it on GitHub https://github.com/ranaroussi/yfinance/issues/2280#issuecomment-2667265226, or unsubscribe https://github.com/notifications/unsubscribe-auth/AEAILKLAAIIQBT3ND7LY4PL2QPKE7AVCNFSM6AAAAABXM2II26VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDMNRXGI3DKMRSGY . You are receiving this because you commented.Message ID: @.***> [image: davipachani]davipachani left a comment (ranaroussi/yfinance#2280) https://github.com/ranaroussi/yfinance/issues/2280#issuecomment-2667265226

Please see: #2277 https://github.com/ranaroussi/yfinance/pull/2277

how can i fix, please? i don’t know what and how to do it.

— Reply to this email directly, view it on GitHub https://github.com/ranaroussi/yfinance/issues/2280#issuecomment-2667265226, or unsubscribe https://github.com/notifications/unsubscribe-auth/AEAILKLAAIIQBT3ND7LY4PL2QPKE7AVCNFSM6AAAAABXM2II26VHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDMNRXGI3DKMRSGY . You are receiving this because you commented.Message ID: @.***>

I had the same problem on version 0.2.37 too. I just updated it to 0.2.54 it working now however the return structure of data frame has been change so you might have to match it to your code my example I change it from

try:
        stock_data = yf.download(stock_name, start=last_trading_day_user_tz.strftime('%Y-%m-%d'),
                                 end=(last_trading_day_user_tz + timedelta(days=1)).strftime('%Y-%m-%d'))
        if not stock_data.empty:
            return round(stock_data['Close'].iloc[-1])
except Exception as e:
        print(f"An error occurred while fetching the stock price: {e}")
        return None

to

try:
        stock_data = yf.download(stock_name, start=last_trading_day_user_tz.strftime('%Y-%m-%d'),
                                 end=(last_trading_day_user_tz + timedelta(days=1)).strftime('%Y-%m-%d'))
        if not stock_data.empty:
            return round(stock_data['Close'][stock_name].iloc[-1])
except Exception as e:
        print(f"An error occurred while fetching the stock price: {e}")
        return None

hope this might help you get and others that have the same problem get some idea to fix it.

@Night-Tales Did you upgrade to version 0.2.54 yet ? if so can I get sniff of your code to help you with that

Ty so much I got it to work, I guess the upgrade didn’t work earlier, i tried now its working fine!

@Night-Tales Did you upgrade to version 0.2.54 yet ? if so can I get sniff of your code to help you with that

Thanks. Updating to the latest (version 0.2.54) worked for me as well.

感谢感谢, 更新到了 0.2.54 版本就可以继续使用了. # Thank you, thank you. After updating to version 0.2.54, it can be used again.

Confirming 0.2.54 fixed the issue, thanks for the crazy fast fix!

Not working for me either. I updated yfinance to latest version 0.2.54, though it started downloading the data again but the returned data is not proper.