.info returns 404 on all tickers

@ValueRaider hijacking top post

please only reply with new information, otherwise just react. I will delete useless comments.
don't know why Yahoo done this. Doesn't affect USA
Ticker.fast_info has subset of Ticker.info
USA VPN is a workaround https://github.com/ranaroussi/yfinance/issues/1729#issuecomment-1773032475
31-Oct update: now affects USA https://github.com/ranaroussi/yfinance/issues/1729#issuecomment-1787687528
changing endpoint might help https://github.com/ranaroussi/yfinance/issues/1729#issuecomment-1776096509
31-Oct update: stopped helping https://github.com/ranaroussi/yfinance/issues/1729#issuecomment-1787886335
cookie & crumb might help https://github.com/ranaroussi/yfinance/pull/1657

Describe bug
Call to .info returns 404 error on all tickers.
Example url: https://query2.finance.yahoo.com/v6/finance/quoteSummary/SPY?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true
Using browsers on multiple connections/devices, yahoo output "Will be right back... Our engineers are working quickly to resolve the issue."
Data could have moved to new link
Simple code that reproduces your problem
import yfinance as yf
yf_ticker=yf.Ticker("SPY")
yf_ticker.info
Debug log
HTTPError: 404 Client Error: Not Found for url: https://query2.finance.yahoo.com/v6/finance/quoteSummary/SPY?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true
Bad data proof
No response
yfinance version
0.2.31
Python version
No response
Operating system
No response

The yahoo finance API looks down.

For reference some of the methods still working:
.history
.fast_info
.news
.earnings_dates
.history_metadata
.option_chain

Same issue in UK

Same issue

Try running on Google colab it works for me but still it is not working on local environment.
Bit weird 🤔

same issue

same issue
but when i open vpn it works

same issue but when i open vpn it works

to which country

same issue

Try running on Google colab it works for me but still it is not working on local environment. Bit weird 🤔

i cant use my code on colab, i hope in resolution. I have error also in pyfinvis, its a strange period:)

May be it will help to switch to v7 or v10 api: https://query2.finance.yahoo.com/v1/test/getcrumb

@bot-unit That reminds me, does #1637 help anyone?

yahooquery has the same problems

same issue but when i open USA vpn it works

You save my life.
USA VPN does work!

I can confirm using USA VPN fixes the issue. Thanks for sharing @MrH32 !

I confirm, I set up a US proxy for my app and it works.

Please only reply if you have new information, otherwise just react.

In my case using threads=False partially solves it

In my case using threads=False partially solves it

can you explain more

In my case using threads=False partially solves it

can you explain more
It is a yfinace option(yd.download(share, threads=False))

for me it is unrelated to threads, download seems to work always, others not:
#!/bin/python3

import yfinance as yf

print('Quotes:\n')
quotes = yf.download('ORCL', period = '1d')
print(quotes)

print('\n\nQuote:\n')
quote = yf.Ticker('ORCL')
print(quote.info['currentPrice'])

Quotes:

[*********************100%%**********************]  1 of 1 completed
                  Open        High         Low       Close   Adj Close    Volume
Date
2023-10-20  106.989998  107.035004  100.660004  101.849998  101.849998  21718467

Quote:

Traceback (most recent call last):
  File "/opt/svn/DynatraceFinance/./test.py", line 11, in <module>
    print(quote.info['currentPrice'])
  File "/home/dstadler/.local/lib/python3.10/site-packages/yfinance/ticker.py", line 142, in info
    return self.get_info()
  File "/home/dstadler/.local/lib/python3.10/site-packages/yfinance/base.py", line 1736, in get_info
    data = self._quote.info
  File "/home/dstadler/.local/lib/python3.10/site-packages/yfinance/scrapers/quote.py", line 571, in info
    self._fetch(self.proxy)
  File "/home/dstadler/.local/lib/python3.10/site-packages/yfinance/scrapers/quote.py", line 600, in _fetch
    result = self._data.get_raw_json(
  File "/home/dstadler/.local/lib/python3.10/site-packages/yfinance/data.py", line 75, in get_raw_json
    response.raise_for_status()
  File "/home/dstadler/.local/lib/python3.10/site-packages/requests/models.py", line 1021, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://query2.finance.yahoo.com/v6/finance/quoteSummary/ORCL?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true

'yf.download' gets the data from the chart json (which works):
https://query2.finance.yahoo.com/v8/finance/chart/ORCL
whereas 'yf.Ticker' gets the data from the quotesummary (which doesn't work)
https://query2.finance.yahoo.com/v6/finance/quoteSummary/ORCL

@bot-unit That reminds me, does #1657 help anyone?

I don't known. Just make wrapper like:
        self.session = requests.Session()         response = self.session.get('https://guce.yahoo.com/consent', headers=self.user_agent_headers)         soup = BeautifulSoup(response.content, 'html.parser')         csrfTokenInput = soup.find('input', attrs={'name': 'csrfToken'})         csrfToken = csrfTokenInput['value']         sessionIdInput = soup.find('input', attrs={'name': 'sessionId'})         sessionId = sessionIdInput['value']         originalDoneUrl = 'https://finance.yahoo.com/'         namespace = 'yahoo'         data = {             'agree': ['agree', 'agree'],             'consentUUID': 'default',             'sessionId': sessionId,             'csrfToken': csrfToken,             'originalDoneUrl': originalDoneUrl,             'namespace': namespace,         }         self.session.post(f'https://consent.yahoo.com/v2/collectConsent?sessionId={sessionId}', data=data, headers=self.user_agent_headers)         self.session.get(f'https://guce.yahoo.com/copyConsent?sessionId={sessionId}', headers=self.user_agent_headers)         self.crumb = self.session.get('https://query2.finance.yahoo.com/v1/test/getcrumb', headers=self.user_agent_headers).text

@bot-unit That reminds me, does #1657 help anyone?

I don't known. We just need to fix url to use api v7,v8 and v10 and include crumb= in requests.
Crumb we can take something like this:
self.session = requests.Session()
response = self.session.get('https://guce.yahoo.com/consent', headers=self.user_agent_headers)
soup = BeautifulSoup(response.content, 'html.parser')
csrfTokenInput = soup.find('input', attrs={'name': 'csrfToken'})
csrfToken = csrfTokenInput['value']
sessionIdInput = soup.find('input', attrs={'name': 'sessionId'})
sessionId = sessionIdInput['value']
originalDoneUrl = 'https://finance.yahoo.com/'
namespace = 'yahoo'
data = {
'agree': ['agree', 'agree'],
'consentUUID': 'default',
'sessionId': sessionId,
'csrfToken': csrfToken,
'originalDoneUrl': originalDoneUrl,
'namespace': namespace,
}
self.session.post(f'https://consent.yahoo.com/v2/collectConsent?sessionId={sessionId}', data=data, headers=self.user_agent_headers)
self.session.get(f'https://guce.yahoo.com/copyConsent?sessionId={sessionId}', headers=self.user_agent_headers)
self.crumb = self.session.get('https://query2.finance.yahoo.com/v1/test/getcrumb', headers=self.user_agent_headers).text

I am not really into programming at this level but i think the answers is understanding why it works with an american IP...

I am not really into programming at this level but i think the answers is understanding why it works with an american IP...

Because Yahoo is banning not-American IP ˆ)

I am not really into programming at this level but i think the answers is understanding why it works with an american IP...

Because Yahoo is banning not-American IP ˆ)

Right now I am trying with this american VPN ip <IP_ADDRESS> and I am getting 404. =)

I've observed different IP addresses for query2.finance.yahoo.com when running nslookup on AWS EC2 instances in the US and EU.
Using the following curl command works in the US but not in the EU:
curl -v 'https://query2.finance.yahoo.com/v6/finance/quoteSummary/SPY?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true'
However, when I hardcode the IP address returned by the DNS lookup from the US instance, the request works outside of the US:
curl -v -k -H "Host: query2.finance.yahoo.com" 'https://<IP_ADDRESS>/v6/finance/quoteSummary/SPY?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true'
Please note that this is not a long-term solution, as the IP address might change dynamically. It's just an observation that might help diagnose the issue.

hmm, interesting. What about this?
curl -v -k -H "Host: query2.finance.yahoo.com" 'https://e1.ycpi.vip.dca.yahoo.com/v6/finance/quoteSummary/SPY?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true'

I use yahooquery and for me hardcoding the IP for "query2.finance.yahoo.com" in /etc/hosts works as a temporary solution for my script.
@lucas03 using the subdomain is probably better but is there a quick way to fix existing scripts with subdomain as for IP adresses?

I've observed different IP addresses for query2.finance.yahoo.com when running nslookup on AWS EC2 instances in the US and EU.
Using the following curl command works in the US but not in the EU: curl -v 'https://query2.finance.yahoo.com/v6/finance/quoteSummary/SPY?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true' However, when I hardcode the IP address returned by the DNS lookup from the US instance, the request works outside of the US: curl -v -k -H "Host: query2.finance.yahoo.com" 'https://<IP_ADDRESS>/v6/finance/quoteSummary/SPY?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true' Please note that this is not a long-term solution, as the IP address might change dynamically. It's just an observation that might help diagnose the issue.

 Maybe the location block is attached to the load-balancer somehow.

I am not really into programming at this level but i think the answers is understanding why it works with an american IP...

Because Yahoo is banning not-American IP ˆ)

Right now I am trying with this american VPN ip <IP_ADDRESS> and I am getting 404. =)

I'm using Browsec VPN.
Using my Australian IP: 404
Using Browsec German VPN: 404
Using Browsec US VPN: I get results.
Using Browsec US (west) VPN: 404.

I am not really into programming at this level but i think the answers is understanding why it works with an american IP...

Because Yahoo is banning not-American IP ˆ)

Right now I am trying with this american VPN ip <IP_ADDRESS> and I am getting 404. =)

I'm using Browsec VPN. Using my Australian IP: 404 Using Browsec German VPN: 404 Using Browsec US VPN: I get results. Using Browsec US (west) VPN: 404.

Yes, from a Western US VPN I got 404, but switching to a Californian IP, as far as i am concerned, I got results yesterday.

I am having the same problem, yahoo wants to deny for not US ip address?

hmm, interesting. What about this?
curl -v -k -H "Host: query2.finance.yahoo.com" 'https://e1.ycpi.vip.dca.yahoo.com/v6/finance/quoteSummary/SPY?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true'

both this curl & the one with the IP work for me from the UK

Seems the problem still persists, for example, I am trying to access info regarding the company's data using the yf.Ticker method and no success so far. For example if I run:
import yfinance as yf
ts = yf.download('KRI.AT', period = 'max')
print(ts) # this works, I can download historical price data
info = yf.Ticker('KRI.AT')
print(info.info) # this still doesn't not work, I get 404 client error.

I'm using PIA VPN and the only one that works for me is US Houston (<IP_ADDRESS>).
That works on my desktop, but my code is running on a server in the DMZ, so can't fix it with VPN.

I live in the united states and even trying to use my local ip dosent work for me.

I might (unfortunately) be able to add some extra complexity to this issue. I'm running automated tests in my github workflows using yfinance, one test which tries and fetch information using the get_info() method on the yf.Ticker object.
This workflow is run on [ubuntu-latest, macos-latest, windows-latest] for Python3.10.x. Interestingly, the tests pass when running on ubuntu and macos, but failing when running on windows.
The request to the following url is getting a 404: https://query2.finance.yahoo.com/v6/finance/quoteSummary/ABB.ST?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true
The runner version are the following:

os
version
image provisioner
fails due to 404

Ubuntu 22.04.3 LTS
20231016.1.0
2.0.312.1
No

macOS 12.6.9 21G726
20230921.1
2.0.312.1
No

Microsoft Windows Server 2022 10.0.20348 Datacenter
20231023.1.0
2.0.312.1
Yes

Link to the entire failing test output due to 404.
Could it be that GitHub's ubuntu and macOS workers are hosted in the US, whereas the windows worker is hosted in the EU?
Looking forward to follow this issue and hopefully help narrow the problem down :)
//w

I tried to apply curl changes to yfinance, as a temporary hotfix for testing
https://github.com/ranaroussi/yfinance/compare/main...lucas03:yfinance:lukas/yahoo_domain

How can I solve the problem if I'm working from Spain?
Is there any free solution?

sed -i '0 i <IP_ADDRESS> query2.finance.yahoo.com' /etc/hosts

@lukas How did you find the e1.ycpi.vip.dca.yahoo.com subdomain?

"Reverse IP Lookup"

> @bot-unit That reminds me, does #1657 help anyone?
I don't known. We just need to fix url to use api v7,v8 and v10 and include crumb= in requests.
Crumb we can take something like this:
        self.session = requests.Session()
        response = self.session.get('https://guce.yahoo.com/consent', headers=self.user_agent_headers)
        soup = BeautifulSoup(response.content, 'html.parser')
        csrfTokenInput = soup.find('input', attrs={'name': 'csrfToken'})
        csrfToken = csrfTokenInput['value']
        sessionIdInput = soup.find('input', attrs={'name': 'sessionId'})
        sessionId = sessionIdInput['value']
        originalDoneUrl = 'https://finance.yahoo.com/'
        namespace = 'yahoo'
        data = {
            'agree': ['agree', 'agree'],
            'consentUUID': 'default',
            'sessionId': sessionId,
            'csrfToken': csrfToken,
            'originalDoneUrl': originalDoneUrl,
            'namespace': namespace,
        }
        self.session.post(f'https://consent.yahoo.com/v2/collectConsent?sessionId={sessionId}', data=data, headers=self.user_agent_headers)
        self.session.get(f'https://guce.yahoo.com/copyConsent?sessionId={sessionId}', headers=self.user_agent_headers)
        self.crumb = self.session.get('https://query2.finance.yahoo.com/v1/test/getcrumb', headers=self.user_agent_headers).text

I am not a web developer (so forgive the naivety), but can anyone share further insight on this approach of changing the URL and supplying a crumb.
My understanding is the following URL is causing the issue (for maybe just non-us users):

https://query2.finance.yahoo.com/v6/finance/quoteSummary/ORCL

When I change the 'v6' in the URL (to any of the following: 'V7', 'v8', 'v9'), I get a "Error 404" response.
However, for 'v10' I get a different response depending on the browser, which says "invalid crumb" or "invalid cookie"
New URL: https://query2.finance.yahoo.com/v10/finance/quoteSummary/ORCL
Response: {"finance":{"result":null,"error":{"code":"Unauthorized","description":"Invalid Crumb"}}}
If I get the crumb (from: https://query2.finance.yahoo.com/v1/test/getcrumb) and add it to the URL via (appending "?crumb=[crumb value]). I get a bad request message stating missing modules. But what modules need to be added?
Or is this entire approach not correct/has been ruled out by everybody commenting since?

I think @zq99 is on to something. His approach works for me. After appending the crumb from a request to:
https://query2.finance.yahoo.com/v1/test/getcrumb
to this URL:
https://query2.finance.yahoo.com/v10/finance/quoteSummary/AAPL?module=summaryDetail&ssl=true&crumb=<crumbfrompreviouscall>
I get a valid result. Without having any modifications in /etc/hosts. I should say that I am in the US, but if I use the v6 API and an unmodified hosts file I still get 404 errors.

My 2 cents: why we have this problem? Is Yahoo saying something? Is it a bug or they are blocking definitely the API access?

This link, which appears in the library's error, doesn't work
https://query2.finance.yahoo.com/v6/finance/quoteSummary/MSFT?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true
But it only works when query1,v8 and chart changes
https://query1.finance.yahoo.com/v8/finance/chart/MSFT?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true

Not an immediate solution to the problem, but roic.ai has API access for only $67 per month.
https://roic.ai/pricing

Not an immediate solution to the problem, but roic.ai has API access for only $67 per month. https://roic.ai/pricing

This thread may not be the ideal place to discuss this, but I, for one, would like to have a contingency plan in place for when Yahoo decides to close their API, as I believe some of Yahoo's APIs have been deprecated for years. I’m okay with paying a reasonable amount for a robust data source. There are a variety of API providers available, and I imagine there are many potential pitfalls.
What’s your stance on this, @ranaroussi and @ValueRaider? Would it be okay to start a discussion on backup alternatives?

same issue
but when i open USA vpn it works

I can confirm it doesn't work outside US. Using a VPN or proxy works though.

@jirisarri10 read the top post

I think @zq99 is on to something. His approach works for me. After appending the crumb from a request to: https://query2.finance.yahoo.com/v1/test/getcrumb to this URL: https://query2.finance.yahoo.com/v10/finance/quoteSummary/AAPL?module=summaryDetail&ssl=true&crumb=<crumbfrompreviouscall> I get a valid result. Without having any modifications in /etc/hosts. I should say that I am in the US, but if I use the v6 API and an unmodified hosts file I still get 404 errors.

I have been having a brief look at the code. The 'quoteSummary' v6 URL is declared in the module quote.py.
However, when I was looking at the version history of this module, it seems that the original URL was actually pointing
to v10 rather than v6.
A change from v10 to v6 was made on Jul 13th with commit https://github.com/ranaroussi/yfinance/commit/509a109f29a657190e7af86a160db340d1dff71d
So maybe there was some kind of issue with it.

@jirisarri10 most questions answered by reading top post then #1084

@bot-unit What symbol did you test crumbs on, and where are you? https://github.com/ranaroussi/yfinance/issues/1729#issuecomment-1775575210 I get more fails than successes, either with your crumb fetch or mine #1657.

Symbol
#1657 crumb
bot-unit crumb

MSFT
works
Unauthorized for url

AMZN
Unauthorized for url
works

AZN.L
Unauthorized for url
Unauthorized for url

DBK.DE
Unauthorized for url
Unauthorized for url

@ValueRaider Due to my experience with yahooquery you can try a different capitalization instead in case of failure amzn instead of AMZN. It seems Yahoo is changing the capitalization rules.

@bot-unit What symbol did you test crumbs on, and where are you? I am in Europe. #1729 (comment) I get more fails than successes, either with your crumb fetch or mine #1657.
Symbol 	#1657 crumb 	bot-unit crumb
MSFT 	works 	401 Client Error: Unauthorized for url
AMZN 	401 Client Error: Unauthorized for url 	works
AZN.L 	401 Client Error: Unauthorized for url 	401 Client Error: Unauthorized for url
DBK.DE 	401 Client Error: Unauthorized for url 	401 Client Error: Unauthorized for url
I am in Europe and my fix is working for ALL symbols. With dot notated symbols, just do simple replace dor to '-': symbol_name = symbol_name.replace('.', '-')

Try running on Google colab it works for me but still it is not working on local environment. Bit weird 🤔

In my case, it's the exact opposite. It works locally but doesn't work on Colab

@bot-unit I'm having more success now. I think my caching was problem, which raises question - how long can crumb be cached for? Takes 4 requests to get crumb, need to maximise crumb reuse.

I've same issue in colab. When I try delete runtime and reconnect multiple times, it works. Its very random, should be based on IP I guess.

yesterday it was working fine with a US VPN, today is not. Locally it is not working either and am based in the US/EAST

yesterday it was working fine with a US VPN, today is not. Locally it is not working either and am based in the US/EAST

The page is genuinely under maintenance I guess
https://query2.finance.yahoo.com/v6/finance/quoteSummary/AAPL?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true

In case its helpful I just tried the feature/cookie-and-crumb branch and get error:
(Pdb) yf.Ticker("SPY")
yfinance.Ticker object <SPY>
(Pdb) yf.Ticker("SPY").info
*** TypeError: 'NoneType' object is not subscriptable

All was fine with main branch until this stopped working today.

I am in the US, and I had exactly the same experience as @gene-git .  The TypeError shows up at line 109 of data.pyin the _get_crumb_botnunit method.

@gene-git @ms82494 post pull request feedback in the pull request.

Hi, how about this issue? I am from Argentina and I can not get the info from Yahoo API.
stock = yf.Ticker(ticker)
info = stock.info  <-- error message
/usr/local/lib/python3.10/dist-packages/requests/models.py in raise_for_status(self)
1019
1020         if http_error_msg:
-> 1021             raise HTTPError(http_error_msg, response=self)
1022
1023     def close(self):
HTTPError: 404 Client Error: Not Found for url: https://query2.finance.yahoo.com/v6/finance/quoteSummary/NFLX?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true

yesterday it was working fine with a US VPN, today is not. Locally it is not working either and am based in the US/EAST

The page is genuinely under maintenance I guess https://query2.finance.yahoo.com/v6/finance/quoteSummary/AAPL?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true

That message is the same as 10 days ago.

https://imgur.com/a/YVJNyGQ
For a while VPNing outside the US worked.  No longer.  I'd guess that they're not going to be right back.
https://www.google.com/search?hl=en&q=alternative to python yfinance
Think I'll try out these other two.

Alpha_vantage seems to work for the following simple test.  Pip install, get free API key from here:  https://www.alphavantage.co/
This
from alpha_vantage.timeseries import TimeSeries
import pdb

pdb.set_trace()
ts = TimeSeries(key='MyAPIKey')
# Get json object with the intraday data and another with  the call's metadata
data, meta_data = ts.get_intraday('GOOGL')

gets prev two days prices every 15 minutes.

(Pdb) data['2023-10-30 19:45:00']
{'1. open': '124.5900', '2. high': '124.5900', '3. low': '124.3100', '4. close': '124.3100', '5. volume': '4195'}
(Pdb) data['2023-10-30 19:30:00']
{'1. open': '124.5000', '2. high': '124.6200', '3. low': '124.4500', '4. close': '124.5900', '5. volume': '808'}
(Pdb) data['2023-10-30 19:15:00']
{'1. open': '124.4800', '2. high': '124.6100', '3. low': '124.4700', '4. close': '124.5000', '5. volume': '3682'}
(Pdb) for i in dir(ts): print(i)

@patfla Read https://github.com/ranaroussi/yfinance/issues/1729#issuecomment-1782840961

@ValueRaider You write that there's information about changes to yahoo finance's API out in blogs.  I've googled and find little that's useful.

@patfla I also say discuss anywhere but this issue thread.

changing endpoint might help .info returns 404 on all tickers #1729 (comment)

Seems like the endpoint fix was also broken as of today. Trying to use the https://e1.ycpi.vip.dca.yahoo.com/ endpoint from Lucas' fix returns a 404 now.
HTTPError: 404 Client Error: Not Found for url: https://e1.ycpi.vip.dca.yahoo.com/v6/finance/quoteSummary/AAPL?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true

@silentsight I'm afraid it won't help with ticker.info issue

One solution which works for me is to use ticker.fast_info. It doesn't fail, has way less data points and some of the names differ from the original info response:
stock_data['current_price'] = info.last_price
stock_data['volume'] = info.last_volume
stock_data['fifty_two_week_low'] = info.year_low
stock_data['fifty_two_week_high'] = info.year_high

@wowo  - trying same Using the feature/cookie-and-crum branch i get something odd:
    ticker = 'JPM'
    key = 'lastPrice'
    fast_info = yf.Ticker(ticker).fast_info
    fast_info[key]

KeyError: 'currentTradingPeriod'

@wowo - trying same Using the feature/cookie-and-crumb branch i get something odd:
    ticker = 'JPM'
    key = 'lastPrice'
    fast_info = yf.Ticker(ticker).fast_info
    fast_info[key]

KeyError: 'currentTradingPeriod'

same code, it worked on colab :/

One solution which works for me is to use ticker.fast_info. It doesn't fail, has way less data points and some of the names differ from the original info response:
stock_data['current_price'] = info.last_price
stock_data['volume'] = info.last_volume
stock_data['fifty_two_week_low'] = info.year_low
stock_data['fifty_two_week_high'] = info.year_high

I can confirm that using fast_info instead of info worked just fine for my particular use-case:
import yfinance as yf
import os
import pprint

stock = yf.Ticker("AAPL")

price = round(stock.fast_info['lastPrice'], 2)
previous_close = stock.fast_info['previousClose']

Question - for those with fast_info working:

which git branch are you using - "main", "feature/cookie-and-crumb" or something else?

I can confirm that using fast_info instead of info worked just fine for my particular use-case:

I am not sure this is a solution, unless I am mistaken, but I don't think 'fast_info' really is a subset of 'info'.
Both methods come from the Ticker object. However, 'fast_info' represents price and calculated data, whereas 'info' seems to represent static/fundamental data (e.g sector, industry etc..).:
It seems that all price data in the library is coming from the chart json (either directly or indirectly)
e.g. https://query2.finance.yahoo.com/v8/finance/chart/ORCL).
So this includes the methods ('download', 'fast_info', Ticker.History).
'fast_info' actually queries Ticker.History for the data, then does some calculations/aggregations.
However, the issue with the library is that 'info' which is pulling from a completely different url which no longer works:
https://query2.finance.yahoo.com/v6/finance/quoteSummary/ORCL

I can confirm that using fast_info instead of info worked just fine for my particular use-case:

I am not sure this is a solution, unless I am mistaken, but I don't think 'fast_info' really is a subset of 'info'.
Both methods come from the Ticker object. However, 'fast_info' represents price and calculated data, whereas 'info' seems to represent static/fundamental data (e.g sector, industry etc..).:
It seems that all price data in the library is coming from the chart json (either directly or indirectly) e.g. https://query2.finance.yahoo.com/v8/finance/chart/ORCL).
So this includes the methods ('download', 'fast_info', Ticker.History).
'fast_info' actually queries Ticker.History for the data, then does some calculations/aggregations.
However, the issue with the library is that 'info' which is pulling from a completely different url which no longer works: https://query2.finance.yahoo.com/v6/finance/quoteSummary/ORCL

I confirm that. On my script, I just added fast_ to .info and I got "none" response for all fields but: marketCap, regularMarketPreviousClose, fiftyDayAverage, twoHunderdDayAverage,
So, the actual result of fast_info (don't know what was before) are: 'currency', 'dayHigh', 'dayLow', 'exchange', 'fiftyDayAverage', 'lastPrice', 'lastVolume', 'marketCap', 'open', 'previousClose', 'quoteType', 'regularMarketPreviousClose', 'shares', 'tenDayAverageVolume', 'threeMonthAverageVolume', 'timezone', 'twoHundredDayAverage', 'yearChange', 'yearHigh', 'yearLow'.

fast-info works for me but does not return the yield of a stock, which is the reason I am calling info

fast_info shouldn't be affected by this issue so move to a separate Issue / Discussion. I will cleanup this thread later.

No one should be guessing what anything inside yfinance does, just inspect the codebase.

It stopped working for me Oct 31.  I am in the US (NY).  fast_info does not work either.  Does anyone know, is this a known issue or maybe something I need to do?

@valueraider - I can say that while fast_info may work ok with 'main' branch - fast_info does NOT work with "feature/cookie-and-crumb" branch - something to keep in mind as work continues on that branch. As above, it barfs in quote.py:
  File "/usr/lib/python3.11/site-packages/yfinance/scrapers/quote.py", line 190, in _get_1y_prices
    ctp = self._md["currentTradingPeriod"]
          ~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^
KeyError: 'currentTradingPeriod'

Since this is a response to folks in this thread, but is also related to the PR thread - feel free to delete it.
Honestly I found the fast_info comment useful as I'm sure others may as well.
I understand that you're a bit unhappy that things are broken, but take a deep breath and count to 5 - people are trying to be helpful best they can and are looking for thoughts and guidance.  And, perhaps not all have the appropriate coding skills either for that matter.
@StanLackey - as you've gathered from this thread indeed stuff stopped working for many - some work has found differences for those in US vs EU and there is a work in progress on the feature/cookie-and-crumb branch PR here:
https://github.com/ranaroussi/yfinance/pull/1657

Please move fast_info discussion to a separate Issue / Discussion. I will lock this for a short while to give people time to read.

fast_info vs info seemed worth investigating.  Found that there was only one instance of .info() in my program and I was able to replace that with something else.
Elsewhere, things like stock.history(), to get actual prices (where type stock = yfinance.ticker.Ticker), still works and my program is running again.  It has a list of all members of QQQ and retrieves intraday prices.
So I take it that only parts of the API aren't working - which maybe I should have inferred from the topic title.

I'm not in the US, using this url the info is returned.
Perhaps the base_url and ticker.py url need changing.
https://query2.finance.yahoo.com/v7/finance/options/bt-a.l
{"optionChain":{"result":[{"underlyingSymbol":"BT-A.L","expirationDates":[],"strikes":[],"hasMiniOptions":false,"quote":{"language":"en-US","region":"US","quoteType":"EQUITY","typeDisp":"Equity","quoteSourceName":"Delayed Quote","triggerable":false,"customPriceAlertConfidence":"LOW","currency":"GBp","exchangeTimezoneShortName":"GMT","gmtOffSetMilliseconds":0,"esgPopulated":false,"regularMarketChangePercent":-1.463416,"regularMarketPrice":111.1,"messageBoardId":"finmb_171577","exchangeTimezoneName":"Europe/London","market":"gb_market","exchange":"LSE","shortName":"BT GROUP PLC ORD 5P","longName":"BT Group plc","marketState":"POSTPOST","tradeable":false,"cryptoTradeable":false,"priceHint":2,"regularMarketChange":-1.6500015,"regularMarketTime":1698860724,"regularMarketDayHigh":113.45,"regularMarketDayRange":"111.0 - 113.45","regularMarketDayLow":111.0,"regularMarketVolume":32525515,"regularMarketPreviousClose":112.75,"bid":110.1,"ask":125.0,"bidSize":0,"askSize":0,"fullExchangeName":"LSE","financialCurrency":"GBP","regularMarketOpen":113.1,"averageDailyVolume3Month":30413774,"averageDailyVolume10Day":32775872,"fiftyTwoWeekLowChange":88.118,"fiftyTwoWeekLowChangePercent":3.8342178,"fiftyTwoWeekRange":"22.982 - 165.49","fiftyTwoWeekHighChange":-54.390007,"fiftyTwoWeekHighChangePercent":-0.32866037,"fiftyTwoWeekLow":22.982,"fiftyTwoWeekHigh":165.49,"fiftyTwoWeekChangePercent":-11.741686,"earningsTimestamp":1698908400,"earningsTimestampStart":1698908400,"earningsTimestampEnd":1698908400,"trailingAnnualDividendRate":0.077,"trailingPE":5.8473682,"dividendRate":0.08,"trailingAnnualDividendYield":6.8292685E-4,"dividendYield":6.83,"epsTrailingTwelveMonths":0.19,"epsForward":18.45,"epsCurrentYear":18.24,"priceEpsCurrentYear":6.0910087,"sharesOutstanding":9943310336,"bookValue":1.49,"fiftyDayAverage":115.447,"fiftyDayAverageChange":-4.347,"fiftyDayAverageChangePercent":-0.037653644,"twoHundredDayAverage":131.6465,"twoHundredDayAverageChange":-20.546501,"twoHundredDayAverageChangePercent":-0.15607329,"marketCap":11047018496,"forwardPE":0.0602168,"priceToBook":74.56376,"sourceInterval":15,"exchangeDataDelayedBy":15,"averageAnalystRating":"2.4 - Buy","firstTradeDateMilliseconds":583743600000,"symbol":"BT-A.L"},"options":[]}],"error":null}}

Same issue here for me. I'm in the US and .info is not working for all tickers.

Please move fast_info discussion to a separate Issue / Discussion. If what you're actually talking about is the branch feature/cookie-and-crumb, then post in #1657.
I'm not unhappy, just trying to maintain order, otherwise we get a single thread with 200+ comments of interleaved conversations. That's a lot to read before replying.
I will lock this for a short while to give people time to read.

@ValueRaider If you had not hijacked the first post in this issue to talk about 'fast_info', then if would not have had a single mention in this thread.
fast_info has nothing to do with this issue, and you should not have been mentioned it.

Ticker.fast_info has subset of Ticker.info

Your comment is incorrect. Please remove it, to avoid confusing people further. I suggest you read and understand the codebase before changing other people's comments regarding this issue.

yesterday it was working fine with a US VPN, today is not. Locally it is not working either and am based in the US/EAST

The page is genuinely under maintenance I guess https://query2.finance.yahoo.com/v6/finance/quoteSummary/AAPL?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true

That message is the same as 10 days ago.

The data is returned using the modified URL ...
https://query2.finance.yahoo.com/v7/finance/options/AAPL?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true

@LordByron1788 Are you dumb? You literally posted after someone showing info contains price-related data. I assure you that fast_info is a subset of info, that's why it exists. I grant you it's a small subset, and some key names different because it was rushed out in Spring. yfinance is open-source, you could have checked this ...

yesterday it was working fine with a US VPN, today is not. Locally it is not working either and am based in the US/EAST

The page is genuinely under maintenance I guess https://query2.finance.yahoo.com/v6/finance/quoteSummary/AAPL?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true

That message is the same as 10 days ago.

The data is returned using the modified URL ...
https://query2.finance.yahoo.com/v7/finance/options/AAPL?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true

Much of the data appears to be similar but there are still some absences. sector industry and news data are all missing and possibly others as well.

The main things I was using from info were "yield" and "beta3Year", which are not in .fast_info. As mentioned by @brian-dm100, this URL has yield but not beta:
https://query2.finance.yahoo.com/v7/finance/options/bt-a.l
Is there another source of beta info?

Is it fixed?

Hi,
Here a script I wrote to fix the problem without the yfinance package in my own project. If a developer want to internalize it in yfinance be free:
class YFinance:
    user_agent_key = "User-Agent"
    user_agent_value = ("Mozilla/5.0 (Windows NT 6.1; Win64; x64) "
                        "AppleWebKit/537.36 (KHTML, like Gecko) "
                        "Chrome/58.0.3029.110 Safari/537.36")

    def __init__(self, ticker):
        self.yahoo_ticker = ticker

    def __str__(self):
        return self.yahoo_ticker

    def _get_yahoo_cookie(self):
        cookie = None

        headers = {self.user_agent_key: self.user_agent_value}
        response = requests.get("https://fc.yahoo.com",
                                headers=headers,
                                allow_redirects=True)

        if not response.cookies:
            raise Exception("Failed to obtain Yahoo auth cookie.")

        cookie = list(response.cookies)[0]

        return cookie

    def _get_yahoo_crumb(self, cookie):
        crumb = None

        headers = {self.user_agent_key: self.user_agent_value}

        crumb_response = requests.get(
            "https://query1.finance.yahoo.com/v1/test/getcrumb",
            headers=headers,
            cookies={cookie.name: cookie.value},
            allow_redirects=True,
        )
        crumb = crumb_response.text

        if crumb is None:
            raise Exception("Failed to retrieve Yahoo crumb.")

        return crumb

    @property
    def info(self):
        # Doc informations :
        # https://cryptocointracker.com/yahoo-finance/yahoo-finance-api
        cookie = self._get_yahoo_cookie()
        crumb = self._get_yahoo_crumb(cookie)
        info = {}
        ret = {}

        headers = {self.user_agent_key: self.user_agent_value}

        yahoo_modules = ("summaryDetail,"
                         "financialData,"
                         "indexTrend,"
                         "defaultKeyStatistics")

        url = ("https://query1.finance.yahoo.com/v10/finance/"
               f"quoteSummary/{self.yahoo_ticker}"
               f"?modules={urllib.parse.quote_plus(yahoo_modules)}"
               f"&ssl=true&crumb={urllib.parse.quote_plus(crumb)}")

        info_response = requests.get(url,
                                     headers=headers,
                                     cookies={cookie.name: cookie.value},
                                     allow_redirects=True)

        info = info_response.json()
        info = info['quoteSummary']['result'][0]

        for mainKeys in info.keys():
            for key in info[mainKeys].keys():
                if isinstance(info[mainKeys][key], dict):
                    try:
                        ret[key] = info[mainKeys][key]['raw']
                    except (KeyError, TypeError):
                        pass
                else:
                    ret[key] = info[mainKeys][key]

        return ret

I'm using the API v10 and only get values from this modules : "summaryDetail," "financialData," "indexTrend," "defaultKeyStatistics".
If you need more modules add it in the yahoo_modules

Thank you I will try

Hi, Here a script I wrote to fix the problem without the yfinance package in my own project. If a developer want to internalize it in yfinance be free:
...
I'm using the API v10 and only get values from this modules : "summaryDetail," "financialData," "indexTrend," "defaultKeyStatistics".
If you need more modules add it in the yahoo_modules

Just tried it and it seems to be a true and working fix. I don't know enough about the codebase but I think it should work OOTB if integrated.

@psychoz971  thank you  works well. clear code and very fast - nicely done.

I was able to get .info working by using .fast_info instead. I'm only pulling the marketCap for each Ticker in my particular use case. My program heavily relies on marketCap data. Thanks all!

@psychoz971 question - using your code snippet on ticker='^IXIC' is there a way to get current value of index?

This is what I used for a while before learning there was a currentPrice attribute for many symbols:
last = round(ticker.history(period='1d')['Close'].iloc[0], 2)
It also has the added benefit of not depending on the quoteSummary endpoint which has obviously broken multiple times recently as it uses history instead of info.

@psychoz971  I tried below code. I am sure im missing something
yf = YFinance('AAPL')
yf.info()
I am getting below error
 in _get_yahoo_cookie(self)
15
16         headers = {self.user_agent_key: self.user_agent_value}
---> 17         response = requests.get("https://fc.yahoo.com/",
18                                 headers=headers,
19                                 allow_redirects=True)
NameError: name 'requests' is not defined

OK, lot's of comments and possibilities! Is there way to retrieve the company name?

👍
On Thu, Nov 2, 2023 at 3:25 PM prabhakaran2812 @.***>
wrote:

@psychoz971 https://github.com/psychoz971 I tried below code. I am sure
im missing something
yf = YFinance('AAPL')
yf.info()
I am getting below error
https://localhost:8080/# in _get_yahoo_cookie(self)
15
16 headers = {self.user_agent_key: self.user_agent_value}
---> 17 response = requests.get("https://fc.yahoo.com/",
18 headers=headers,
19 allow_redirects=True)
NameError: name 'requests' is not defined
—
Reply to this email directly, view it on GitHub
https://github.com/ranaroussi/yfinance/issues/1729#issuecomment-1791419427,
or unsubscribe
https://github.com/notifications/unsubscribe-auth/A5QKGW24NI74BCOXW3KM2Y3YCPXTJAVCNFSM6AAAAAA6IUG7XOVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTOOJRGQYTSNBSG4
.
You are receiving this because you are subscribed to this thread.Message
ID: @.***>

Company name: not that I can see.  I'm printing out all the field names (data items) I find below.  If PASS then that field wasn't, for example, of type dict and the field is unaccepted (not in the output).
Company name appears neither in the accepted nor unaccepted values.  Not though that isn't in there somewhere in the API anyway - but not the code as it stands currently.  As best I can determine.
[note prabhakaran2812, sanyearng: code needs import requests, urllib]

D:\Projects\QQQ>python yf2.py

d:\projects\qqq\yf2.py(5)()
-> test = YFinance2('GOOG')
(Pdb) c
maxAge
priceHint
previousClose
open
dayLow
dayHigh
regularMarketPreviousClose
regularMarketOpen
regularMarketDayLow
regularMarketDayHigh
dividendRate
PASS: dividendRate
dividendYield
PASS: dividendYield
exDividendDate
PASS: exDividendDate
payoutRatio
fiveYearAvgDividendYield
PASS: fiveYearAvgDividendYield
beta
trailingPE
forwardPE
volume
regularMarketVolume
averageVolume
averageVolume10days
averageDailyVolume10Day
bid
ask
bidSize
askSize
marketCap
yield
PASS: yield
ytdReturn
PASS: ytdReturn
totalAssets
PASS: totalAssets
expireDate
PASS: expireDate
strikePrice
PASS: strikePrice
openInterest
PASS: openInterest
fiftyTwoWeekLow
fiftyTwoWeekHigh
priceToSalesTrailing12Months
fiftyDayAverage
twoHundredDayAverage
trailingAnnualDividendRate
trailingAnnualDividendYield
navPrice
PASS: navPrice
currency
fromCurrency
toCurrency
lastMarket
coinMarketCapLink
volume24Hr
PASS: volume24Hr
volumeAllCurrencies
PASS: volumeAllCurrencies
circulatingSupply
PASS: circulatingSupply
algorithm
maxSupply
PASS: maxSupply
startDate
PASS: startDate
tradeable
maxAge
priceHint
enterpriseValue
forwardPE
profitMargins
floatShares
sharesOutstanding
sharesShort
sharesShortPriorMonth
sharesShortPreviousMonthDate
dateShortInterest
sharesPercentSharesOut
heldPercentInsiders
heldPercentInstitutions
shortRatio
shortPercentOfFloat
PASS: shortPercentOfFloat
beta
impliedSharesOutstanding
morningStarOverallRating
PASS: morningStarOverallRating
morningStarRiskRating
PASS: morningStarRiskRating
category
bookValue
priceToBook
annualReportExpenseRatio
PASS: annualReportExpenseRatio
ytdReturn
PASS: ytdReturn
beta3Year
PASS: beta3Year
totalAssets
PASS: totalAssets
yield
PASS: yield
fundFamily
fundInceptionDate
PASS: fundInceptionDate
legalType
threeYearAverageReturn
PASS: threeYearAverageReturn
fiveYearAverageReturn
PASS: fiveYearAverageReturn
priceToSalesTrailing12Months
PASS: priceToSalesTrailing12Months
lastFiscalYearEnd
nextFiscalYearEnd
mostRecentQuarter
earningsQuarterlyGrowth
revenueQuarterlyGrowth
PASS: revenueQuarterlyGrowth
netIncomeToCommon
trailingEps
forwardEps
pegRatio
lastSplitFactor
lastSplitDate
enterpriseToRevenue
enterpriseToEbitda
52WeekChange
SandP52WeekChange
lastDividendValue
PASS: lastDividendValue
lastDividendDate
PASS: lastDividendDate
lastCapGain
PASS: lastCapGain
annualHoldingsTurnover
PASS: annualHoldingsTurnover
maxAge
symbol
peRatio
pegRatio
estimates
maxAge
currentPrice
targetHighPrice
targetLowPrice
targetMeanPrice
targetMedianPrice
recommendationMean
recommendationKey
numberOfAnalystOpinions
totalCash
totalCashPerShare
ebitda
totalDebt
quickRatio
currentRatio
totalRevenue
debtToEquity
revenuePerShare
returnOnAssets
returnOnEquity
grossProfits
freeCashflow
operatingCashflow
earningsGrowth
revenueGrowth
grossMargins
ebitdaMargins
operatingMargins
profitMargins
financialCurrency
marketCap = {'raw':<PHONE_NUMBER>256, 'fmt': '1.6T', 'longFmt': '1,601,643,872,256'}

Hi, Here a script I wrote to fix the problem without the yfinance package in my own project. If a developer want to internalize it in yfinance be free:
class YFinance:
    user_agent_key = "User-Agent"
    user_agent_value = ("Mozilla/5.0 (Windows NT 6.1; Win64; x64) "
                        "AppleWebKit/537.36 (KHTML, like Gecko) "
                        "Chrome/58.0.3029.110 Safari/537.36")

    def __init__(self, ticker):
        self.yahoo_ticker = ticker

    def __str__(self):
        return self.yahoo_ticker

    def _get_yahoo_cookie(self):
        cookie = None

        headers = {self.user_agent_key: self.user_agent_value}
        response = requests.get("https://fc.yahoo.com",
                                headers=headers,
                                allow_redirects=True)

        if not response.cookies:
            raise Exception("Failed to obtain Yahoo auth cookie.")

        cookie = list(response.cookies)[0]

        return cookie

    def _get_yahoo_crumb(self, cookie):
        crumb = None

        headers = {self.user_agent_key: self.user_agent_value}

        crumb_response = requests.get(
            "https://query1.finance.yahoo.com/v1/test/getcrumb",
            headers=headers,
            cookies={cookie.name: cookie.value},
            allow_redirects=True,
        )
        crumb = crumb_response.text

        if crumb is None:
            raise Exception("Failed to retrieve Yahoo crumb.")

        return crumb

    @property
    def info(self):
        # Yahoo modules doc informations :
        # https://cryptocointracker.com/yahoo-finance/yahoo-finance-api
        cookie = self._get_yahoo_cookie()
        crumb = self._get_yahoo_crumb(cookie)
        info = {}
        ret = {}

        headers = {self.user_agent_key: self.user_agent_value}

        yahoo_modules = ("summaryDetail,"
                         "financialData,"
                         "indexTrend,"
                         "defaultKeyStatistics")

        url = ("https://query1.finance.yahoo.com/v10/finance/"
               f"quoteSummary/{self.yahoo_ticker}"
               f"?modules={urllib.parse.quote_plus(yahoo_modules)}"
               f"&ssl=true&crumb={urllib.parse.quote_plus(crumb)}")

        info_response = requests.get(url,
                                     headers=headers,
                                     cookies={cookie.name: cookie.value},
                                     allow_redirects=True)

        info = info_response.json()
        info = info['quoteSummary']['result'][0]

        for mainKeys in info.keys():
            for key in info[mainKeys].keys():
                if isinstance(info[mainKeys][key], dict):
                    try:
                        ret[key] = info[mainKeys][key]['raw']
                    except (KeyError, TypeError):
                        pass
                else:
                    ret[key] = info[mainKeys][key]

        return ret

I'm using the API v10 and only get values from this modules : "summaryDetail," "financialData," "indexTrend," "defaultKeyStatistics".
If you need more modules add it in the yahoo_modules

Great solution!
Can confirm this update works off GCP's us-east-4 zone.
Thank you!

Hi @ValueRaider @psychoz971, thank you both for your amazing work!
I have created a PR that integrates both of your solutions. It should be able to fairly reliably get the info data.

Hi, Here a script I wrote to fix the problem without the yfinance package in my own project. If a developer want to internalize it in yfinance be free:
class YFinance:
    user_agent_key = "User-Agent"
    user_agent_value = ("Mozilla/5.0 (Windows NT 6.1; Win64; x64) "
                        "AppleWebKit/537.36 (KHTML, like Gecko) "
                        "Chrome/58.0.3029.110 Safari/537.36")

    def __init__(self, ticker):
        self.yahoo_ticker = ticker

    def __str__(self):
        return self.yahoo_ticker

    def _get_yahoo_cookie(self):
        cookie = None

        headers = {self.user_agent_key: self.user_agent_value}
        response = requests.get("https://fc.yahoo.com",
                                headers=headers,
                                allow_redirects=True)

        if not response.cookies:
            raise Exception("Failed to obtain Yahoo auth cookie.")

        cookie = list(response.cookies)[0]

        return cookie

    def _get_yahoo_crumb(self, cookie):
        crumb = None

        headers = {self.user_agent_key: self.user_agent_value}

        crumb_response = requests.get(
            "https://query1.finance.yahoo.com/v1/test/getcrumb",
            headers=headers,
            cookies={cookie.name: cookie.value},
            allow_redirects=True,
        )
        crumb = crumb_response.text

        if crumb is None:
            raise Exception("Failed to retrieve Yahoo crumb.")

        return crumb

    @property
    def info(self):
        # Yahoo modules doc informations :
        # https://cryptocointracker.com/yahoo-finance/yahoo-finance-api
        cookie = self._get_yahoo_cookie()
        crumb = self._get_yahoo_crumb(cookie)
        info = {}
        ret = {}

        headers = {self.user_agent_key: self.user_agent_value}

        yahoo_modules = ("summaryDetail,"
                         "financialData,"
                         "indexTrend,"
                         "defaultKeyStatistics")

        url = ("https://query1.finance.yahoo.com/v10/finance/"
               f"quoteSummary/{self.yahoo_ticker}"
               f"?modules={urllib.parse.quote_plus(yahoo_modules)}"
               f"&ssl=true&crumb={urllib.parse.quote_plus(crumb)}")

        info_response = requests.get(url,
                                     headers=headers,
                                     cookies={cookie.name: cookie.value},
                                     allow_redirects=True)

        info = info_response.json()
        info = info['quoteSummary']['result'][0]

        for mainKeys in info.keys():
            for key in info[mainKeys].keys():
                if isinstance(info[mainKeys][key], dict):
                    try:
                        ret[key] = info[mainKeys][key]['raw']
                    except (KeyError, TypeError):
                        pass
                else:
                    ret[key] = info[mainKeys][key]

        return ret

I'm using the API v10 and only get values from this modules : "summaryDetail," "financialData," "indexTrend," "defaultKeyStatistics".
If you need more modules add it in the yahoo_modules

@psychoz971 Works like a charm, Thank you.
To the yfinance admins, if there is an option to say manipulate the BASE URL / URL constructs it will be great.

Hi, Here a script I wrote to fix the problem without the yfinance package in my own project. If a developer want to internalize it in yfinance be free:
class YFinance:
    user_agent_key = "User-Agent"
    user_agent_value = ("Mozilla/5.0 (Windows NT 6.1; Win64; x64) "
                        "AppleWebKit/537.36 (KHTML, like Gecko) "
                        "Chrome/58.0.3029.110 Safari/537.36")

    def __init__(self, ticker):
        self.yahoo_ticker = ticker

    def __str__(self):
        return self.yahoo_ticker

    def _get_yahoo_cookie(self):
        cookie = None

        headers = {self.user_agent_key: self.user_agent_value}
        response = requests.get("https://fc.yahoo.com",
                                headers=headers,
                                allow_redirects=True)

        if not response.cookies:
            raise Exception("Failed to obtain Yahoo auth cookie.")

        cookie = list(response.cookies)[0]

        return cookie

    def _get_yahoo_crumb(self, cookie):
        crumb = None

        headers = {self.user_agent_key: self.user_agent_value}

        crumb_response = requests.get(
            "https://query1.finance.yahoo.com/v1/test/getcrumb",
            headers=headers,
            cookies={cookie.name: cookie.value},
            allow_redirects=True,
        )
        crumb = crumb_response.text

        if crumb is None:
            raise Exception("Failed to retrieve Yahoo crumb.")

        return crumb

    @property
    def info(self):
        # Yahoo modules doc informations :
        # https://cryptocointracker.com/yahoo-finance/yahoo-finance-api
        cookie = self._get_yahoo_cookie()
        crumb = self._get_yahoo_crumb(cookie)
        info = {}
        ret = {}

        headers = {self.user_agent_key: self.user_agent_value}

        yahoo_modules = ("summaryDetail,"
                         "financialData,"
                         "indexTrend,"
                         "defaultKeyStatistics")

        url = ("https://query1.finance.yahoo.com/v10/finance/"
               f"quoteSummary/{self.yahoo_ticker}"
               f"?modules={urllib.parse.quote_plus(yahoo_modules)}"
               f"&ssl=true&crumb={urllib.parse.quote_plus(crumb)}")

        info_response = requests.get(url,
                                     headers=headers,
                                     cookies={cookie.name: cookie.value},
                                     allow_redirects=True)

        info = info_response.json()
        info = info['quoteSummary']['result'][0]

        for mainKeys in info.keys():
            for key in info[mainKeys].keys():
                if isinstance(info[mainKeys][key], dict):
                    try:
                        ret[key] = info[mainKeys][key]['raw']
                    except (KeyError, TypeError):
                        pass
                else:
                    ret[key] = info[mainKeys][key]

        return ret

I'm using the API v10 and only get values from this modules : "summaryDetail," "financialData," "indexTrend," "defaultKeyStatistics".
If you need more modules add it in the yahoo_modules

@psychoz971 Thanks! For some reason, "assetProfile" cannot work with other module in the same module list. But it can work if it's the only module in the list. Do you know why?

@psychoz971 Thanks! For some reason, "assetProfile" cannot work with other module in the same module list. But it can work if it's the only module in the list. Do you know why?

@kuantumk everythink is good for me if I add "assetProfile". Here the script we all modules of the previews info definition, i only add assetProfile:
class YFinance:
    user_agent_key = "User-Agent"
    user_agent_value = ("Mozilla/5.0 (Windows NT 6.1; Win64; x64) "
                        "AppleWebKit/537.36 (KHTML, like Gecko) "
                        "Chrome/58.0.3029.110 Safari/537.36")

    def __init__(self, ticker):
        self.yahoo_ticker = ticker

    def __str__(self):
        return self.yahoo_ticker

    def _get_yahoo_cookie(self):
        cookie = None

        headers = {self.user_agent_key: self.user_agent_value}
        response = requests.get("https://fc.yahoo.com",
                                headers=headers,
                                allow_redirects=True)

        if not response.cookies:
            raise Exception("Failed to obtain Yahoo auth cookie.")

        cookie = list(response.cookies)[0]

        return cookie

    def _get_yahoo_crumb(self, cookie):
        crumb = None

        headers = {self.user_agent_key: self.user_agent_value}

        crumb_response = requests.get(
            "https://query1.finance.yahoo.com/v1/test/getcrumb",
            headers=headers,
            cookies={cookie.name: cookie.value},
            allow_redirects=True,
        )
        crumb = crumb_response.text

        if crumb is None:
            raise Exception("Failed to retrieve Yahoo crumb.")

        return crumb

    @property
    def info(self):
        # Yahoo modules doc informations :
        # https://cryptocointracker.com/yahoo-finance/yahoo-finance-api
        cookie = self._get_yahoo_cookie()
        crumb = self._get_yahoo_crumb(cookie)
        info = {}
        ret = {}

        headers = {self.user_agent_key: self.user_agent_value}

        yahoo_modules = ("financialData,"
                         "quoteType,"
                         "defaultKeyStatistics,"
                         "assetProfile,"
                         "summaryDetail")

        url = ("https://query1.finance.yahoo.com/v10/finance/"
               f"quoteSummary/{self.yahoo_ticker}"
               f"?modules={urllib.parse.quote_plus(yahoo_modules)}"
               f"&ssl=true&crumb={urllib.parse.quote_plus(crumb)}")

        info_response = requests.get(url,
                                     headers=headers,
                                     cookies={cookie.name: cookie.value},
                                     allow_redirects=True)

        info = info_response.json()
        info = info['quoteSummary']['result'][0]

        for mainKeys in info.keys():
            for key in info[mainKeys].keys():
                if isinstance(info[mainKeys][key], dict):
                    try:
                        ret[key] = info[mainKeys][key]['raw']
                    except (KeyError, TypeError):
                        pass
                else:
                    ret[key] = info[mainKeys][key]

        return ret

@psychoz971 Works like a charm, Thank you. To the yfinance admins, if there is an option to say manipulate the BASE URL / URL constructs it will be great.

@prabhakaran2812  if you need it I think you can add new properties base_urland cookie_url and replace it in the YFinance class.

@psychoz971 question - using your code snippet on ticker='^IXIC' is there a way to get current value of index?

@gene-git I make only the info endpoint to debug my own program and I'm thinking info doesn't have the currentPrice, sorry!

class YFinance:
    user_agent_key = "User-Agent"
    user_agent_value = ("Mozilla/5.0 (Windows NT 6.1; Win64; x64) "
                        "AppleWebKit/537.36 (KHTML, like Gecko) "
                        "Chrome/58.0.3029.110 Safari/537.36")

    def __init__(self, ticker):
        self.yahoo_ticker = ticker

    def __str__(self):
        return self.yahoo_ticker

    def _get_yahoo_cookie(self):
        cookie = None

        headers = {self.user_agent_key: self.user_agent_value}
        response = requests.get("https://fc.yahoo.com",
                                headers=headers,
                                allow_redirects=True)

        if not response.cookies:
            raise Exception("Failed to obtain Yahoo auth cookie.")

        cookie = list(response.cookies)[0]

        return cookie

    def _get_yahoo_crumb(self, cookie):
        crumb = None

        headers = {self.user_agent_key: self.user_agent_value}

        crumb_response = requests.get(
            "https://query1.finance.yahoo.com/v1/test/getcrumb",
            headers=headers,
            cookies={cookie.name: cookie.value},
            allow_redirects=True,
        )
        crumb = crumb_response.text

        if crumb is None:
            raise Exception("Failed to retrieve Yahoo crumb.")

        return crumb

    @property
    def info(self):
        # Yahoo modules doc informations :
        # https://cryptocointracker.com/yahoo-finance/yahoo-finance-api
        cookie = self._get_yahoo_cookie()
        crumb = self._get_yahoo_crumb(cookie)
        info = {}
        ret = {}

        headers = {self.user_agent_key: self.user_agent_value}

        yahoo_modules = ("financialData,"
                         "quoteType,"
                         "defaultKeyStatistics,"
                         "assetProfile,"
                         "summaryDetail")

        url = ("https://query1.finance.yahoo.com/v10/finance/"
               f"quoteSummary/{self.yahoo_ticker}"
               f"?modules={urllib.parse.quote_plus(yahoo_modules)}"
               f"&ssl=true&crumb={urllib.parse.quote_plus(crumb)}")

        info_response = requests.get(url,
                                     headers=headers,
                                     cookies={cookie.name: cookie.value},
                                     allow_redirects=True)

        info = info_response.json()
        info = info['quoteSummary']['result'][0]

        for mainKeys in info.keys():
            for key in info[mainKeys].keys():
                if isinstance(info[mainKeys][key], dict):
                    try:
                        ret[key] = info[mainKeys][key]['raw']
                    except (KeyError, TypeError):
                        pass
                else:
                    ret[key] = info[mainKeys][key]

        return ret

@psychoz971 Many thanks! It's working today. So the code is fine and it might be the API issue yesterday.

I'm trying to implement @psychoz971 YFinance class.  Can somebody post a short example of some main program code that uses this?

I'm trying to implement @psychoz971 YFinance class. Can somebody post a short example of some main program code that uses this?

Just grab the main function from the Class and modify for out-of-class usage.
`USER_AGENT = 'User-Agent'
USER_AGENT_VALUE = ("Mozilla/5.0 (Windows NT 6.1; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/58.0.3029.110 Safari/537.36")
def _get_yahoo_cookie():
 cookie = None

 headers = {USER_AGENT : USER_AGENT_VALUE}
 response = requests.get("https://fc.yahoo.com",
                            headers=headers,
                            allow_redirects=True)

 if not response.cookies:

      raise Exception("Failed to obtain Yahoo auth cookie.")

 cookie = list(response.cookies)[0]

 print ('Obtained cookie')

 return cookie

def _get_yahoo_crumb(cookie):
 crumb = None

 headers = {USER_AGENT: USER_AGENT_VALUE}

 crumb_response = requests.get(
        "https://query1.finance.yahoo.com/v1/test/getcrumb",
        headers=headers,
        cookies={cookie.name: cookie.value},
        allow_redirects=True,
    )

 crumb = crumb_response.text

 if crumb is None:

      raise Exception("Failed to get Yahoo crumb.")

 return crumb`

Or you can just use the class
client = YFinance('AAPL').info

@mykolaz Thank you for this help.  I figured out how to get .info to work with the cookies&crumbs fix but can no longer get the .Ticker method and associated .history.

@mykolaz Thank you for this help. I figured out how to get .info to work with the cookies&crumbs fix but can no longer get the .Ticker method and associated .history.

The separate class that was provided only contains the endpoint for .info. If you want to use .history() then you just have to use the standard yfinance provided Ticker class which still works fine for that use case. Until the changes are implemented into the library, what I did (since I don't have enough knowledge of the codebase to make my own fork / pull request at the moment) is just make two Ticker classes and call history or info appropriately depending on which one I need.

I am managing to work around .info no longer working to some extent.  From aIl the above activity and proposed workarounds I'm getting the impression that .info isn't going to be fixed.  I am now using fast info and .history.
My question is, I'd like to retrieve quantities like dividend yield, capitalization, PE and target mean.  I'm not a sophisticated enough python programmer to use the cookie and crumb related workarounds.  Can I get those other quantities in a more straightforward way?

And the company name, if there's a way to retrieve that, that would be great.

Names, both long and short, seem to be in there now with the change above.
        yahoo_modules = ("financialData,"
                         "quoteType,"
                         "defaultKeyStatistics,"
                         "assetProfile,"
                         "summaryDetail")

I'd love it if there was comment from a Yahoo engineer or somebody with knowledge about exactly what was changed/broken.  My guess is that everyone who has imported the Python yfinance library now has broken code.   If I manually load one of the API's URL then I see that Yahoo says "Will be right back...  Thank you for your patience.  Our engineers are working quickly to resolve the issue." but I worry that maybe Yahoo has killed specific yfinance features because maybe it was pissing off the companies who sell this data for a fee?  My hope is that Yahoo engineers really are working on this and it will soon be back to the way it was.

Part of being a tech giant is never having to say you're sorry.

from yfinance3 import YFinance3
import pdb

pdb.set_trace()
test = YFinance3('GOOG')
info = test.info
print("marketCap = " + str(info['marketCap']))
print("longName = " + str(info['longName']))

.
.
.
operatingMargins
profitMargins
financialCurrency
marketCap =<PHONE_NUMBER>072
longName = Alphabet Inc.

Hi Patfla, thanks but I don't know what to do with this information.  -Stan

From: patfla @.>
Sent: Friday, November 3, 2023 1:28 PM
To: ranaroussi/yfinance @.>
Cc: StanLackey @.>; Mention @.>
Subject: Re: [ranaroussi/yfinance] .info returns 404 on all tickers (Issue #1729)
Names, both long and short, seem to be in there now with the change above.
    yahoo_modules = ("financialData,"
                     "quoteType,"
                     "defaultKeyStatistics,"
                     "assetProfile,"
                     "summaryDetail")

—
Reply to this email directly, view it on GitHubhttps://github.com/ranaroussi/yfinance/issues/1729#issuecomment-1792852444, or unsubscribehttps://github.com/notifications/unsubscribe-auth/ASZNPAWS737GK2LYV6XTV5TYCUSS7AVCNFSM6AAAAAA6IUG7XOVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMYTOOJSHA2TENBUGQ.
You are receiving this because you were mentioned.Message ID: @.***>

@psychoz971 question - using your code snippet on ticker='^IXIC' is there a way to get current value of index?

@gene-git I make only the info endpoint to debug my own program and I'm thinking info doesn't have the currentPrice, sorry!

@gene-git @brld - Try this , there are mostly 3 values for quoteType - EQUITY, ETF, INDEX, if equity get currentPrice, if ETF get navPrice, if INDEX get previousClose

@psychoz971 Works like a charm, Thank you. To the yfinance admins, if there is an option to say manipulate the BASE URL / URL constructs it will be great.

@prabhakaran2812 if you need it I think you can add new properties base_urland cookie_url and replace it in the YFinance class.

I got that, but I want yfinance to provide property overriding, which is not the current case.
I can't do a = yf.Ticker('AAPL') ; a.BASE_URL = https://xyz in yfinance

@prabhakaran2812 - thanks but:

if INDEX get previousClose

Not what I need.  I need current value of index not yesterdays close.

Using yfinance in it's current form, no fixes, you can still retrieve the current price.

@prabhakaran2812 - thanks but:

if INDEX get previousClose

Not what I need. I need current value of index not yesterdays close.

Using yfinance, no fixes, you can still retrieve the current price.
As far as I can ascertain, yfinance 0.2.31 and previous versions can no longer retrieve .info but other functions still do work.

@brian-dm100 Thanks - I'm trying to understand the code and how yahoo API works (or doesn't) - which yahoo modules and which api v11? v10? v7? something else maybe - can be used to retrieve current value of ^IXIC?
Separately, are you guys aware of decent docs of yahoo api ?

Company name ^IXIC
Suggest Strength Price Now 13,484.34
Output from one of my TA programs. Only change I made was to comment out shortname as that is in .info and was causing program to fail because of the known .info url issue.

Company name ^IXIC
Suggest Strength Price Now 13,484.34
Output from one of my TA programs. Only change I made was to comment out shortname as that is in .info and was causing programs to fall over because of the known .info url issue.

I am managing to work around .info no longer working to some extent. From aIl the above activity and proposed workarounds I'm getting the impression that .info isn't going to be fixed. I am now using fast info and .history. My question is, I'd like to retrieve quantities like dividend yield, capitalization, PE and target mean. I'm not a sophisticated enough python programmer to use the cookie and crumb related workarounds. Can I get those other quantities in a more straightforward way?

@mykolaz Thank you for this help. I figured out how to get .info to work with the cookies&crumbs fix but can no longer get the .Ticker method and associated .history.

The separate class that was provided only contains the endpoint for .info. If you want to use .history() then you just have to use the standard yfinance provided Ticker class which still works fine for that use case. Until the changes are implemented into the library, what I did (since I don't have enough knowledge of the codebase to make my own fork / pull request at the moment) is just make two Ticker classes and call history or info appropriately depending on which one I need.

@mykolaz Thank you for this help. I figured out how to get .info to work with the cookies&crumbs fix but can no longer get the .Ticker method and associated .history.

The separate class that was provided only contains the endpoint for .info. If you want to use .history() then you just have to use the standard yfinance provided Ticker class which still works fine for that use case. Until the changes are implemented into the library, what I did (since I don't have enough knowledge of the codebase to make my own fork / pull request at the moment) is just make two Ticker classes and call history or info appropriately depending on which one I need.

It is not that difficult of a workaround. Just use the snippet of code to declare functions that return cookie and crumb. Then use the cookie and crumb like this:
`def _get_info(ticker):
 cookie = _get_yahoo_cookie()
 crumb = _get_yahoo_crumb(cookie)

 headers = {USER_AGENT: USER_AGENT_VALUE}

 # Initialized dictionaries
 info = {}
 ret = {}

 yahoo_modules = ("summaryDetail,"
                "financialData,"
                "indexTrend,"
                "defaultKeyStatistics")

 url = ("https://query1.finance.yahoo.com/v10/finance/"
           f"quoteSummary/{ticker}"
           f"?modules={urllib.parse.quote_plus(yahoo_modules)}"
           f"&ssl=true&crumb={urllib.parse.quote_plus(crumb)}")

 info_response = requests.get(url,
                               headers=headers,
                               cookies={cookie.name: cookie.value},
                               allow_redirects=True)

 info = info_response.json()
 info = info['quoteSummary']['result'][0]

 for mainKeys in info.keys():
      for key in info[mainKeys].keys():
           if isinstance(info[mainKeys][key], dict):
                try:
                     ret[key] = info[mainKeys][key]['raw']
                except (KeyError, TypeError):
                     pass
           else:
                ret[key] = info[mainKeys][key]

 return ret`

 Then use the _get_info function in a variable that you used to do with yf.Ticker({Ticker}).info

from yfinance3 import YFinance3
import pdb
pdb.set_trace()
test = YFinance3('GOOG')
info = test.info
print("marketCap = " + str(info['marketCap']))
print("longName = " + str(info['longName']))

How to install yfinance3?

Too many comments!
 data = yfinance.Ticker('GOOGL').history()
                    self.create_and_save_graph(data, "/home/container/bot/src/graph.png")
                    image = nextcord.File("/home/container/bot/src/graph.png")
                    info = yfinance.Ticker('GOOGL').info
                    city = info["city"]
                    country = info["country"]
                    industry = info["industry"]
                    summary = info["longBusinessSummary"][0:2084]
                    jobs = info["fullTimeEmployees"]
                    website = info["website"]
                    price = int(info['currentPrice']) * 10000

                this is my current code. how to fix it?

Still having trouble running (what I think is) yfinance3 (the long script from a few days ago).  For example it needs 'import urllib.requests'.  Even so I still get lots of errors.  Is it possible to get someone in a separate email chain to give some help?
<EMAIL_ADDRESS>

Still having trouble running (what I think is) yfinance3 (the long script from a few days ago). For example it needs 'import urllib.requests'. Even so I still get lots of errors. Is it possible to get someone in a separate email chain to give some help<EMAIL_ADDRESS>
try importing libraries, for example:
import requests, urllib
class YFinance3:
......

...
info = info['quoteSummary']['result'][0]
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^
TypeError: 'NoneType' object is not subscriptable

... info = info['quoteSummary']['result'][0] ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^ TypeError: 'NoneType' object is not subscriptable

ticker symbol?

AMD and INTC were the two I tried.  I can try more if you have any suggestions.

AMD and INTC were the two I tried. I can try more if you have any suggestions.

i tried above, and it worked for me. btw, i'm not using jupyter notebook. try running it from the command line

No idea what 'jupyter notebook' is.  I'm running from command line (W10)

No idea what 'jupyter notebook' is. I'm running from command line (W10)

copy/paste your code here

caller:
from yf3 import YFinance3
import yfinance as yf
import sys
while 1:
cmd = input("\nTicker: ")
iparams = cmd.split()
if (len(iparams) < 1):
sys.exit(0)
ticker = iparams[0]
if (ticker == "exit"):
sys.exit(0)
company = yf.Ticker(ticker)
print(company)
#try:
str1 = YFinance3(company)
stinfo = str1.info
myKeys = list(stinfo.keys())
if (len(iparams) == 2):
    if (iparams[1] == "sort"):
        myKeys.sort()
        substr = ""
    else:
        substr = iparams[1]
else:
    substr = ""
for nnm in myKeys:
    if (substr.lower() in nnm.lower()):
        print("%-30s %s" % (nnm, stinfo[nnm]))
#except:
#    print("No such ticker")

yf3.py:
import requests
import urllib
class YFinance3:
user_agent_key = "User-Agent"
user_agent_value = ("Mozilla/5.0 (Windows NT 6.1; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/58.0.3029.110 Safari/537.36")
def __init__(self, ticker):
    self.yahoo_ticker = ticker

def __str__(self):
    return self.yahoo_ticker

def _get_yahoo_cookie(self):
    cookie = None

    headers = {self.user_agent_key: self.user_agent_value}
    response = requests.get("https://fc.yahoo.com",
                            headers=headers,
                            allow_redirects=True)

    if not response.cookies:
        raise Exception("Failed to obtain Yahoo auth cookie.")

    cookie = list(response.cookies)[0]

    return cookie

def _get_yahoo_crumb(self, cookie):
    crumb = None

    headers = {self.user_agent_key: self.user_agent_value}

    crumb_response = requests.get(
        "https://query1.finance.yahoo.com/v1/test/getcrumb",
        headers=headers,
        cookies={cookie.name: cookie.value},
        allow_redirects=True,
    )
    crumb = crumb_response.text

    if crumb is None:
        raise Exception("Failed to retrieve Yahoo crumb.")

    return crumb

@property
def info(self):
    # Yahoo modules doc informations :
    # https://cryptocointracker.com/yahoo-finance/yahoo-finance-api
    cookie = self._get_yahoo_cookie()
    crumb = self._get_yahoo_crumb(cookie)
    info = {}
    ret = {}

    headers = {self.user_agent_key: self.user_agent_value}

    yahoo_modules = ("financialData,"
                     "quoteType,"
                     "defaultKeyStatistics,"
                     "assetProfile,"
                     "summaryDetail")

    url = ("https://query1.finance.yahoo.com/v10/finance/"
           f"quoteSummary/{self.yahoo_ticker}"
           f"?modules={urllib.parse.quote_plus(yahoo_modules)}"
           f"&ssl=true&crumb={urllib.parse.quote_plus(crumb)}")

    info_response = requests.get(url,
                                 headers=headers,
                                 cookies={cookie.name: cookie.value},
                                 allow_redirects=True)

    info = info_response.json()
    info = info['quoteSummary']['result'][0]

    for mainKeys in info.keys():
        for key in info[mainKeys].keys():
            if isinstance(info[mainKeys][key], dict):
                try:
                    ret[key] = info[mainKeys][key]['raw']
                except (KeyError, TypeError):
                    pass
            else:
                ret[key] = info[mainKeys][key]

    return ret

caller:
from yf3 import YFinance3 import yfinance as yf import sys
while 1: cmd = input("\nTicker: ") iparams = cmd.split() if (len(iparams) < 1): sys.exit(0) ticker = iparams[0] if (ticker == "exit"): sys.exit(0) company = yf.Ticker(ticker) print(company) #try:
str1 = YFinance3(company)
stinfo = str1.info
myKeys = list(stinfo.keys())
if (len(iparams) == 2):
    if (iparams[1] == "sort"):
        myKeys.sort()
        substr = ""
    else:
        substr = iparams[1]
else:
    substr = ""
for nnm in myKeys:
    if (substr.lower() in nnm.lower()):
        print("%-30s %s" % (nnm, stinfo[nnm]))
#except:
#    print("No such ticker")

yf3.py:
import requests import urllib
class YFinance3: user_agent_key = "User-Agent" user_agent_value = ("Mozilla/5.0 (Windows NT 6.1; Win64; x64) " "AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/58.0.3029.110 Safari/537.36")
def __init__(self, ticker):
    self.yahoo_ticker = ticker

def __str__(self):
    return self.yahoo_ticker

def _get_yahoo_cookie(self):
    cookie = None

    headers = {self.user_agent_key: self.user_agent_value}
    response = requests.get("https://fc.yahoo.com",
                            headers=headers,
                            allow_redirects=True)

    if not response.cookies:
        raise Exception("Failed to obtain Yahoo auth cookie.")

    cookie = list(response.cookies)[0]

    return cookie

def _get_yahoo_crumb(self, cookie):
    crumb = None

    headers = {self.user_agent_key: self.user_agent_value}

    crumb_response = requests.get(
        "https://query1.finance.yahoo.com/v1/test/getcrumb",
        headers=headers,
        cookies={cookie.name: cookie.value},
        allow_redirects=True,
    )
    crumb = crumb_response.text

    if crumb is None:
        raise Exception("Failed to retrieve Yahoo crumb.")

    return crumb

@property
def info(self):
    # Yahoo modules doc informations :
    # https://cryptocointracker.com/yahoo-finance/yahoo-finance-api
    cookie = self._get_yahoo_cookie()
    crumb = self._get_yahoo_crumb(cookie)
    info = {}
    ret = {}

    headers = {self.user_agent_key: self.user_agent_value}

    yahoo_modules = ("financialData,"
                     "quoteType,"
                     "defaultKeyStatistics,"
                     "assetProfile,"
                     "summaryDetail")

    url = ("https://query1.finance.yahoo.com/v10/finance/"
           f"quoteSummary/{self.yahoo_ticker}"
           f"?modules={urllib.parse.quote_plus(yahoo_modules)}"
           f"&ssl=true&crumb={urllib.parse.quote_plus(crumb)}")

    info_response = requests.get(url,
                                 headers=headers,
                                 cookies={cookie.name: cookie.value},
                                 allow_redirects=True)

    info = info_response.json()
    info = info['quoteSummary']['result'][0]

    for mainKeys in info.keys():
        for key in info[mainKeys].keys():
            if isinstance(info[mainKeys][key], dict):
                try:
                    ret[key] = info[mainKeys][key]['raw']
                except (KeyError, TypeError):
                    pass
            else:
                ret[key] = info[mainKeys][key]

    return ret

Not correct:
company = yf.Ticker(ticker)
str1 = YFinance3(company)
it should be:
stock = YFinance3(ticker) # e.g., 'AMD'
print(stock.info)

thanks!  Works now.

I think time for polling to see what works / doesn't work, for who and where. I'll comment some options below, and you vote on those you agree.

@psychoz971 solution in USA

@psychoz971 solution in USA

@psychoz971 solution in Europe

@psychoz971 solution in Asia

I'm new to this project and not one of its contributors but it seems that to me that 1) in principle the new, working, .info should be integrated into the existing project.  However, I'm a largely retired software engineer who worked in both tech and finance and  2) my concern would be data consistency.  I don't know the Yahoo Finance API, nor their datastores, and, again in principle, one wants to pull from s single, hopefully consistent location.  Data consistency is a very big deal in financial data - as one should hopefully appreciate.  The documentation for the new .info does give a place to start (at least as regards yf modules): https://cryptocointracker.com/yahoo-finance/yahoo-finance-api.  At cryptocointracker, eh?  That suggests some interesting things.  I mean where's Yahoo's own documentation for the Finance API?  Some other places to read:
https://www.google.com/search?hl=en&q=yahoo finance api documentation
I'd don't use this data, currently, directly to invest - I use it for, in some sense, research.

Time zone other than Eastern Time might affect data consistency. So if the query is being made outside the US, this might affect results. Still, it's not working with a VPN.

@patfla That's a lot of words but seems you're only saying "data consistency is a concern".

@francemur That's a different API, for price history not info

This has significantly impacted a project I was working on. I have tried all workarounds suggested in this thread.
Am willing to pay $ for a solution/fix.
'info fast' works but the data I need (MarketCap/Volume) is not part of that subset.

@arjune1987 Did you try this? https://github.com/ranaroussi/yfinance/pull/1657 I hope you did, it's listed up top. Post your feedback there.

@arjune1987 Did you try this? #1657 I hope you did, it's listed up top ("I have tried all workarounds").

Thank you for the quick reply, #1657 seems to work however it doesn't work for certain fields. For example here, it returns None for EnterpriseValue:
import requests

def get_yahoo_cookie():
    cookie = None

    user_agent_key = "User-Agent"
    user_agent_value = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"

    headers = {user_agent_key: user_agent_value}
    response = requests.get(
        "https://fc.yahoo.com", headers=headers, allow_redirects=True
    )

    if not response.cookies:
        raise Exception("Failed to obtain Yahoo auth cookie.")

    cookie = list(response.cookies)[0]

    return cookie

def get_yahoo_crumb(cookie):
    crumb = None

    user_agent_key = "User-Agent"
    user_agent_value = "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"

    headers = {user_agent_key: user_agent_value}

    crumb_response = requests.get(
        "https://query1.finance.yahoo.com/v1/test/getcrumb",
        headers=headers,
        cookies={cookie.name: cookie.value},
        allow_redirects=True,
    )
    crumb = crumb_response.text

    if crumb is None:
        raise Exception("Failed to retrieve Yahoo crumb.")

    return crumb

try:
    cookie = get_yahoo_cookie()
    crumb = get_yahoo_crumb(cookie)

    # Make the request to the Yahoo Finance API with the cookie and crumb
    url = f'https://query2.finance.yahoo.com/v7/finance/quote?symbols=AAPL&fields=marketCap,enterpriseValue&crumb={crumb}'
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
    }
    response = requests.get(url, headers=headers, cookies={cookie.name: cookie.value})
    data = response.json()

    # Extract the market cap and enterprise value from the response data
    if "quoteResponse" in data and data['quoteResponse']['result']:
        market_cap = data['quoteResponse']['result'][0].get('marketCap')
        enterprise_value = data['quoteResponse']['result'][0].get('enterpriseValue')
        print(f"The market capitalization of AAPL is: {market_cap}")
        print(f"The enterprise value of AAPL is: {enterprise_value}")
    else:
        print("Market capitalization and enterprise value information are not available.")
except Exception as e:
    print(f"An error occurred: {e}")

eqz@eqzs-MBP Nandtech R2 % /usr/local/bin/python3 "/Users/eqz/Documents/Nandtech R2/Scripts/APIStatus.py"
The market capitalization of AAPL is:<PHONE_NUMBER>008
The enterprise value of AAPL is: None
eqz@eqzs-MBP Nandtech R2 %

That code you posted is neither of the solutions. It contacts v7 not v10 - why?

@arjune1987 That looks like https://github.com/ranaroussi/yfinance/issues/1729#issuecomment-1790830481 not #1657. modified to use v7 not v10. Perhaps you can greatly condense your comment?

#1657

Thanks, but I am bit confused here -  I am a new developer.
I installed yfinance  v0.2.31.
 Maybe you can't help.

sorry for my novice mistakes, I finally got it working - I did not understand the fix was in a different version. I successfully installed yfinance-0.2.31b2 and can confirm it is working - thankyou  and I am sorry about my mistakes, this is why I offer $ because I am still newbie developer.

yfinance-0.2.31b2 can't possibly fix this issue. It's basically same as latest official version.

https://github.com/ranaroussi/yfinance/issues/1729#issuecomment-1790830481 (psychoz971 solution) works in Canada.  For certainty, and based on other recommendations, I was required to add the following to the start of the YFinance module given by psychoz971
import requests import urllib
and edited the yahoo_modules part of the code to include the following (for greater information access, such as company name, etc):
       yahoo_modules = ("summaryDetail,"                          "financialData,"                          "indexTrend,"                          "quoteType,"                          "assetProfile,"                          "defaultKeyStatistics")
Now, can access .info with this new YFinance module (and still can access .fast_info and .get_history_metadata() using the original yfinance module).  Really appreciate all the work and expertise that has been offered up to allow this!

Another poll, but to survey if Pull Request #1657 works / doesn't work.
USA - vote 👍 or 👎

Europe - vote 👍 or 👎

Asia - vote 👍 or 👎

for balance sheet until repair use this :
`import time
import pandas as pd
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
from pandasgui import show
def balance_sheet_collect(Ticker):
pd.options.display.float_format = '{:.0f}'.format
options = Options()
options.add_argument('--headless')  # METTRE LE MOTEUR DE recherche EN CACHER
is_link = 'https://fr.finance.yahoo.com/quote/' + Ticker + '/balance-sheet?p=A' + Ticker
driver = webdriver.Firefox(options=options)
driver.get(is_link)
# button scroll down cookies
driver.find_element(By.XPATH, '//*[@id="scroll-down-btn"]').click()
# button accept cookies
driver.find_element(By.NAME, 'agree').click()
# version anglaise
# element = driver.find_element(By.XPATH, '//*[@id="header-wrapper"]/div')
# driver.execute_script("arguments[0].style.visibility='hidden'", element)

# button expend all version anglaise
# driver.find_element(By.XPATH, '//*[@id="Col1-1-Financials-Proxy"]/section/div[2]/button').click()

# beautify soup html after cookies
html = driver.execute_script('return document.body.innerHTML;')
soup = BeautifulSoup(html, 'lxml')

close_price = [entry.text for entry in
               soup.find_all('span', {'class': 'Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)'})]

features = soup.find_all('div', class_='D(tbr)')

headers = []
temp_list = []
final = []
index = 0

# create headers
for item in features[0].find_all('div', class_='D(ib)'):
    headers.append(item.text)
# statement contents
while index <= len(features) - 1:
    # filter for each line of the statement
    temp = features[index].find_all('div', class_='D(tbc)')
    for line in temp:
        # each item adding to a temporary list
        temp_list.append(line.text)
    # temp_list added to final list
    final.append(temp_list)
    # clear temp_list
    temp_list = []
    index += 1

df = pd.DataFrame(final[1:])
df.columns = headers
driver.quit()

# function to make all values numerical
def convert_to_numeric(column):
    first_col = [i.replace(' ', '') for i in column]
    # second_col = [i.replace('-', '') for i in first_col]
    final_col = pd.to_numeric(first_col, errors='ignore')

    return final_col

for column in headers[1:]:
    df[column] = convert_to_numeric(df[column])
final_balance_df = df.fillna('-')
final_balance_df = final_balance_df.replace('-', 0.00)
final_balance_df = final_balance_df.replace('', 0.00)

return final_balance_df`

for statement until repair use
`
import pandas as pd
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options
from pandasgui import show
def statement_collect(ticker):
pd.options.display.float_format = '{:.0f}'.format
options = Options()
options.add_argument('--headless')
is_link = 'https://fr.finance.yahoo.com/quote/' + ticker + '/financials?p=' + ticker
driver = webdriver.Firefox(options=options)
driver.get(is_link)
# button scroll down cookies
driver.find_element(By.XPATH, '//*[@id="scroll-down-btn"]').click()
# button accept cookies
driver.find_element(By.NAME, 'agree').click()
# button expend all version anglaise
#driver.find_element(By.XPATH, '//*[@id="Col1-1-Financials-Proxy"]/section/div[2]/button').click()

# beautify soup html after cookies
html = driver.execute_script('return document.body.innerHTML;')
soup = BeautifulSoup(html, 'lxml')

close_price = [entry.text for entry in
               soup.find_all('span', {'class': 'Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)'})]

features = soup.find_all('div', class_='D(tbr)')

headers = []
temp_list = []
final = []
index = 0

# create headers

for item in features[0].find_all('div', class_='D(ib)'):
    headers.append(item.text)
# statement contents
while index <= len(features) - 1:
    # filter for each line of the statement
    temp = features[index].find_all('div', class_='D(tbc)')
    for line in temp:
        # each item adding to a temporary list
        temp_list.append(line.text)
    # temp_list added to final list
    final.append(temp_list)
    # clear temp_list
    temp_list = []
    index += 1

df = pd.DataFrame(final[1:])
df.columns = headers

driver.quit()
# function to make all values numerical
def convert_to_numeric(column):
    first_col = [i.replace(' ', '') for i in column]
    #second_col = [i.replace('-', '') for i in first_col]
    final_col = pd.to_numeric(first_col, errors='ignore')

    return final_col

for column in headers[1:]:
    df[column] = convert_to_numeric(df[column])
final_statement_df = df.fillna('-')

return final_statement_df

`

for cash flow use that until repair
import time
import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
from selenium import webdriver

from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.firefox.options import Options
from pandasgui import show
import concurrent.futures
NUM_THREADS = 8

def cashflowcollect(Ticker):
    pd.options.display.float_format = '{:.0f}'.format
    options = Options()
    options.add_argument('--headless')

    is_link = 'https://fr.finance.yahoo.com/quote/' + Ticker + '/cash-flow?p=' + Ticker
    driver = webdriver.Firefox(options=options)
    driver.get(is_link)
    # button scroll down cookies
    driver.find_element(By.XPATH, '//*[@id="scroll-down-btn"]').click()
    # button accept cookies
    driver.find_element(By.NAME, 'agree').click()

    # element = driver.find_element(By.XPATH, '//*[@id="header-wrapper"]/div')
    # driver.execute_script("arguments[0].style.visibility='hidden'", element)

    # button expend all
    # driver.find_element(By.XPATH, '//*[@id="Col1-1-Financials-Proxy"]/section/div[2]/button').click()

    # beautify soup html after cookies
    html = driver.execute_script('return document.body.innerHTML;')
    soup = BeautifulSoup(html, 'lxml')

    close_price = [entry.text for entry in
                   soup.find_all('span', {'class': 'Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)'})]

    features = soup.find_all('div', class_='D(tbr)')

    headers = []
    temp_list = []
    final = []
    index = 0

    # create headers
    for item in features[0].find_all('div', class_='D(ib)'):
        headers.append(item.text)
    # statement contents
    while index <= len(features) - 1:
        # filter for each line of the statement
        temp = features[index].find_all('div', class_='D(tbc)')
        for line in temp:
            # each item adding to a temporary list
            temp_list.append(line.text)
        # temp_list added to final list
        final.append(temp_list)
        # clear temp_list
        temp_list = []
        index += 1
    df = pd.DataFrame(final[1:])
    df.columns = headers
    driver.quit()

    # function to make all values numerical
    def convert_to_numeric(column):
        first_col = [i.replace(' ', '') for i in column]

        # second_col = [i.replace('-', '') for i in first_col]
        final_col = pd.to_numeric(first_col, errors='ignore')

        return final_col

    for column in headers[1:]:
        df[column] = convert_to_numeric(df[column])
    final_cashflow_df = df.fillna('-')

    return final_cashflow_df

@yalcindavid I thought financials were fine. Also please hide code or attach as file, is kinda spammy.

https://github.com/ranaroussi/yfinance/issues/1729#issuecomment-1790830481 (psychoz971 solution) works perfectly here in Europe. I've added the following at the beginning:
import requests
import urllib.parse
Thank you very much, I hope this will be integrated into the next release of yfinance.

https://github.com/ranaroussi/yfinance/issues/1729#issuecomment-1794791782
It definitely works!
Thank you!

@ValueRaider i delete it sorry

I use .history
Is there a fix for EU?

I use .history
Is there a fix for EU?

Here is a version that includes History:
`import requests
import yfinance as yf
import urllib.parse  # Add this import statement
class YFinance:
user_agent_key = "User-Agent"
user_agent_value = ("Mozilla/5.0 (Windows NT 6.1; Win64; x64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/58.0.3029.110 Safari/537.36")
def __init__(self, ticker):
    self.yahoo_ticker = ticker

def __str__(self):
    return self.yahoo_ticker

def _get_yahoo_cookie(self):
    cookie = None
    headers = {self.user_agent_key: self.user_agent_value}
    response = requests.get("https://fc.yahoo.com",
                            headers=headers,
                            allow_redirects=True)

    if not response.cookies:
        raise Exception("Failed to obtain Yahoo auth cookie.")

    cookie = list(response.cookies)[0]

    return cookie

def _get_yahoo_crumb(self, cookie):
    crumb = None
    headers = {self.user_agent_key: self.user_agent_value}
    crumb_response = requests.get(
        "https://query1.finance.yahoo.com/v1/test/getcrumb",
        headers=headers,
        cookies={cookie.name: cookie.value},
        allow_redirects=True,
    )
    crumb = crumb_response.text

    if crumb is None:
        raise Exception("Failed to retrieve Yahoo crumb.")

    return crumb

def get_history(self, period="max"):
    # Obtain cookies and crumb for downloading historical data
    cookie = self._get_yahoo_cookie()
    crumb = self._get_yahoo_crumb(cookie)

    # Fetch historical stock data using yfinance
    stock = yf.Ticker(self.yahoo_ticker)
    return stock.history(period=period)

@property
def info(self):
    cookie = self._get_yahoo_cookie()
    crumb = self._get_yahoo_crumb(cookie)
    info = {}
    ret = {}

    headers = {self.user_agent_key: self.user_agent_value}

    yahoo_modules = ("summaryDetail,"
                     "financialData,"
                     "quoteType,"
                     "assetProfile,"
                     "indexTrend,"
                     "defaultKeyStatistics")

    url = ("https://query1.finance.yahoo.com/v10/finance/"
           f"quoteSummary/{self.yahoo_ticker}"
           f"?modules={urllib.parse.quote_plus(yahoo_modules)}"  # Use urllib.parse.quote_plus
           f"&ssl=true&crumb={urllib.parse.quote_plus(crumb)}")  # Use urllib.parse.quote_plus

    info_response = requests.get(url,
                                 headers=headers,
                                 cookies={cookie.name: cookie.value},
                                 allow_redirects=True)

    info = info_response.json()
    info = info['quoteSummary']['result'][0]

    for mainKeys in info.keys():
        for key in info[mainKeys].keys():
            if isinstance(info[mainKeys][key], dict):
                try:
                    ret[key] = info[mainKeys][key]['raw']
                except (KeyError, TypeError):
                    pass
            else:
                ret[key] = info[mainKeys][key]

    return ret

`

@francemur Hi this work for me form France/Enrope.

Latest version of #1657 should fix info, everyone test it, and vote feedback here: https://github.com/ranaroussi/yfinance/issues/1729#issuecomment-1793803181

@francemur @HelioCard Vote instead of replying (see top post)

/vote I'm using my version which is working perfectly (https://github.com/ranaroussi/yfinance/issues/1729#issuecomment-1795344783) Thank you all for your help, especially psychoz971 https://github.com/ranaroussi/yfinance/issues/1729#issuecomment-1790830481 , I've just added some more stuff to his great work.

@francemur is the underlying cookie/crumb strategy different?

@francemur is the underlying cookie/crumb strategy different?

If you compare my script with the original one, you'll see there are more chances to make this work as a turnkey solution for many. Still, most of the credit for this must go to psychoz971, I have only refined the code.

@francemur Can you submit a patch to #1657 ?

I use .history
Is there a fix for EU?

Here is a version that includes History:
import requests
import yfinance as yf
import urllib.parse  # Add this import statement

class YFinance:
    user_agent_key = "User-Agent"
    user_agent_value = ("Mozilla/5.0 (Windows NT 6.1; Win64; x64) "
                        "AppleWebKit/537.36 (KHTML, like Gecko) "
                        "Chrome/58.0.3029.110 Safari/537.36")

    def __init__(self, ticker):
        self.yahoo_ticker = ticker

    def __str__(self):
        return self.yahoo_ticker

    def _get_yahoo_cookie(self):
        cookie = None
        headers = {self.user_agent_key: self.user_agent_value}
        response = requests.get("https://fc.yahoo.com",
                                headers=headers,
                                allow_redirects=True)

        if not response.cookies:
            raise Exception("Failed to obtain Yahoo auth cookie.")

        cookie = list(response.cookies)[0]

        return cookie

    def _get_yahoo_crumb(self, cookie):
        crumb = None
        headers = {self.user_agent_key: self.user_agent_value}
        crumb_response = requests.get(
            "https://query1.finance.yahoo.com/v1/test/getcrumb",
            headers=headers,
            cookies={cookie.name: cookie.value},
            allow_redirects=True,
        )
        crumb = crumb_response.text

        if crumb is None:
            raise Exception("Failed to retrieve Yahoo crumb.")

        return crumb

    def get_history(self, period="max"):
        # Obtain cookies and crumb for downloading historical data
        cookie = self._get_yahoo_cookie()
        crumb = self._get_yahoo_crumb(cookie)

        # Fetch historical stock data using yfinance
        stock = yf.Ticker(self.yahoo_ticker)
        return stock.history(period=period)

    @property
    def info(self):
        cookie = self._get_yahoo_cookie()
        crumb = self._get_yahoo_crumb(cookie)
        info = {}
        ret = {}

        headers = {self.user_agent_key: self.user_agent_value}

        yahoo_modules = ("summaryDetail,"
                         "financialData,"
                         "quoteType,"
                         "assetProfile,"
                         "indexTrend,"
                         "defaultKeyStatistics")

        url = ("https://query1.finance.yahoo.com/v10/finance/"
               f"quoteSummary/{self.yahoo_ticker}"
               f"?modules={urllib.parse.quote_plus(yahoo_modules)}"  # Use urllib.parse.quote_plus
               f"&ssl=true&crumb={urllib.parse.quote_plus(crumb)}")  # Use urllib.parse.quote_plus

        info_response = requests.get(url,
                                     headers=headers,
                                     cookies={cookie.name: cookie.value},
                                     allow_redirects=True)

        info = info_response.json()
        info = info['quoteSummary']['result'][0]

        for mainKeys in info.keys():
            for key in info[mainKeys].keys():
                if isinstance(info[mainKeys][key], dict):
                    try:
                        ret[key] = info[mainKeys][key]['raw']
                    except (KeyError, TypeError):
                        pass
                else:
                    ret[key] = info[mainKeys][key]

        return ret

And what to do with it?
This is my current code
info = yfinance.Ticker("MSF.DE").info
        ms_actual_price = int(info['currentPrice']) * 10000

I use .history
Is there a fix for EU?

Here is a version that includes History:
import requests
import yfinance as yf
import urllib.parse  # Add this import statement

class YFinance:
    user_agent_key = "User-Agent"
    user_agent_value = ("Mozilla/5.0 (Windows NT 6.1; Win64; x64) "
                        "AppleWebKit/537.36 (KHTML, like Gecko) "
                        "Chrome/58.0.3029.110 Safari/537.36")

    def __init__(self, ticker):
        self.yahoo_ticker = ticker

    def __str__(self):
        return self.yahoo_ticker

    def _get_yahoo_cookie(self):
        cookie = None
        headers = {self.user_agent_key: self.user_agent_value}
        response = requests.get("https://fc.yahoo.com",
                                headers=headers,
                                allow_redirects=True)

        if not response.cookies:
            raise Exception("Failed to obtain Yahoo auth cookie.")

        cookie = list(response.cookies)[0]

        return cookie

    def _get_yahoo_crumb(self, cookie):
        crumb = None
        headers = {self.user_agent_key: self.user_agent_value}
        crumb_response = requests.get(
            "https://query1.finance.yahoo.com/v1/test/getcrumb",
            headers=headers,
            cookies={cookie.name: cookie.value},
            allow_redirects=True,
        )
        crumb = crumb_response.text

        if crumb is None:
            raise Exception("Failed to retrieve Yahoo crumb.")

        return crumb

    def get_history(self, period="max"):
        # Obtain cookies and crumb for downloading historical data
        cookie = self._get_yahoo_cookie()
        crumb = self._get_yahoo_crumb(cookie)

        # Fetch historical stock data using yfinance
        stock = yf.Ticker(self.yahoo_ticker)
        return stock.history(period=period)

    @property
    def info(self):
        cookie = self._get_yahoo_cookie()
        crumb = self._get_yahoo_crumb(cookie)
        info = {}
        ret = {}

        headers = {self.user_agent_key: self.user_agent_value}

        yahoo_modules = ("summaryDetail,"
                         "financialData,"
                         "quoteType,"
                         "assetProfile,"
                         "indexTrend,"
                         "defaultKeyStatistics")

        url = ("https://query1.finance.yahoo.com/v10/finance/"
               f"quoteSummary/{self.yahoo_ticker}"
               f"?modules={urllib.parse.quote_plus(yahoo_modules)}"  # Use urllib.parse.quote_plus
               f"&ssl=true&crumb={urllib.parse.quote_plus(crumb)}")  # Use urllib.parse.quote_plus

        info_response = requests.get(url,
                                     headers=headers,
                                     cookies={cookie.name: cookie.value},
                                     allow_redirects=True)

        info = info_response.json()
        info = info['quoteSummary']['result'][0]

        for mainKeys in info.keys():
            for key in info[mainKeys].keys():
                if isinstance(info[mainKeys][key], dict):
                    try:
                        ret[key] = info[mainKeys][key]['raw']
                    except (KeyError, TypeError):
                        pass
                else:
                    ret[key] = info[mainKeys][key]

        return ret

And what to do with it?
This is my current code
info = yfinance.Ticker("MSF.DE").info
        ms_actual_price = int(info['currentPrice']) * 10000

But I also use
data = yfinance.Ticker('MSF.DE').history()
                    self.create_and_save_graph(data, "/home/container/bot/src/graph.png")

    def create_and_save_graph(self, data_frame, output_file):
        df = data_frame
        df["High"] = df["High"] * 10000
        plt.figure(figsize=(12, 6))
        plt.plot(df.index, df['High'], label='Price')
        plt.xlabel('Date')
        plt.ylabel('Price per share')
        plt.title('Coin price over time')
        plt.legend()
        plt.gca().yaxis.set_major_formatter(ticker.StrMethodFormatter('{x:.0f} Coins'))

        plt.tight_layout()

        buffer = io.BytesIO()
        plt.savefig(buffer, format='png')
        buffer.seek(0)

        with open(output_file, 'wb') as f:
            f.write(buffer.read())

        plt.close()

got it

@HumanBot000 do you really need to quote the full code, twice?

Currently I am using https://query2.finance.yahoo.com/v7/finance/options/AAPL which gives us the option chain with quote details
import requests
import json

url = "https://query2.finance.yahoo.com/v7/finance/options/AAPL"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'}
response = requests.get(url=url, headers=headers)
if response.status_code == 200:
  data = json.loads(response.content)
  print(data['optionChain']['result'][0]['quote']) # provides fundamental data
else:
  print('Error fetching data from URL:', response.status_code)

No Dice for me.  Still getting the same error -->    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://query2.finance.yahoo.com/v6/finance/quoteSummary/GLW?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true
Which takes you to a page that says
Yahoo Logo
Will be right back...
Thank you for your patience.
Our engineers are working quickly to resolve the issue.
What next?

pip install git+https://github.com/ranaroussi/yfinance@feature/cookie-and-crumb
Didn't work for me, location: India.

@Breezeman69 That says v6, tells me you haven't read this thread.

No Dice for me. Still getting the same error --> raise HTTPError(http_error_msg, response=self) requests.exceptions.HTTPError: 404 Client Error: Not Found for url: https://query2.finance.yahoo.com/v6/finance/quoteSummary/GLW?modules=financialData&modules=quoteType&modules=defaultKeyStatistics&modules=assetProfile&modules=summaryDetail&ssl=true
Which takes you to a page that says Yahoo Logo Will be right back... Thank you for your patience.
Our engineers are working quickly to resolve the issue.
What next?

First, use my custom class. Copy the code I provided in my previous post, save it as a.py file and name it as "YourCustomYFinance.py" Put the file in the very same directory of your .py script. Then you also have to edit your original .py script to make sure it will be using the customized class.
For instance, if in your original script you had:
import yfinance as yf import pandas as pd from datetime import datetime, timedelta, timezone
You should replace it with this at the beginning of your script:
import requests import pandas as pd from datetime import datetime, timedelta, timezone import urllib.parse  # Add this import statement from YourCustomYFinance30 import YFinance  # Import your custom YFinance class
Hope this helps...

I have an existing .py script(original) it as at the beginning of it.
Import yfinance
import requests
import yfinance as yf
from bs4 import BeautifulSoup
I use PyCharm for my IDE and I am newbie at these things.
So can you please explain what this custom code is for this script you refer to as "YourCustoFinance.py"and where it needs to be placed in directory structures.  Can I just create it in the same project file?
Also if you could provide the modified portion at the beginning of my script given what I provided above I would really appreciate it.
Sorry for all the questions but being a newbie these are real challenges for me.  Thanks :)

Attached is my full script that is facing this issue.  It alwayts has worked for me but now broken past few days or so.
Stock Chart.txt

To me, It still gives me the same error.

I used VPN (not worked)
I changed to an old version (not work for me)
I used the F12, but there appears an error on the Yahoo website like the one we face. (weird)

The solution @iamsaicharan is the nearest solution to me, not all data is available but helps a lot.
Thanks to you all, community.

OK.  Thanks.  Maybe the Yahoo Engineers will fix it like message says
"Our engineers are working quickly to resolve the issue."
:>)

@Breezeman69

... finance.yahoo.com/v6/finance ...

Why v6? v6 is broken, none of the solutions use it.

ValueRaider.  I got that it is broken,   Was looking for other direction here.

@Breezeman69 You didn't look really, there are several solutions documented in this thread.

For the kind of programmers like me (not really experienced and patient) , to fix it I needed to remove the old installation of yfinance (the same version) and install with pip install git+https://github.com/ranaroussi/yfinance@feature/cookie-and-crumb and it worked.

yup, it worked for me as well. thanks

Could there be a bug that will cause new on missing attributes clear when trying to clear cookies session. In the code data.py under yfinance.
The part of the init constructor where _session is set:
self._session = session or requests
Fix:
self._session = session or requests.Session()

Attached is my full script that is facing this issue. It alwayts has worked for me but now broken past few days or so.
Stock Chart.txt

Very easy. As I said, with my custom class, the problem will be fixed. Here is your modified script and the custom class for yfinance. Please rename both of them from  .txt to .py and make sure to put both of them in the same directory.
All: I can't fix the anybody's, but as I mentioned earlier, if you check this example and read my previous posts, you will realize this is a possible solution to the issue that originated this thread.
Plot stock Charts - Fixed.txt
YourCustomYFinance.txt

Francemur, Thank Youso much!  It works like a charm.  Much appreciated for eceryone's assistance and the community as a whole

yf.Ticker("MSFT").history().iloc[-1,0] is working for me for now

A better solution is to install this branch https://github.com/ranaroussi/yfinance/pull/1657

For the kind of programmers like me (not really experienced and patient) , to fix it I needed to remove the old installation of yfinance (the same version) then do #1729 (comment)

This worked for me as well. Uninstalled yfinance, and did the steps in the comments. Restarted my jupyter notebook in between steps

At the risk of a redundant comment, uninstalling and then branch-installing:
$ pip uninstall yfinance
$ pip install git+https://github.com/ranaroussi/yfinance@feature/cookie-and-crumb

worked for me, too. info is now working again. (I'm in the U.S.)
Thank you!

Same py script works on my macboook but not on my conventional Fedor 38 installation on my desktop

Not sure if this is important to anyone else, but I had tried to install the cookie-and-crumb feature branch multiple times, and at one point I was wondering if the updates actually got applied, since pip caches the downloaded packages by default. So, I started to disable the installation cache. I am honestly not sure whether this made a difference for me, but it's working now. If you suspect this might be a problem for you, you can try this:
pip install git+https://github.com/ranaroussi/yfinance@feature/cookie-and-crumb --no-cache-dir

or, if you use SSH:
pip install git+ssh://git@github.com/ranaroussi/yfinance@feature/cookie-and-crumb --no-cache-dir

This will force pip to download the most recent version from Github.

Not sure if this is important to anyone else, but I had tried to install the cookie-and-crumb feature branch multiple times, and at one point I was wondering if the updates actually got applied, since pip caches the downloaded packages by default. So, I started to disable the installation cache. I am honestly not sure whether this made a difference for me, but it's working now. If you suspect this might be a problem for you, you can try this:
pip install git+https://github.com/ranaroussi/yfinance@feature/cookie-and-crumb --no-cache-dir

or, if you use SSH:
pip install git+ssh://git@github.com/ranaroussi/yfinance@feature/cookie-and-crumb --no-cache-dir

This will force pip to download the most recent version from Github.

THIS WORKED FOR ME. Thank you, God Bless.

I tried this:
pip install git+https://github.com/ranaroussi/yfinance@feature/cookie-and-crumb --no-cache-dir
and I get:
TypeError: unsupported operand type(s) for |: 'dict' and 'dict'
Not really sure if it helps..

@ramosreenata: This probably means that this branch needs Python 3.9 (October 2020). The '|' operator, aka pipe, is defined as dictionary merge in Python 3.9.

@ramosreenata  '|' operator was introduced in 0.2.27. Not relevant here.

pip install git+https://github.com/ranaroussi/yfinance@feature/cookie-and-crumb

This is failing now with the below error,
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='fc.yahoo.com', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x13c31c5d0>: Failed to establish a new connection: [Errno 61] Connection refused'))

Hi, please can I ask if there's planning to make 0.2.32b1 available on pypi.org ?

@brian-dm100  it's not available anywhere, I deleted it almost immediately.

I don't know what you did but it also reduced A LOT the CPU usage for downloading history() and get_info(). Thanks!

Agreed @antonior the process is more performant. @ValueRaider and everyone, excellent progress, great work!

A great way to express gratitude is contributing to project. There's a dozen abandoned incomplete Pull Requests, and some Issues that need fixing.

The fix works, but not if input a ISIN instead of a symbol:
yf_ticker=yf.Ticker("US0079031078")
yf_ticker.info
returns:
HTTPError: 404 Client Error: Not Found for url: https://query2.finance.yahoo.com/v10/finance/quoteSummary/US0079031078?modules=financialData%2CquoteType%2CdefaultKeyStatistics%2CassetProfile%2CsummaryDetail&ssl=true&crumb=nkKfTFXt4wT
While
yf_ticker=yf.Ticker("AMD")
yf_ticker.info
returns the original .info.
Is there a workaround on this?

@SteynGuelen Move to a new Issue.

still does not work even you are US IP.

@tonydeck0506 https://github.com/ranaroussi/yfinance/issues/1729#issuecomment-1817503067