Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
137 changes: 137 additions & 0 deletions examples/rest/stocks-aggregates_bars_highcharts.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
from polygon import RESTClient
from polygon.rest.models import (
Agg,
)
import datetime
import http.server
import socketserver
import traceback
import json

# This program retrieves stock price data for the AAPL stock from the Polygon
# API using a REST client, and formats the data in a format expected by the
# Highcharts JavaScript library. The program creates a web server that serves
# an HTML page that includes a candlestick chart of the AAPL stock prices using
# Highcharts. The chart displays data for the time range from January 1, 2019,
# to February 16, 2023. The chart data is updated by retrieving the latest data
# from the Polygon API every time the HTML page is loaded or refreshed. The
# server listens on port 8888 and exits gracefully when a KeyboardInterrupt is
# received.
#
# Connect to http://localhost:8888 in your browser to view candlestick chart.

PORT = 8888

# https://www.highcharts.com/blog/products/stock/
# JavaScript StockChart with Date-Time Axis
html = """
<!DOCTYPE HTML>
<html>
<head>

<style>
#container {
height: 750px;
min-width: 310px;
}
</style>

<script src="https://code.highcharts.com/stock/highstock.js"></script>
<script src="https://code.highcharts.com/stock/modules/data.js"></script>
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
<script src="https://code.highcharts.com/stock/modules/accessibility.js"></script>

<div id="container"></div>

<script type="text/javascript">
Highcharts.getJSON('/data', function (data) {

// create the chart
Highcharts.stockChart('container', {
rangeSelector: {
selected: 1
},

title: {
text: 'Stock Price'
},

series: [{
type: 'candlestick',
name: 'Stock Price',
data: data
}]
});
});
</script>
</head>
<body>
"""

client = RESTClient() # POLYGON_API_KEY environment variable is used

aggs = client.get_aggs(
"AAPL",
1,
"day",
"2019-01-01",
"2023-02-16",
limit=50000,
)

# print(aggs)

data = []

# writing data
for agg in aggs:

# verify this is an agg
if isinstance(agg, Agg):

# verify this is an int
if isinstance(agg.timestamp, int):

new_record = {
"date": agg.timestamp,
"open": agg.open,
"high": agg.high,
"low": agg.low,
"close": agg.close,
"volume": agg.volume,
}

data.append(new_record)

values = [[v for k, v in d.items()] for d in data]

# json_data = json.dumps(data)
# print(json_data)


class handler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
if self.path == "/data":
self.send_response(200)
self.send_header("Content-type", "application/json")
self.end_headers()
json_data = json.dumps(values)
self.wfile.write(json_data.encode())
else:
self.send_response(200)
self.send_header("Content-type", "text/html")
self.end_headers()
self.wfile.write(html.encode())


# handle ctrl-c KeyboardInterrupt to exit the program gracefully
try:
while True:
# run http server
with socketserver.TCPServer(("", PORT), handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
pass
except KeyboardInterrupt:
print("\nExiting gracefully...")
# traceback.print_exc()
2 changes: 1 addition & 1 deletion examples/rest/stocks-grouped_daily_bars.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
client = RESTClient() # POLYGON_API_KEY environment variable is used

grouped = client.get_grouped_daily_aggs(
"2023-02-07",
"2023-02-16",
)

# print(grouped)
Expand Down
2 changes: 1 addition & 1 deletion examples/rest/stocks-tickers.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,6 @@
client = RESTClient() # POLYGON_API_KEY environment variable is used

tickers = []
for t in client.list_tickers(limit=1000):
for t in client.list_tickers(market="stocks", type="CS", active=True, limit=1000):
tickers.append(t)
print(tickers)
2 changes: 1 addition & 1 deletion examples/rest/stocks-trades_extra.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
if isinstance(t, Trade):

# verify these are float
if isinstance(t.price, float) and isinstance(t.size, float):
if isinstance(t.price, float) and isinstance(t.size, int):

money += t.price * t.size

Expand Down
21 changes: 13 additions & 8 deletions examples/websocket/stocks-ws.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,23 +2,28 @@
from polygon.websocket.models import WebSocketMessage
from typing import List

client = WebSocketClient("N_4QqOFs3X_pCHeIJjW4pCETSOBerS4_") # api_key is used
# client = WebSocketClient("XXXXXX") # hardcoded api_key is used
client = WebSocketClient() # POLYGON_API_KEY environment variable is used

# docs
# https://polygon.io/docs/stocks/ws_stocks_am
# https://polygon-api-client.readthedocs.io/en/latest/WebSocket.html#

# aggregates
# client.subscribe("AM.*") # aggregates (per minute)
# client.subscribe("A.*") # aggregates (per second)
# aggregates (per minute)
# client.subscribe("AM.*") # all aggregates
# client.subscribe("AM.TSLA") # single ticker

# aggregates (per second)
client.subscribe("A.*") # all aggregates
# client.subscribe("A.TSLA") # single ticker

# trades
# client.subscribe("T.*") # all trades
# client.subscribe("T.TSLA", "T.UBER") # limited trades
# client.subscribe("T.*") # all trades
# client.subscribe("T.TSLA", "T.UBER") # multiple tickers

# quotes
# client.subscribe("Q.*") # all quotes
# client.subscribe("Q.TSLA", "Q.UBER") # limited quotes
# client.subscribe("Q.*") # all quotes
# client.subscribe("Q.TSLA", "Q.UBER") # multiple tickers


def handle_msg(msgs: List[WebSocketMessage]):
Expand Down
77 changes: 53 additions & 24 deletions examples/websocket/stocks-ws_extra.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
from polygon import WebSocketClient
from polygon.websocket.models import WebSocketMessage
from polygon.websocket.models import WebSocketMessage, EquityTrade
from typing import List
from typing import Dict
from datetime import datetime
import time
import threading


# docs
# https://polygon.io/docs/stocks/ws_stocks_am
# https://polygon-api-client.readthedocs.io/en/latest/WebSocket.html#
Expand All @@ -16,18 +16,6 @@
# program then prints the map, which gives a readout of the top stocks
# traded in the past 5 seconds.

# aggregates
# client.subscribe("AM.*") # aggregates (per minute)
# client.subscribe("A.*") # aggregates (per second)

# trades
# client.subscribe("T.*") # all trades
# client.subscribe("T.TSLA", "T.UBER") # limited trades

# quotes
# client.subscribe("Q.*") # all quotes
# client.subscribe("Q.TSLA", "Q.UBER") # limited quotes


def run_websocket_client():
# client = WebSocketClient("XXXXXX") # hardcoded api_key is used
Expand All @@ -38,32 +26,73 @@ def run_websocket_client():

string_map: Dict[str, int]
string_map = {} #
cash_traded = float(0)


def handle_msg(msgs: List[WebSocketMessage]):
for m in msgs:
# print(m)

# verify this is a string
if isinstance(m, str):
if type(m) == EquityTrade:

if m.symbol in string_map:
string_map[m.symbol] += 1
else:
string_map[m.symbol] = 1
# verify this is a string
if isinstance(m.symbol, str):

if m.symbol in string_map:
string_map[m.symbol] += 1
else:
string_map[m.symbol] = 1

# print messages
# client.run(handle_msg)
# verify these are float
if isinstance(m.price, float) and isinstance(m.size, int):

global cash_traded
cash_traded += m.price * m.size
# print(cash_traded)


def top_function():

# start timer
start_time = time.time()

sorted_string_map = sorted(string_map.items(), key=lambda x: x[1], reverse=True)
print("\033c", end="") # ANSI escape sequence to clear the screen

for index, item in sorted_string_map[:10]:
for index, item in sorted_string_map[:25]:
print("{:<15}{:<15}".format(index, item))
string_map.clear() # clear map for next loop

# end timer
end_time = time.time()

# print stats
print()

# current time
current_time = datetime.now()
print(f"Time: {current_time}")

# how many tickers seen
ticker_count = len(sorted_string_map)
print(f"Tickers seen: {ticker_count}")

# how many trades seen
trade_count = 0
for index, item in sorted_string_map:
trade_count += item
print(f"Trades seen: {trade_count}")

# cash traded
global cash_traded
formatted_number = "{:,.2f}".format(cash_traded)
print("Roughly " + formatted_number + " cash changed hands")

# performance?
print(f"Time taken: {end_time - start_time:.6f} seconds")

# clear map and cash for next loop
string_map.clear()
cash_traded = 0


def run_function_periodically():
Expand Down