Skip to content

Instantly share code, notes, and snippets.

@rruntsch
Last active May 23, 2023 21:35
Show Gist options
  • Save rruntsch/374d7be0758724fe1c7b010195fc55f3 to your computer and use it in GitHub Desktop.
Save rruntsch/374d7be0758724fe1c7b010195fc55f3 to your computer and use it in GitHub Desktop.
Example Python code to get real time stock quotes and end of day (EOD) historical stock price data from StockData.org APIs.
# Author: Randy Runtsch
# Date: May 23, 2023
# Title: get_stock_data.py
# Description: Create and instance of class c_stock and call its
# get_eod_stock_date function to obtain daily closing prices
# and get_real_time_stock_quotes to obtain the latest price quote.
from c_stock import c_stock
from api_secrets import api_token
# Get end of day and real time quote data for the AAPL stock.
# Instantiate c_stock.
stock = c_stock(api_token, 'AAPL', '2022-05-24', '2023-05-23')
# Get end of day closing prices and write them to a JSON file.
stock.get_eod_stock_data('c:\\stock_data\\eod.json', 'JSON')
# Get the real time quote data and write them to a JSON file.
stock.get_real_time_stock_quote('c:\\stock_data\\rtq.json')
# Author: Randy Runtsch
# Date: May 23, 2023
# Title: c_stock.py
# Description: Implementation of class c_stock that obtains stock data with the
# StockData.org end of day (eod) and quote API endpoints. Each function
# writes the data to the specified file.
import http.client, urllib.parse
class c_stock:
def __init__(self, api_token, symbol, date_from, date_to):
# Set base URL, API token, stock symbols, and date range.
self.conn = http.client.HTTPSConnection('api.stockdata.org')
self.api_token = api_token
self.symbol = symbol
self.date_from = date_from
self.date_to = date_to
def get_eod_stock_data(self, out_file_name, format):
# Get end of day stock values.
# Set the URL parameters. Note that the parameter "format"
# is set to "JSON" or "CSV" to write the file in that format.
params = urllib.parse.urlencode({
'api_token': self.api_token,
'symbols': self. Symbol,
'date_from': self.date_from,
'date_to': self.date_to,
'format': format
})
# Make the request, get the response, and read the data.
self.conn.request('GET', '/v1/data/eod?{}'.format(params))
resp = self.conn.getresponse()
data = resp.read()
# Write data to the specified file.
fl = open(out_file_name, 'w')
fl.write(data.decode('ascii'))
fl.close()
def get_real_time_stock_quote(self, out_file_name):
# Get the current quote for the selected stock.
# Set the URL parameters.
params = urllib.parse.urlencode({
'api_token': self.api_token,
'symbols': self.symbol
})
# Make the request, get the response, and read the data.
self.conn.request('GET', '/v1/data/quote?{}'.format(params))
resp = self.conn.getresponse()
data = resp.read()
# Write data to the specified file.
fl = open(out_file_name, 'w')
fl.write(data.decode('ascii'))
fl.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment