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:

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'))

Leave a Reply