Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

pandas-1.4 yfinance-0.1.69 AttributeError: 'Index' object has no attribute 'tz_localize' #939

Closed
peterxie1 opened this issue Jan 24, 2022 · 34 comments

Comments

@peterxie1
Copy link

peterxie1 commented Jan 24, 2022

Just upgraded to yfinance-0.1.69 and pandas-1.4 you will likely hit this issue. The code is trivial and used to work fine. Any suggestions?

python-3.9.10
windows 10

python
Python 3.9.10 (tags/v3.9.10:f2f3f53, Jan 17 2022, 15:14:21) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

import yfinance as yf
yf.version
'0.1.69'
ticker = "QQQ"
period = "1d"
interval = "5m"
print(ticker, period, interval)
QQQ 1d 5m
yf.download([ticker], period=period, interval=interval)
Exception in thread Thread-3:
Traceback (most recent call last):
File "C:\Users\peter\AppData\Local\Programs\Python\Python39\lib\threading.py", line 973, in _bootstrap_inner
self.run()
File "C:\Users\peter\AppData\Local\Programs\Python\Python39\lib\threading.py", line 910, in run
self._target(*self._args, **self.kwargs)
File "C:\Users\peter\AppData\Local\Programs\Python\Python39\lib\site-packages\multitasking_init
.py", line 104, in _run_via_pool
return callee(*args, **kwargs)
File "C:\Users\peter\AppData\Local\Programs\Python\Python39\lib\site-packages\yfinance\multi.py", line 188, in _download_one_threaded
data = _download_one(ticker, start, end, auto_adjust, back_adjust,
File "C:\Users\peter\AppData\Local\Programs\Python\Python39\lib\site-packages\yfinance\multi.py", line 202, in _download_one
return Ticker(ticker).history(period=period, interval=interval,
File "C:\Users\peter\AppData\Local\Programs\Python\Python39\lib\site-packages\yfinance\base.py", line 295, in history
df.index = df.index.tz_localize("UTC").tz_convert(
AttributeError: 'Index' object has no attribute 'tz_localize'
Traceback (most recent call last):
File "", line 1, in
File "C:\Users\peter\AppData\Local\Programs\Python\Python39\lib\site-packages\yfinance\multi.py", line 112, in download
_time.sleep(0.01)
KeyboardInterrupt

@tsdeng
Copy link

tsdeng commented Jan 24, 2022

lol, just saw the same problem and spent an hour debugging.
It happens with pandas version 1.4 which is just released yesterday.
To workaround it, you can install pip install pandas==1.3.5.
But yeah, it's a problem that needs a fix when using pandas 1.4

@peterxie1
Copy link
Author

Thanks for the note! yes, downgrading pandas from 1.4 to 1.3.5 worked-around this issue.

@peterxie1 peterxie1 changed the title yfinance-0.1.69 AttributeError: 'Index' object has no attribute 'tz_localize' pandas-1.4 yfinance-0.1.69 AttributeError: 'Index' object has no attribute 'tz_localize' Jan 24, 2022
@wonka929
Copy link

yes, same issue here!

@nichmetsa
Copy link

same issue here

@v3natio
Copy link

v3natio commented Jan 24, 2022

same here, had to roll back the pandas version

@ysdede
Copy link

ysdede commented Jan 25, 2022

lol, just saw the same problem and spent an hour debugging. It happens with pandas version 1.4 which is just released yesterday. To workaround it, you can install pip install pandas==1.3.5. But yeah, it's a problem that needs a fix when using pandas 1.4

Thanks!

@Rational-IM
Copy link

I also tried downgrading yfinance to older versions - it didn't work. There were other changes on pandas 1.4 that required some adjustments on other parts of my code - maybe this update is a broader one.

@mundus08
Copy link

I faced the same problem. It might be related to pandas change:
"Ignoring dtypes in concat with empty or all-NA columns"
The problem seams to in
df = _pd.concat([quotes, dividends, splits], axis=1, sort=True)

df.intext.dtype=object in pandas 1.4 because dividends and splits are empty.
With pandas 1.3.5 df.intext.dtype=datetime64[ns]

@Dharmik-19
Copy link

Hi @mundus08 , I am a newbie in the deployment domain. I was curious how you find the exact lines which might be the solution to the problem we are facing. So, did you go through the entire code for pandas to find the prospective lines which can be causing the trouble?

@mundus08
Copy link

Hi @Dharmik-19
the stack trace contained the line number where the problem occured in yfinance. Then I added some print statements to the code and found out that the index dtype has changed. I suspected that it was due to the concat statement (because the dtype of the quotes df was still correct). In the release notes of pandas 1.4 I found a reference to the changes in the concat method.

@ProgrammingDao
Copy link

ProgrammingDao commented Jan 30, 2022

Duplicate of #937 I believe.

@Rational-IM
Copy link

Rational-IM commented Feb 3, 2022

Although #937 was closed, I still get an error message after updating Python/Pandas. I run the file test_yfinance.py and here are the results:

=========================================
ERROR: test_attributes (main.TestTicker)

Traceback (most recent call last):
File "C:\Users\danil\OneDrive\Python_projects\RIM_trading\untitled0.py", line 44, in test_attributes
ticker.dividends
File "C:\Users\danil\anaconda3\envs\spyder-5.2.2\lib\site-packages\yfinance\ticker.py", line 131, in dividends
return self.get_dividends()
File "C:\Users\danil\anaconda3\envs\spyder-5.2.2\lib\site-packages\yfinance\base.py", line 692, in get_dividends
self.history(period="max", proxy=proxy)
File "C:\Users\danil\anaconda3\envs\spyder-5.2.2\lib\site-packages\yfinance\base.py", line 295, in history
df.index = df.index.tz_localize("UTC").tz_convert(
AttributeError: 'Index' object has no attribute 'tz_localize'

=========================================
ERROR: test_info_history (main.TestTicker)

Traceback (most recent call last):
File "C:\Users\danil\OneDrive\Python_projects\RIM_trading\untitled0.py", line 35, in test_info_history
history = ticker.history(period="max")
File "C:\Users\danil\anaconda3\envs\spyder-5.2.2\lib\site-packages\yfinance\base.py", line 295, in history
df.index = df.index.tz_localize("UTC").tz_convert(
AttributeError: 'Index' object has no attribute 'tz_localize'


Ran 3 tests in 20.653s

FAILED (errors=2)

@neilsmurphy
Copy link

Confirm downgrading to pandas 1.3.5 solved the issue.

@grzesir
Copy link

grzesir commented Feb 16, 2022

any updates on a fix?

@hubbubba
Copy link

hubbubba commented Jul 2, 2022

The pandas downgrade worked for me as well. I'm looking forward to a fix for 1.4x.

@ValueRaider
Copy link
Collaborator

Does this still happen in the latest release?

@waqaskhan137
Copy link

waqaskhan137 commented Oct 31, 2022

For me it was still causing the issue even after install panadas 1.3.5
But then I printed the version and came to know it wasnt using pandas 1.3.5 I had to restart the kernal of jupyter notebook in order to get the defined version. Hope this will help someone who is facing the similar issue.

image

!pip install yfinance
!pip install -U pandas==1.3.5

import yfinance as yf
import pandas as pd
import sys
 
 
print("Python Version", sys.version)
print("Yahoo Fianance lib : ", yf.__version__)
print("Panadas : ", pd.__version__)

Python Version 3.10.6 (main, Aug 10 2022, 11:40:04) [GCC 11.3.0]
Yahoo Finance : 0.1.67
Panadas : 1.5.1

@wgong
Copy link

wgong commented Nov 22, 2022

Thank you, pandas==1.3.5 worked

@ValueRaider
Copy link
Collaborator

@wgong Can you provide code that was failing before you downgraded Pandas? We want to fix this problem but we can't reproduce.

@wgong
Copy link

wgong commented Nov 22, 2022

@ValueRaider I just upgraded pandas back to 1.5.1, and cannot reproduced it either.

Here is my function which failed before

def gwg_download_yf(tickers, start_dt, end_dt=""):
    """download quotes of multiple tickers for given start_dt, end_dt (exclusive)
    Args:
        tickers (list)
        start_dt (str) - YYYYMMDD
        end_dt (str) - YYYYMMDD, optional. If end_dt = "", will download one date at start_dt
        
    Returns:
        dataframe or None
    """    
    df_ = None
    if len(tickers) < 1:
        return df_
    
    start_date = datetime.strptime(start_dt, "%Y%m%d")
    if not end_dt:
        end_date = start_date + timedelta(days=1)
    else:
        end_date = datetime.strptime(end_dt, "%Y%m%d")
    data = yf.download(" ".join(tickers), 
                    start=datetime.strftime(start_date, "%Y-%m-%d"), 
                    end=datetime.strftime(end_date, "%Y-%m-%d"))
    return data

@wgong
Copy link

wgong commented Nov 24, 2022

@ValueRaider I tried on a different Ubuntu computer, and cannot reproduce the initial error.

@AminatAzeez
Copy link

I downgraded to 1.3.5 and restarted the kernel but I am still getting the same error

AttributeError Traceback (most recent call last)
Input In [10], in <cell line: 3>()
1 #Question 3 Obtain stock data for AMD using the history function, set the period to max.
2 #Find the Volume traded on the first day (first row).
----> 3 amd_stock_data = amd.history(period="max")

File ~\anaconda3\lib\site-packages\yfinance\base.py:279, in TickerBase.history(self, period, interval, start, end, prepost, actions, auto_adjust, back_adjust, proxy, rounding, tz, timeout, **kwargs)
276 df["Stock Splits"].fillna(0, inplace=True)
278 # index eod/intraday
--> 279 df.index = df.index.tz_localize("UTC").tz_convert(
280 data["chart"]["result"][0]["meta"]["exchangeTimezoneName"])
282 if params["interval"][-1] == "m":
283 df.index.name = "Datetime"

AttributeError: 'Index' object has no attribute 'tz_localize'

please help....

@ValueRaider
Copy link
Collaborator

That looks like old code. Update yfinance to latest version, confirm with import yfinance as yf ; print(yf.__version__)

@AminatAzeez
Copy link

I checked version and it says 0.1.67

@AminatAzeez
Copy link

It works fine now, I just realized the version of the pandas was not changing , I was installing it the wrong way. So, I got the correct installation and it worked

@iamNeverwell
Copy link

Restarted Kernel;

!pip install yfinance
!pip install -U pandas==1.3.5

Confirmed

@ValueRaider
Copy link
Collaborator

Confirmed

Confirmed what?

Also everyone should be able to use any version of Pandas >=1.3.0 without problems.

@Abdul675
Copy link

In my case downgrading the pandas version to 1.3.5 is not working same error how can i resolve this

@waqaskhan137
Copy link

For me it was still causing the issue even after install panadas 1.3.5 But then I printed the version and came to know it wasnt using pandas 1.3.5 I had to restart the kernal of jupyter notebook in order to get the defined version. Hope this will help someone who is facing the similar issue.

image

!pip install yfinance
!pip install -U pandas==1.3.5

import yfinance as yf
import pandas as pd
import sys
 
 
print("Python Version", sys.version)
print("Yahoo Fianance lib : ", yf.__version__)
print("Panadas : ", pd.__version__)

Python Version 3.10.6 (main, Aug 10 2022, 11:40:04) [GCC 11.3.0] Yahoo Finance : 0.1.67 Panadas : 1.5.1

@Abdul675 please refer to this

@ValueRaider
Copy link
Collaborator

ValueRaider commented Mar 30, 2023

@Abdul675 Try branch fix/prices-index-not-datetime (instructions #1080) and give feedback.

@ValueRaider ValueRaider reopened this Mar 30, 2023
@ValueRaider
Copy link
Collaborator

Is this fixed in latest release 0.2.17?

@kaili-yang
Copy link

same issue here

@ValueRaider
Copy link
Collaborator

@kaili-yang Create a new issue following its instructions.

@MrEriikR
Copy link

MrEriikR commented Jan 5, 2024

It worked for me by using the code !pip install pandas==1.3.5 and t hen restarting the kernel.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests