Fetch Stock Data


Fetch Stock Data from Yahoo Finance and Convert to Pandas DataFrame


This example demonstrates how to fetch stock price data from Yahoo Finance using a URL endpoint that returns JSON data. We then parse the JSON data to extract the stock's timestamp and closing prices. Finally, we convert this data into a pandas DataFrame for further analysis. The timestamps are converted to human-readable datetime format.

Here we are using the %5ENSEI index, which represents NIFTY50.


Install Pandas

import micropip import asyncio asyncio.ensure_future(micropip.install('pandas'))

Here will fetch the stock data from yahoo and transform to dataframe


from pyodide.http import open_url import pandas as pd import json # Define dynamic parameters symbol = "%5ENSEI" # You can replace with other indices like ^NSEBANK, etc. interval = "1d" # Options: 1m, 2m, 5m, 15m, 1d, etc. range = "6mo" # Options: 1d, 5d, 1mo, 6mo, 1y, etc. # Construct the dynamic URL base_url = "https://query1.finance.yahoo.com/v8/finance/chart/" url = f"/fetch?url=https://query1.finance.yahoo.com/v8/finance/chart/{symbol}?interval={interval}%26range={range}" # Step 2: Fetch and parse data response = open_url(url) data = response.read() parsed = json.loads(data) # Step 3: Extract time and price data chart = parsed['chart']['result'][0] timestamps = chart['timestamp'] quote = chart['indicators']['quote'][0] df = pd.DataFrame({ 'timestamp': timestamps, 'close': quote['close'], 'open': quote['open'], 'low': quote['low'], 'high': quote['high'], 'volume': quote['volume'] }) # Step 4: Convert timestamp df['timestamp'] = pd.to_datetime(df['timestamp'], unit='s') df