Skip to content

How to call stock market API to extract JSON Data using Python?

Alpha Vantage offers free stock market dataset API for retrieving stock market data. This post will be using a demo API link to explain how to extract the JSON data using Python.

In Python “requests” is a very popular package that allows to interact with the web applications and APIs.

Install Python “requests” package if it is not already installed.

$ pip install requests

Or if you are not using code spaces you can use following command

$ python3 -m pip install requests

The following code calls stock market dataset API and extracts JSON that can be further analysed.  First import “requests” package to call the API, “json” package for JSON data processing and write it in the .json file

import requests
import json
response = requests.get(
    "https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=IBM&interval=5min&apikey=demo")
IBM_intra_day_5min = response.json()
with open("IBM.json", "w") as f:
    json.dump(IBM_intra_day_5min, f, indent=2)

#Output 
IBM.json

The IBM stock JSON data looks like following:

{
  "Meta Data": {
    "1. Information": "Intraday (5min) open, high, low, close prices and volume",
    "2. Symbol": "IBM",
    "3. Last Refreshed": "2024-01-12 19:55:00",
    "4. Interval": "5min",
    "5. Output Size": "Compact",
    "6. Time Zone": "US/Eastern"
  },
  "Time Series (5min)": {
    "2024-01-12 19:55:00": {
      "1. open": "165.7800",
      "2. high": "165.7800",
      "3. low": "165.6100",
      "4. close": "165.6110",
      "5. volume": "155"
    },
    "2024-01-12 19:50:00": {
      "1. open": "165.6200",
      "2. high": "165.7800",
      "3. low": "165.6100",
      "4. close": "165.7800",
      "5. volume": "257"
    },....
Leave a Reply

Your email address will not be published. Required fields are marked *