Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get live stock price?

def get_stock_price(symbol):
    """get a stock price from yahoo finance"""
    import requests
    import json
    url = "https://query1.finance.yahoo.com/v7/finance/quote?symbols=" + symbol
    response = requests.get(url)
    data = json.loads(response.text)
    return data['quoteResponse']['result'][0]['regularMarketPrice']


print(get_stock_price('AAPL'))

I’m getting an error message says

Exception has occurred: JSONDecodeError
Expecting value: line 1 column 1 (char 0)

During handling of the above exception, another exception occurred:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Can someone please help to fix the error message?

>Solution :

You would need to pass some user-agent script in header to get this working. Please see below:

import requests
import json

def get_stock_price(symbol):
    """get a stock price from yahoo finance"""

    url = "https://query1.finance.yahoo.com/v7/finance/quote?symbols=" + symbol
    headers = {'User-Agent': 'Mozilla/5.0'}
    response = requests.get(url, headers=headers)    
    data = json.loads(response.text)
    
    return data['quoteResponse']['result'][0]['regularMarketPrice']


print(get_stock_price('AAPL'))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading