-1

I have following script for stock data...

import pandas as pd
import requests
import json

baseurl = "https://www.nseindia.com/"
url = f'https://www.nseindia.com/api/quote-derivative?symbol=ACC'

headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, ''like Gecko) ''Chrome/80.0.3987.149 Safari/537.36','accept-language': 'en,gu;q=0.9,hi;q=0.8', 'accept-encoding': 'gzip, deflate, br'}

session = requests.Session()
request = session.get(baseurl, headers=headers, timeout=30)
cookies = dict(request.cookies)
res = session.get(url, headers=headers, timeout=30, cookies=cookies)
data = res.json()
print(data)

Here I want to fetch "totalBuyQuantity" and "totalSellQuantity" for stock future for current expiry (27 Oct 2022). How to get that plz ???

  • Your JSON is parsed into a Python dictionary use `data.keys()` to see the dictionary's keys, `data['stocks']` would give you a list containing your stock dictionary objects where you can then loop over and extract it based on your condition – dreadnaught Oct 25 '22 at 12:10
  • Can you elaborate a little bit more plz with few suggestive codes plz. I'm just a beginner plz. – Python Learner Oct 25 '22 at 12:12
  • You can loop over your data object like this: https://stackoverflow.com/questions/3294889/iterating-over-dictionaries-using-for-loops. – dreadnaught Oct 25 '22 at 12:13

1 Answers1

1

I am new to coding myself, but I got all the values out and put them in a dictionary with keys 'totalBuyQuantity', 'totalSellQuantity'. I think because the json is nested, you have to write a recursive function. If there is a more simple solution I would also be happy to know (maybe I am still thinking to complex haha). Anyway...here the code:


def quantities(values, keys=None):
    if keys is None:
        keys = {'totalBuyQuantity':[], 'totalSellQuantity':[]}
    if isinstance(values, dict):
        for key in values.keys():
            if key == 'totalBuyQuantity':
                keys[key].append(values[key])
            elif key == 'totalSellQuantity':
                keys[key].append(values[key])
            elif isinstance(values[key], (dict, list)):
                quantities(values[key], keys)
    elif isinstance(values, list):
        for value in values:
            quantities(value, keys)
    return keys

print(quantities(data))

Jana
  • 49
  • 2
  • 6