Skip to content

Commit a09584a

Browse files
add/update examples (#383)
* add/update examples * added comment to on how to use
1 parent 29ecabc commit a09584a

File tree

6 files changed

+206
-35
lines changed

6 files changed

+206
-35
lines changed
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
from polygon import RESTClient
2+
from polygon.rest.models import (
3+
Agg,
4+
)
5+
import datetime
6+
import http.server
7+
import socketserver
8+
import traceback
9+
import json
10+
11+
# This program retrieves stock price data for the AAPL stock from the Polygon
12+
# API using a REST client, and formats the data in a format expected by the
13+
# Highcharts JavaScript library. The program creates a web server that serves
14+
# an HTML page that includes a candlestick chart of the AAPL stock prices using
15+
# Highcharts. The chart displays data for the time range from January 1, 2019,
16+
# to February 16, 2023. The chart data is updated by retrieving the latest data
17+
# from the Polygon API every time the HTML page is loaded or refreshed. The
18+
# server listens on port 8888 and exits gracefully when a KeyboardInterrupt is
19+
# received.
20+
#
21+
# Connect to http://localhost:8888 in your browser to view candlestick chart.
22+
23+
PORT = 8888
24+
25+
# https://www.highcharts.com/blog/products/stock/
26+
# JavaScript StockChart with Date-Time Axis
27+
html = """
28+
<!DOCTYPE HTML>
29+
<html>
30+
<head>
31+
32+
<style>
33+
#container {
34+
height: 750px;
35+
min-width: 310px;
36+
}
37+
</style>
38+
39+
<script src="https://code.highcharts.com/stock/highstock.js"></script>
40+
<script src="https://code.highcharts.com/stock/modules/data.js"></script>
41+
<script src="https://code.highcharts.com/stock/modules/exporting.js"></script>
42+
<script src="https://code.highcharts.com/stock/modules/accessibility.js"></script>
43+
44+
<div id="container"></div>
45+
46+
<script type="text/javascript">
47+
Highcharts.getJSON('/data', function (data) {
48+
49+
// create the chart
50+
Highcharts.stockChart('container', {
51+
rangeSelector: {
52+
selected: 1
53+
},
54+
55+
title: {
56+
text: 'Stock Price'
57+
},
58+
59+
series: [{
60+
type: 'candlestick',
61+
name: 'Stock Price',
62+
data: data
63+
}]
64+
});
65+
});
66+
</script>
67+
</head>
68+
<body>
69+
"""
70+
71+
client = RESTClient() # POLYGON_API_KEY environment variable is used
72+
73+
aggs = client.get_aggs(
74+
"AAPL",
75+
1,
76+
"day",
77+
"2019-01-01",
78+
"2023-02-16",
79+
limit=50000,
80+
)
81+
82+
# print(aggs)
83+
84+
data = []
85+
86+
# writing data
87+
for agg in aggs:
88+
89+
# verify this is an agg
90+
if isinstance(agg, Agg):
91+
92+
# verify this is an int
93+
if isinstance(agg.timestamp, int):
94+
95+
new_record = {
96+
"date": agg.timestamp,
97+
"open": agg.open,
98+
"high": agg.high,
99+
"low": agg.low,
100+
"close": agg.close,
101+
"volume": agg.volume,
102+
}
103+
104+
data.append(new_record)
105+
106+
values = [[v for k, v in d.items()] for d in data]
107+
108+
# json_data = json.dumps(data)
109+
# print(json_data)
110+
111+
112+
class handler(http.server.SimpleHTTPRequestHandler):
113+
def do_GET(self):
114+
if self.path == "/data":
115+
self.send_response(200)
116+
self.send_header("Content-type", "application/json")
117+
self.end_headers()
118+
json_data = json.dumps(values)
119+
self.wfile.write(json_data.encode())
120+
else:
121+
self.send_response(200)
122+
self.send_header("Content-type", "text/html")
123+
self.end_headers()
124+
self.wfile.write(html.encode())
125+
126+
127+
# handle ctrl-c KeyboardInterrupt to exit the program gracefully
128+
try:
129+
while True:
130+
# run http server
131+
with socketserver.TCPServer(("", PORT), handler) as httpd:
132+
print("serving at port", PORT)
133+
httpd.serve_forever()
134+
pass
135+
except KeyboardInterrupt:
136+
print("\nExiting gracefully...")
137+
# traceback.print_exc()

examples/rest/stocks-grouped_daily_bars.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
client = RESTClient() # POLYGON_API_KEY environment variable is used
1010

1111
grouped = client.get_grouped_daily_aggs(
12-
"2023-02-07",
12+
"2023-02-16",
1313
)
1414

1515
# print(grouped)

examples/rest/stocks-tickers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,6 @@
88
client = RESTClient() # POLYGON_API_KEY environment variable is used
99

1010
tickers = []
11-
for t in client.list_tickers(limit=1000):
11+
for t in client.list_tickers(market="stocks", type="CS", active=True, limit=1000):
1212
tickers.append(t)
1313
print(tickers)

examples/rest/stocks-trades_extra.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
if isinstance(t, Trade):
2222

2323
# verify these are float
24-
if isinstance(t.price, float) and isinstance(t.size, float):
24+
if isinstance(t.price, float) and isinstance(t.size, int):
2525

2626
money += t.price * t.size
2727

examples/websocket/stocks-ws.py

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,23 +2,28 @@
22
from polygon.websocket.models import WebSocketMessage
33
from typing import List
44

5-
client = WebSocketClient("N_4QqOFs3X_pCHeIJjW4pCETSOBerS4_") # api_key is used
5+
# client = WebSocketClient("XXXXXX") # hardcoded api_key is used
6+
client = WebSocketClient() # POLYGON_API_KEY environment variable is used
67

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

11-
# aggregates
12-
# client.subscribe("AM.*") # aggregates (per minute)
13-
# client.subscribe("A.*") # aggregates (per second)
12+
# aggregates (per minute)
13+
# client.subscribe("AM.*") # all aggregates
14+
# client.subscribe("AM.TSLA") # single ticker
15+
16+
# aggregates (per second)
17+
client.subscribe("A.*") # all aggregates
18+
# client.subscribe("A.TSLA") # single ticker
1419

1520
# trades
16-
# client.subscribe("T.*") # all trades
17-
# client.subscribe("T.TSLA", "T.UBER") # limited trades
21+
# client.subscribe("T.*") # all trades
22+
# client.subscribe("T.TSLA", "T.UBER") # multiple tickers
1823

1924
# quotes
20-
# client.subscribe("Q.*") # all quotes
21-
# client.subscribe("Q.TSLA", "Q.UBER") # limited quotes
25+
# client.subscribe("Q.*") # all quotes
26+
# client.subscribe("Q.TSLA", "Q.UBER") # multiple tickers
2227

2328

2429
def handle_msg(msgs: List[WebSocketMessage]):

examples/websocket/stocks-ws_extra.py

Lines changed: 53 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
11
from polygon import WebSocketClient
2-
from polygon.websocket.models import WebSocketMessage
2+
from polygon.websocket.models import WebSocketMessage, EquityTrade
33
from typing import List
44
from typing import Dict
5+
from datetime import datetime
56
import time
67
import threading
78

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

19-
# aggregates
20-
# client.subscribe("AM.*") # aggregates (per minute)
21-
# client.subscribe("A.*") # aggregates (per second)
22-
23-
# trades
24-
# client.subscribe("T.*") # all trades
25-
# client.subscribe("T.TSLA", "T.UBER") # limited trades
26-
27-
# quotes
28-
# client.subscribe("Q.*") # all quotes
29-
# client.subscribe("Q.TSLA", "Q.UBER") # limited quotes
30-
3119

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

3927
string_map: Dict[str, int]
4028
string_map = {} #
29+
cash_traded = float(0)
4130

4231

4332
def handle_msg(msgs: List[WebSocketMessage]):
4433
for m in msgs:
4534
# print(m)
4635

47-
# verify this is a string
48-
if isinstance(m, str):
36+
if type(m) == EquityTrade:
4937

50-
if m.symbol in string_map:
51-
string_map[m.symbol] += 1
52-
else:
53-
string_map[m.symbol] = 1
38+
# verify this is a string
39+
if isinstance(m.symbol, str):
5440

41+
if m.symbol in string_map:
42+
string_map[m.symbol] += 1
43+
else:
44+
string_map[m.symbol] = 1
5545

56-
# print messages
57-
# client.run(handle_msg)
46+
# verify these are float
47+
if isinstance(m.price, float) and isinstance(m.size, int):
48+
49+
global cash_traded
50+
cash_traded += m.price * m.size
51+
# print(cash_traded)
5852

5953

6054
def top_function():
55+
56+
# start timer
57+
start_time = time.time()
58+
6159
sorted_string_map = sorted(string_map.items(), key=lambda x: x[1], reverse=True)
6260
print("\033c", end="") # ANSI escape sequence to clear the screen
6361

64-
for index, item in sorted_string_map[:10]:
62+
for index, item in sorted_string_map[:25]:
6563
print("{:<15}{:<15}".format(index, item))
66-
string_map.clear() # clear map for next loop
64+
65+
# end timer
66+
end_time = time.time()
67+
68+
# print stats
69+
print()
70+
71+
# current time
72+
current_time = datetime.now()
73+
print(f"Time: {current_time}")
74+
75+
# how many tickers seen
76+
ticker_count = len(sorted_string_map)
77+
print(f"Tickers seen: {ticker_count}")
78+
79+
# how many trades seen
80+
trade_count = 0
81+
for index, item in sorted_string_map:
82+
trade_count += item
83+
print(f"Trades seen: {trade_count}")
84+
85+
# cash traded
86+
global cash_traded
87+
formatted_number = "{:,.2f}".format(cash_traded)
88+
print("Roughly " + formatted_number + " cash changed hands")
89+
90+
# performance?
91+
print(f"Time taken: {end_time - start_time:.6f} seconds")
92+
93+
# clear map and cash for next loop
94+
string_map.clear()
95+
cash_traded = 0
6796

6897

6998
def run_function_periodically():

0 commit comments

Comments
 (0)