Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python3
- # date: 2024.05.26
- # Stackoverflow:
- # pandas - KeyError when trying to access 'data' from StockData.org API response in Python - Stack Overflow
- # https://stackoverflow.com/questions/78532919/keyerror-when-trying-to-access-data-from-stockdata-org-api-response-in-python)
- # Documentation:
- # StockData.org - API Documentation - intraday data (unadjusted)
- # https://www.stockdata.org/documentation#intraday-data
- # requests-cache:
- # requests-cache 1.2.0 documentation
- # https://requests-cache.readthedocs.io/en/stable/
- from datetime import timedelta
- #import requests
- import requests_cache
- import pandas as pd
- # keep responses in sqlite because API has limit of requests
- # (free account has limit 100 requests/day)
- session = requests_cache.CachedSession('requests_stockdata', expire_after=timedelta(hours=1))
- payload = {
- 'api_token': '<API KEY>',
- 'symbols': 'NVDA', # `symbols` with char `s` - even if you send only one symbol
- 'intervals': 'minute', # allowed `minute` and `hour` but not `1m`
- }
- url = 'https://api.stockdata.org/v1/data/intraday'
- #response = requests.get(url, params=payload)
- response = session.get(url, params=payload)
- data = response.json()
- if 'message' in data:
- print(data['message'])
- if 'data' in data:
- df = pd.DataFrame(data['data'])
- # convert dict in one column into seperate columns
- data_as_colums = df['data'].apply(pd.Series)
- df_without_data = df.drop(columns=['data'])
- df = pd.concat([df_without_data, data_as_colums], axis=1)
- print(df.head())
- df.to_csv('NVDA_minute_data.csv', index=False)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement