Ivan Parra
Ivan Parra

Reputation: 660

Error: Errno socket error] [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:727)

I have a little code, in python 2.7.17, where I'm trying to reach the Yahoo! Finance API to get information about a stock, but when I execute it, I get an error. I don't know how to fix it.

This is the code:

 import urllib

urlStock = 'http://finance.yahoo.com/d/quotes.csv?s=aapl&f=nagh' 
response = urllib.urlopen(urlStock).read()
print response

And this is the error:

   Exception has occurred: IOError
[Errno socket error] [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:727)
  File "/Users/ivanparra/Dropbox/Aprendizaje Python/InternetTests.py", line 4, in <module>
    response = urllib.urlopen(urlStock).read()

Upvotes: 1

Views: 2748

Answers (1)

linqo
linqo

Reputation: 647

That site has been discontinued for since 2018, unfortunately (more discussion here). However, there is an alternative, as pointed out on the linked Github issue thread. The URL is:

https://query1.finance.yahoo.com/v7/finance/quote?lang=en-US&region=US&corsDomain=finance.yahoo.com&symbols=AAPL&fields=regularMarketPrice

Personally, I tend to prefer using the requests library (which you can easily install with pip) whenever possible because of its simple syntax. If you have SSL issues, see my comment in the example code.

Here's how I'd query it:

import requests
import pdb

res = requests.get("https://query1.finance.yahoo.com/v7/finance/quote?lang=en-US&region=US&corsDomain=finance.yahoo.com&symbols=AAPL&fields=regularMarketPrice")
# If you need to work around SSL issues, set the verify kw arg to False. For example:
# requests.get("URL_HERE", verify=False)

stock_data = res.json()
price = stock_data['quoteResponse']['result'][0]['regularMarketPrice']
print(price)

Upvotes: 1

Related Questions