Scrape current stock price and create data frame

Viewed 180

I have a pandas list called Symbols with 30 ticker symbols for stock e.g., Apple ->> AAPL, and I would like to grab the current stock price for each ticker and populate a data frame with this info. Two columns: the first with ticker symbols and the second with current price. I continue getting the following error message when I run this part of my script:

"ValueError: If using all scalar values, you must pass an index"

Stock = []
Price = []
df_temp = []

for symbol in Symbols:
    try:
        params = {
        'symbols': symbol,
        'range': '1d',
        'interval': '1d',
        'indicators': 'close',
        'includeTimestamps': 'false',
        'includePrePost': 'false',
        'corsDomain': 'finance.yahoo.com',
        '.tsrc': 'finance'}

        url = 'https://query1.finance.yahoo.com/v7/finance/spark'

        r = requests.get(url, params=params)
        data = r.json()
                
        df_stock = pd.DataFrame({'Ticker' : symbol,
                                'Current Price' : data['spark']['result'][0]['response'][0]['indicators']['quote'][0]['close'][0]
                                })
        
        df_temp.append(df_stock)
        df_temp = pd.concat(df_temp, axis = 1)
    except KeyError:
        continue
1 Answers

Need to change only one part -

df_stock = pd.DataFrame({'Ticker' : [symbol],
                                'Current Price' : [data['spark']['result'][0]['response'][0]['indicators']['quote'][0]['close'][0]]
                                })

Output

    Ticker  Current Price
0   AAPL        118.119

Full Code

Stock = []
Price = []
df_temp = pd.DataFrame()

for symbol in ['AAPL', 'IBM', 'NKE', 'FB']:
    try:
        params = {
        'symbols': symbol,
        'range': '1d',
        'interval': '1d',
        'indicators': 'close',
        'includeTimestamps': 'false',
        'includePrePost': 'false',
        'corsDomain': 'finance.yahoo.com',
        '.tsrc': 'finance'}

        url = 'https://query1.finance.yahoo.com/v7/finance/spark'

        r = requests.get(url, params=params)
        data = r.json()
                
        df_stock = pd.DataFrame({'Ticker' : [symbol],
                                'Current Price' : [data['spark']['result'][0]['response'][0]['indicators']['quote'][0]['close'][0]]
                                })
        
        df_temp = df_temp.append(df_stock)
    except KeyError:
        continue

Explanation

What you were passing as values to the df_stock were scalar values, wrapped in a list solves it.

Related