diff --git a/examples/rest/stocks-aggregates_bars_highcharts.py b/examples/rest/stocks-aggregates_bars_highcharts.py new file mode 100644 index 00000000..08fccd4c --- /dev/null +++ b/examples/rest/stocks-aggregates_bars_highcharts.py @@ -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 = """ + + +
+ + + + + + + + + + + + + +""" + +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() diff --git a/examples/rest/stocks-grouped_daily_bars.py b/examples/rest/stocks-grouped_daily_bars.py index 8d9e92c5..ea0ff1cd 100644 --- a/examples/rest/stocks-grouped_daily_bars.py +++ b/examples/rest/stocks-grouped_daily_bars.py @@ -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) diff --git a/examples/rest/stocks-tickers.py b/examples/rest/stocks-tickers.py index bffd518e..7fc09230 100644 --- a/examples/rest/stocks-tickers.py +++ b/examples/rest/stocks-tickers.py @@ -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) diff --git a/examples/rest/stocks-trades_extra.py b/examples/rest/stocks-trades_extra.py index 1015f22a..61bc6b7d 100644 --- a/examples/rest/stocks-trades_extra.py +++ b/examples/rest/stocks-trades_extra.py @@ -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 diff --git a/examples/websocket/stocks-ws.py b/examples/websocket/stocks-ws.py index 98064ece..cf238953 100644 --- a/examples/websocket/stocks-ws.py +++ b/examples/websocket/stocks-ws.py @@ -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]): diff --git a/examples/websocket/stocks-ws_extra.py b/examples/websocket/stocks-ws_extra.py index 59883e6c..0fdd6bd8 100644 --- a/examples/websocket/stocks-ws_extra.py +++ b/examples/websocket/stocks-ws_extra.py @@ -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# @@ -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 @@ -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():