Home > Software design >  How to get live stock price?
How to get live stock price?

Time:06-24

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?

CodePudding user response:

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