Skip to content

Commit

Permalink
Create Polygon-API-Connector
Browse files Browse the repository at this point in the history
  • Loading branch information
hollowheights authored Jan 13, 2022
1 parent dc0a54b commit cf97c1c
Showing 1 changed file with 84 additions and 0 deletions.
84 changes: 84 additions & 0 deletions Polygon-API-Connector
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import requests
import pandas as pd
import datetime
import pytz
api = '' #INSERT API HERE


def tickerlistcreator():
storagelist = []
status = 1
totalpages = 1

#Set URL for the initial request
url = 'https://api.polygon.io/v3/reference/tickers?type=CS&market=stocks&active=true&sort=ticker&order=asc&limit=1000' + api

while status == 1:
response = requests.get(url)

for item in response.json()['results']:
storagelist.append(item['ticker'])

if "next_url" in response.json():
url = response.json()['next_url'] + api
totalpages += 1
else:
status = 0

print('total pages of symbols: ', totalpages)
return(storagelist)


def stockdownloader(stock, startdate, enddate):
url = ('https://api.polygon.io/v2/aggs/ticker/%s/range/1/day/%s/%s?adjusted=true&sort=asc&limit=1000' %(stock,startdate,enddate)) + api

status = 1
totalpages = 1
json_list = []

while status == 1:
response = requests.get(url)
ticker = response.json()['ticker']

try:
for item in response.json()['results']:
date = datetime.datetime.fromtimestamp(item['t']/1000, tz= pytz.timezone('America/New_York')).date()

response2 = requests.get('https://api.polygon.io/vX/reference/tickers/%s?date=%s&apiKey=p7YmJp6VUZkyk1dfsv7DVbs5yyDloGdU' %(stock,date) )
marketcap = response2.json()['results']['market_cap']

json_element = {
'date': date,
'open': item['o'],
'high': item['h'],
'low': item['l'],
'close': item['c'],
'marketcap': marketcap }

json_list.append(json_element)
except:
print("Error with stock:", stock)


if "next_url" in response.json():
url = response.json()['next_url'] + api
totalpages += 1
else:
status = 0

df = pd.DataFrame(json_list)
print(df)
print('total pages of stock data: ', totalpages)


#------- RUNNING FUNCTIONS -------

#Define test universe
tickerlist = tickerlistcreator()

print("First 10 tickers: ", tickerlist[0:10])
print("Total number of tickers is: ", len(tickerlist))

#Download data - the main function - set currently to just use the first ticker
for stock in tickerlist[0:1]:
stockdownloader(stock, '2021-01-01','2021-12-31')

0 comments on commit cf97c1c

Please sign in to comment.