Advertisement
furas

Python - StockData.org API - (Stackoverflow)

May 26th, 2024 (edited)
696
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.62 KB | None | 0 0
  1. #!/usr/bin/env python3
  2.  
  3. # date: 2024.05.26
  4.  
  5. # Stackoverflow:
  6. # pandas - KeyError when trying to access 'data' from StockData.org API response in Python - Stack Overflow
  7. # https://stackoverflow.com/questions/78532919/keyerror-when-trying-to-access-data-from-stockdata-org-api-response-in-python)
  8.  
  9. # Documentation:
  10. # StockData.org - API Documentation - intraday data (unadjusted)
  11. # https://www.stockdata.org/documentation#intraday-data
  12.  
  13. # requests-cache:
  14. # requests-cache 1.2.0 documentation
  15. # https://requests-cache.readthedocs.io/en/stable/
  16.  
  17. from datetime import timedelta
  18. #import requests
  19. import requests_cache
  20. import pandas as pd
  21.  
  22. # keep responses in sqlite because API has limit of requests
  23. # (free account has limit 100 requests/day)
  24. session = requests_cache.CachedSession('requests_stockdata', expire_after=timedelta(hours=1))
  25.  
  26. payload = {
  27.     'api_token': '<API KEY>',
  28.     'symbols': 'NVDA',         # `symbols` with char `s` - even if you send only one symbol
  29.     'intervals': 'minute',     # allowed `minute` and `hour` but not `1m`
  30. }
  31.  
  32. url = 'https://api.stockdata.org/v1/data/intraday'
  33. #response = requests.get(url, params=payload)
  34. response = session.get(url, params=payload)
  35.  
  36. data = response.json()
  37. if 'message' in data:
  38.     print(data['message'])
  39.  
  40. if 'data' in data:
  41.     df = pd.DataFrame(data['data'])
  42.    
  43.     # convert dict in one column into seperate columns
  44.     data_as_colums = df['data'].apply(pd.Series)
  45.     df_without_data = df.drop(columns=['data'])
  46.     df = pd.concat([df_without_data, data_as_colums], axis=1)
  47.     print(df.head())    
  48.    
  49.     df.to_csv('NVDA_minute_data.csv', index=False)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement