ranaroussi / yfinance

Download market data from Yahoo! Finance's API
https://aroussi.com/post/python-yahoo-finance
Apache License 2.0
13.24k stars 2.34k forks source link

YFinance Returns Incorrect Timeseries Date for `2024-09-03` for Ticker `CADUSD=X` #2046

Open nkhalil98 opened 1 month ago

nkhalil98 commented 1 month ago

Describe bug

yfinance returns incorrect timeseries dates for ticker CADUSD=X when start date is 2024-09-02. Sep 3rd is basically returned as Sep 4th. Additionally, when using start date as 2024-09-03 the program crashes.

Simple code that reproduces your problem

import datetime as dt
import yfinance as yf

ticker = "CADUSD=X"
obj = yf.Ticker(ticker)
start = dt.date(2024, 9, 3)

df = obj.history(start=start)

Debug log

DEBUG    Entering history()
DEBUG     Entering history()
DEBUG      CADUSD=X: Yahoo GET parameters: {'period1': '2024-09-03 00:00:00+01:00', 'period2': '2024-09-04 16:46:15+01:00', 'interval': '1d', 'includePrePost': False, 'events': 'div,splits,capitalGains'}
DEBUG      Entering get()
DEBUG       url=https://query2.finance.yahoo.com/v8/finance/chart/CADUSD=X
DEBUG       params={'period1': 1725318000, 'period2': 1725464775, 'interval': '1d', 'includePrePost': False, 'events': 'div,splits,capitalGains'}
DEBUG       Entering _get_cookie_and_crumb()
DEBUG        cookie_mode = 'basic'
DEBUG        Entering _get_cookie_and_crumb_basic()
DEBUG         reusing cookie
DEBUG         reusing crumb
DEBUG        Exiting _get_cookie_and_crumb_basic()
DEBUG       Exiting _get_cookie_and_crumb()
DEBUG       response code=200
DEBUG      Exiting get()
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
Cell In[9], line 1
----> 1 df = obj.history(start=start)

File ~/Library/Caches/pypoetry/virtualenvs/x-VvSLft---py3.12/lib/python3.12/site-packages/yfinance/utils.py:104, in log_indent_decorator.<locals>.wrapper(*args, **kwargs)
    101 logger.debug(f'Entering {func.__name__}()')
    103 with IndentationContext():
--> 104     result = func(*args, **kwargs)
    106 logger.debug(f'Exiting {func.__name__}()')
    107 return result

File ~/Library/Caches/pypoetry/virtualenvs/x-VvSLft---py3.12/lib/python3.12/site-packages/yfinance/base.py:78, in TickerBase.history(self, *args, **kwargs)
     76 @utils.log_indent_decorator
     77 def history(self, *args, **kwargs) -> pd.DataFrame:
---> 78     return self._lazy_load_price_history().history(*args, **kwargs)

File ~/Library/Caches/pypoetry/virtualenvs/x-VvSLft---py3.12/lib/python3.12/site-packages/yfinance/utils.py:104, in log_indent_decorator.<locals>.wrapper(*args, **kwargs)
    101 logger.debug(f'Entering {func.__name__}()')
    103 with IndentationContext():
--> 104     result = func(*args, **kwargs)
    106 logger.debug(f'Exiting {func.__name__}()')
    107 return result

File ~/Library/Caches/pypoetry/virtualenvs/x-VvSLft---py3.12/lib/python3.12/site-packages/yfinance/scrapers/history.py:256, in PriceHistory.history(self, period, interval, start, end, prepost, actions, auto_adjust, back_adjust, repair, keepna, proxy, rounding, timeout, raise_errors)
    254     if quotes.index[quotes.shape[0] - 1] >= endDt:
    255         quotes = quotes.iloc[0:quotes.shape[0] - 1]
--> 256 logger.debug(f'{self.ticker}: yfinance received OHLC data: {quotes.index[0]} -> {quotes.index[-1]}')
    258 # 2) fix weired bug with Yahoo! - returning 60m for 30m bars
    259 if interval.lower() == "30m":

File ~/Library/Caches/pypoetry/virtualenvs/x-VvSLft---py3.12/lib/python3.12/site-packages/pandas/core/indexes/base.py:5389, in Index.__getitem__(self, key)
   5386 if is_integer(key) or is_float(key):
   5387     # GH#44051 exclude bool, which would return a 2d ndarray
   5388     key = com.cast_scalar_indexer(key)
-> 5389     return getitem(key)
   5391 if isinstance(key, slice):
   5392     # This case is separated from the conditional above to avoid
   5393     # pessimization com.is_bool_indexer and ndim checks.
   5394     return self._getitem_slice(key)

File ~/Library/Caches/pypoetry/virtualenvs/x-VvSLft---py3.12/lib/python3.12/site-packages/pandas/core/arrays/datetimelike.py:381, in DatetimeLikeArrayMixin.__getitem__(self, key)
    374 """
    375 This getitem defers to the underlying array, which by-definition can
    376 only handle list-likes, slices, and integer scalars
    377 """
    378 # Use cast as we know we will get back a DatetimeLikeArray or DTScalar,
    379 # but skip evaluating the Union at runtime for performance
    380 # (see https://github.com/pandas-dev/pandas/pull/44624)
--> 381 result = cast("Union[Self, DTScalarOrNaT]", super().__getitem__(key))
    382 if lib.is_scalar(result):
    383     return result

File ~/Library/Caches/pypoetry/virtualenvs/x-VvSLft---py3.12/lib/python3.12/site-packages/pandas/core/arrays/_mixins.py:284, in NDArrayBackedExtensionArray.__getitem__(self, key)
    278 def __getitem__(
    279     self,
    280     key: PositionalIndexer2D,
    281 ) -> Self | Any:
    282     if lib.is_integer(key):
    283         # fast-path
--> 284         result = self._ndarray[key]
    285         if self.ndim == 1:
    286             return self._box_func(result)

IndexError: index 0 is out of bounds for axis 0 with size 0

Bad data proof

Screenshot 2024-09-04 at 11 48 19 AM

yfinance version

0.2.43

Python version

3.12.5

Operating system

macOS Sonoma 14.5

ValueRaider commented 2 days ago

Fixed in branch fix/debug-msg, can you try? #1080