From 4d8ab1c45da67a036e1460b1a25cb5158598a846 Mon Sep 17 00:00:00 2001 From: justinpolygon <123573436+justinpolygon@users.noreply.github.com> Date: Mon, 13 Feb 2023 07:55:04 -0800 Subject: [PATCH] Add stocks demo scripts (#377) * added demo scripts --- examples/rest/stocks-aggregates_bars.py | 27 ++++++ examples/rest/stocks-aggregates_bars_extra.py | 78 ++++++++++++++++++ examples/rest/stocks-conditions.py | 13 +++ examples/rest/stocks-daily_open_close.py | 16 ++++ examples/rest/stocks-dividends.py | 13 +++ examples/rest/stocks-exchanges.py | 27 ++++++ examples/rest/stocks-grouped_daily_bars.py | 20 +++++ examples/rest/stocks-last_quote.py | 14 ++++ examples/rest/stocks-last_trade.py | 14 ++++ examples/rest/stocks-market_holidays.py | 22 +++++ examples/rest/stocks-market_status.py | 11 +++ examples/rest/stocks-previous_close.py | 14 ++++ examples/rest/stocks-quotes.py | 21 +++++ examples/rest/stocks-snapshots_all.py | 49 +++++++++++ .../rest/stocks-snapshots_gainers_losers.py | 43 ++++++++++ examples/rest/stocks-snapshots_ticker.py | 11 +++ examples/rest/stocks-stock_financials.py | 13 +++ examples/rest/stocks-stock_splits.py | 13 +++ .../rest/stocks-technical_indicators_ema.py | 11 +++ .../rest/stocks-technical_indicators_macd.py | 11 +++ .../rest/stocks-technical_indicators_rsi.py | 11 +++ .../rest/stocks-technical_indicators_sma.py | 11 +++ examples/rest/stocks-ticker_details.py | 11 +++ examples/rest/stocks-ticker_events.py | 11 +++ examples/rest/stocks-ticker_news.py | 28 +++++++ examples/rest/stocks-ticker_types.py | 11 +++ examples/rest/stocks-tickers.py | 13 +++ examples/rest/stocks-trades.py | 21 +++++ examples/rest/stocks-trades_extra.py | 30 +++++++ examples/websocket/stocks-ws.py | 30 +++++++ examples/websocket/stocks-ws_extra.py | 82 +++++++++++++++++++ 31 files changed, 700 insertions(+) create mode 100644 examples/rest/stocks-aggregates_bars.py create mode 100644 examples/rest/stocks-aggregates_bars_extra.py create mode 100644 examples/rest/stocks-conditions.py create mode 100644 examples/rest/stocks-daily_open_close.py create mode 100644 examples/rest/stocks-dividends.py create mode 100644 examples/rest/stocks-exchanges.py create mode 100644 examples/rest/stocks-grouped_daily_bars.py create mode 100644 examples/rest/stocks-last_quote.py create mode 100644 examples/rest/stocks-last_trade.py create mode 100644 examples/rest/stocks-market_holidays.py create mode 100644 examples/rest/stocks-market_status.py create mode 100644 examples/rest/stocks-previous_close.py create mode 100644 examples/rest/stocks-quotes.py create mode 100644 examples/rest/stocks-snapshots_all.py create mode 100644 examples/rest/stocks-snapshots_gainers_losers.py create mode 100644 examples/rest/stocks-snapshots_ticker.py create mode 100644 examples/rest/stocks-stock_financials.py create mode 100644 examples/rest/stocks-stock_splits.py create mode 100644 examples/rest/stocks-technical_indicators_ema.py create mode 100644 examples/rest/stocks-technical_indicators_macd.py create mode 100644 examples/rest/stocks-technical_indicators_rsi.py create mode 100644 examples/rest/stocks-technical_indicators_sma.py create mode 100644 examples/rest/stocks-ticker_details.py create mode 100644 examples/rest/stocks-ticker_events.py create mode 100644 examples/rest/stocks-ticker_news.py create mode 100644 examples/rest/stocks-ticker_types.py create mode 100644 examples/rest/stocks-tickers.py create mode 100644 examples/rest/stocks-trades.py create mode 100644 examples/rest/stocks-trades_extra.py create mode 100644 examples/websocket/stocks-ws.py create mode 100644 examples/websocket/stocks-ws_extra.py diff --git a/examples/rest/stocks-aggregates_bars.py b/examples/rest/stocks-aggregates_bars.py new file mode 100644 index 00000000..9fb2625b --- /dev/null +++ b/examples/rest/stocks-aggregates_bars.py @@ -0,0 +1,27 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_v2_aggs_ticker__stocksticker__range__multiplier___timespan___from___to +# https://polygon-api-client.readthedocs.io/en/latest/Aggs.html#polygon.RESTClient.get_aggs + +# API key injected below for easy use. If not provided, the script will attempt +# to use the environment variable "POLYGON_API_KEY". +# +# setx POLYGON_API_KEY "" <- windows +# export POLYGON_API_KEY="" <- mac/linux +# +# Note: To persist the environment variable you need to add the above command +# to the shell startup script (e.g. .bashrc or .bash_profile. +# +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +aggs = client.get_aggs( + "AAPL", + 1, + "day", + "2023-01-30", + "2023-02-03", +) + +print(aggs) diff --git a/examples/rest/stocks-aggregates_bars_extra.py b/examples/rest/stocks-aggregates_bars_extra.py new file mode 100644 index 00000000..5936fdb3 --- /dev/null +++ b/examples/rest/stocks-aggregates_bars_extra.py @@ -0,0 +1,78 @@ +# This code retrieves stock market data for a specific stock using the +# Polygon REST API and writes it to a CSV file. It uses the "polygon" +# library to communicate with the API and the "csv" library to write +# the data to a CSV file. The script retrieves data for the stock "AAPL" +# for the dates "2023-01-30" to "2023-02-03" in 1 hour intervals. The +# resulting data includes the open, high, low, close, volume, vwap, +# timestamp, transactions, and otc values for each hour. The output is +# then printed to the console. +from polygon import RESTClient +from polygon.rest.models import ( + Agg, +) +import csv +import datetime +import io + +# docs +# https://polygon.io/docs/stocks/get_v2_aggs_ticker__stocksticker__range__multiplier___timespan___from___to +# https://polygon-api-client.readthedocs.io/en/latest/Aggs.html#polygon.RESTClient.get_aggs + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +aggs = client.get_aggs( + "AAPL", + 1, + "hour", + "2023-01-30", + "2023-02-03", +) + +print(aggs) + +# headers +headers = [ + "timestamp", + "open", + "high", + "low", + "close", + "volume", + "vwap", + "transactions", + "otc", +] + +# creating the csv string +csv_string = io.StringIO() +writer = csv.DictWriter(csv_string, fieldnames=headers) + +# writing headers +writer.writeheader() + +# 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): + + writer.writerow( + { + "timestamp": datetime.datetime.fromtimestamp(agg.timestamp / 1000), + "open": agg.open, + "high": agg.high, + "low": agg.low, + "close": agg.close, + "volume": agg.volume, + "vwap": agg.vwap, + "transactions": agg.transactions, + "otc": agg.otc, + } + ) + +# printing the csv string +print(csv_string.getvalue()) diff --git a/examples/rest/stocks-conditions.py b/examples/rest/stocks-conditions.py new file mode 100644 index 00000000..1be9b483 --- /dev/null +++ b/examples/rest/stocks-conditions.py @@ -0,0 +1,13 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_v3_reference_conditions +# https://polygon-api-client.readthedocs.io/en/latest/Reference.html#list-conditions + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +conditions = [] +for c in client.list_conditions(limit=1000): + conditions.append(c) +print(conditions) diff --git a/examples/rest/stocks-daily_open_close.py b/examples/rest/stocks-daily_open_close.py new file mode 100644 index 00000000..65c96265 --- /dev/null +++ b/examples/rest/stocks-daily_open_close.py @@ -0,0 +1,16 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_v1_open-close__stocksticker___date +# https://polygon-api-client.readthedocs.io/en/latest/Aggs.html#get-daily-open-close-agg + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +# make request +request = client.get_daily_open_close_agg( + "AAPL", + "2023-02-07", +) + +print(request) diff --git a/examples/rest/stocks-dividends.py b/examples/rest/stocks-dividends.py new file mode 100644 index 00000000..75cd795c --- /dev/null +++ b/examples/rest/stocks-dividends.py @@ -0,0 +1,13 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_v3_reference_dividends +# https://polygon-api-client.readthedocs.io/en/latest/Reference.html#list-dividends + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +dividends = [] +for d in client.list_dividends("MSFT", limit=1000): + dividends.append(d) +print(dividends) diff --git a/examples/rest/stocks-exchanges.py b/examples/rest/stocks-exchanges.py new file mode 100644 index 00000000..b65938e2 --- /dev/null +++ b/examples/rest/stocks-exchanges.py @@ -0,0 +1,27 @@ +from polygon import RESTClient +from polygon.rest.models import ( + Exchange, +) + +# docs +# https://polygon.io/docs/stocks/get_v3_reference_exchanges +# https://polygon-api-client.readthedocs.io/en/latest/Reference.html#get-exchanges + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +exchanges = client.get_exchanges() +print(exchanges) + +# loop over exchanges +for exchange in exchanges: + + # verify this is an exchange + if isinstance(exchange, Exchange): + + # print exchange info + print( + "{:<15}{} ({})".format( + exchange.asset_class, exchange.name, exchange.operating_mic + ) + ) diff --git a/examples/rest/stocks-grouped_daily_bars.py b/examples/rest/stocks-grouped_daily_bars.py new file mode 100644 index 00000000..8d9e92c5 --- /dev/null +++ b/examples/rest/stocks-grouped_daily_bars.py @@ -0,0 +1,20 @@ +from polygon import RESTClient +import pprint + +# docs +# https://polygon.io/docs/stocks/get_v2_aggs_grouped_locale_us_market_stocks__date +# https://polygon-api-client.readthedocs.io/en/latest/Aggs.html#get-grouped-daily-aggs + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +grouped = client.get_grouped_daily_aggs( + "2023-02-07", +) + +# print(grouped) + +# pprint (short for "pretty-print") is a module that provides a more human- +# readable output format for data structures. +pp = pprint.PrettyPrinter(indent=2) +pp.pprint(grouped) diff --git a/examples/rest/stocks-last_quote.py b/examples/rest/stocks-last_quote.py new file mode 100644 index 00000000..15b83e55 --- /dev/null +++ b/examples/rest/stocks-last_quote.py @@ -0,0 +1,14 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_v2_last_nbbo__stocksticker +# https://polygon-api-client.readthedocs.io/en/latest/Quotes.html#get-last-quote + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +quote = client.get_last_quote( + "AAPL", +) + +print(quote) diff --git a/examples/rest/stocks-last_trade.py b/examples/rest/stocks-last_trade.py new file mode 100644 index 00000000..42278ba0 --- /dev/null +++ b/examples/rest/stocks-last_trade.py @@ -0,0 +1,14 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_v2_last_trade__stocksticker +# https://polygon-api-client.readthedocs.io/en/latest/Trades.html#get-last-trade + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +trade = client.get_last_trade( + "AAPL", +) + +print(trade) diff --git a/examples/rest/stocks-market_holidays.py b/examples/rest/stocks-market_holidays.py new file mode 100644 index 00000000..bd39bd67 --- /dev/null +++ b/examples/rest/stocks-market_holidays.py @@ -0,0 +1,22 @@ +from polygon import RESTClient +from polygon.rest.models import ( + MarketHoliday, +) + +# docs +# https://polygon.io/docs/stocks/get_v1_marketstatus_upcoming +# https://polygon-api-client.readthedocs.io/en/latest/Reference.html#get-market-holidays + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +holidays = client.get_market_holidays() +# print(holidays) + +# print date, name, and exchange +for holiday in holidays: + + # verify this is an exchange + if isinstance(holiday, MarketHoliday): + + print("{:<15}{:<15} ({})".format(holiday.date, holiday.name, holiday.exchange)) diff --git a/examples/rest/stocks-market_status.py b/examples/rest/stocks-market_status.py new file mode 100644 index 00000000..bd4362b3 --- /dev/null +++ b/examples/rest/stocks-market_status.py @@ -0,0 +1,11 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_v1_marketstatus_now +# https://polygon-api-client.readthedocs.io/en/latest/Reference.html#get-market-status + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +result = client.get_market_status() +print(result) diff --git a/examples/rest/stocks-previous_close.py b/examples/rest/stocks-previous_close.py new file mode 100644 index 00000000..9785ab2e --- /dev/null +++ b/examples/rest/stocks-previous_close.py @@ -0,0 +1,14 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_v2_aggs_ticker__stocksticker__prev +# https://polygon-api-client.readthedocs.io/en/latest/Aggs.html#get-previous-close-agg + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +aggs = client.get_previous_close_agg( + "AAPL", +) + +print(aggs) diff --git a/examples/rest/stocks-quotes.py b/examples/rest/stocks-quotes.py new file mode 100644 index 00000000..4d615dab --- /dev/null +++ b/examples/rest/stocks-quotes.py @@ -0,0 +1,21 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_v3_quotes__stockticker +# https://polygon-api-client.readthedocs.io/en/latest/Quotes.html#list-quotes + +# NBBO (National Best Bid and Offer) is a term used in the financial industry +# to describe the best bid and offer prices for a particular stock or security +# being traded on all the available stock exchanges in the United States. It +# provides information on the highest price a buyer is willing to pay (best +# bid) and the lowest price a seller is willing to accept (best offer) for a +# particular security. This information is used by traders to make informed +# investment decisions and execute trades at the best available price. + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +quotes = [] +for t in client.list_quotes("IBIO", "2023-02-01", limit=50000): + quotes.append(t) +print(quotes) diff --git a/examples/rest/stocks-snapshots_all.py b/examples/rest/stocks-snapshots_all.py new file mode 100644 index 00000000..4f6e0157 --- /dev/null +++ b/examples/rest/stocks-snapshots_all.py @@ -0,0 +1,49 @@ +from polygon import RESTClient +from polygon.rest.models import ( + TickerSnapshot, + Agg, +) + +# docs +# https://polygon.io/docs/stocks/get_v2_snapshot_locale_us_markets_stocks_tickers +# https://polygon-api-client.readthedocs.io/en/latest/Snapshot.html#get-all-snapshots + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +# tickers we are interested in +tickers = ["TSLA", "AAPL", "MSFT", "META"] + +# snapshot = client.get_snapshot_all("stocks") # all tickers +snapshot = client.get_snapshot_all("stocks", tickers) + +# print raw values +print(snapshot) + +# crunch some numbers +for item in snapshot: + + # verify this is an TickerSnapshot + if isinstance(item, TickerSnapshot): + + # verify this is an Agg + if isinstance(item.prev_day, Agg): + + # verify this is a float + if isinstance(item.prev_day.open, float) and isinstance( + item.prev_day.close, float + ): + + percent_change = ( + (item.prev_day.close - item.prev_day.open) + / item.prev_day.open + * 100 + ) + print( + "{:<15}{:<15}{:<15}{:.2f} %".format( + item.ticker, + item.prev_day.open, + item.prev_day.close, + percent_change, + ) + ) diff --git a/examples/rest/stocks-snapshots_gainers_losers.py b/examples/rest/stocks-snapshots_gainers_losers.py new file mode 100644 index 00000000..b0194bfa --- /dev/null +++ b/examples/rest/stocks-snapshots_gainers_losers.py @@ -0,0 +1,43 @@ +from polygon import RESTClient +from polygon.rest.models import ( + TickerSnapshot, +) + +# docs +# https://polygon.io/docs/stocks/get_v2_snapshot_locale_us_markets_stocks__direction +# https://polygon-api-client.readthedocs.io/en/latest/Snapshot.html#get-gainers-losers-snapshot + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +# get gainers +gainers = client.get_snapshot_direction("stocks", "gainers") +# print(gainers) + +# print ticker with % change +for gainer in gainers: + + # verify this is a TickerSnapshot + if isinstance(gainer, TickerSnapshot): + + # verify this is a float + if isinstance(gainer.todays_change_percent, float): + + print("{:<15}{:.2f} %".format(gainer.ticker, gainer.todays_change_percent)) + +print() + +# get losers +losers = client.get_snapshot_direction("stocks", "losers") +# print(losers) + +# print ticker with % change +for loser in losers: + + # verify this is a TickerSnapshot + if isinstance(loser, TickerSnapshot): + + # verify this is a float + if isinstance(loser.todays_change_percent, float): + + print("{:<15}{:.2f} %".format(loser.ticker, loser.todays_change_percent)) diff --git a/examples/rest/stocks-snapshots_ticker.py b/examples/rest/stocks-snapshots_ticker.py new file mode 100644 index 00000000..2b264338 --- /dev/null +++ b/examples/rest/stocks-snapshots_ticker.py @@ -0,0 +1,11 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_v2_snapshot_locale_us_markets_stocks_tickers__stocksticker +# https://polygon-api-client.readthedocs.io/en/latest/Snapshot.html#get-ticker-snapshot + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +ticker = client.get_snapshot_ticker("stocks", "AAPL") +print(ticker) diff --git a/examples/rest/stocks-stock_financials.py b/examples/rest/stocks-stock_financials.py new file mode 100644 index 00000000..dc356494 --- /dev/null +++ b/examples/rest/stocks-stock_financials.py @@ -0,0 +1,13 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_vx_reference_financials +# https://polygon-api-client.readthedocs.io/en/latest/vX.html#list-stock-financials + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +financials = [] +for f in client.vx.list_stock_financials("AAPL"): + financials.append(f) +print(financials) diff --git a/examples/rest/stocks-stock_splits.py b/examples/rest/stocks-stock_splits.py new file mode 100644 index 00000000..55980973 --- /dev/null +++ b/examples/rest/stocks-stock_splits.py @@ -0,0 +1,13 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_v3_reference_splits +# https://polygon-api-client.readthedocs.io/en/latest/Reference.html#list-splits + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +splits = [] +for s in client.list_splits("TSLA", limit=1000): + splits.append(s) +print(splits) diff --git a/examples/rest/stocks-technical_indicators_ema.py b/examples/rest/stocks-technical_indicators_ema.py new file mode 100644 index 00000000..0b87d48d --- /dev/null +++ b/examples/rest/stocks-technical_indicators_ema.py @@ -0,0 +1,11 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_v1_indicators_ema__stockticker +# https://github.com/polygon-io/client-python/blob/master/polygon/rest/indicators.py + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +ema = client.get_ema("AAPL") +print(ema) diff --git a/examples/rest/stocks-technical_indicators_macd.py b/examples/rest/stocks-technical_indicators_macd.py new file mode 100644 index 00000000..45221926 --- /dev/null +++ b/examples/rest/stocks-technical_indicators_macd.py @@ -0,0 +1,11 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_v1_indicators_macd__stockticker +# https://github.com/polygon-io/client-python/blob/master/polygon/rest/indicators.py + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +macd = client.get_macd("AAPL") +print(macd) diff --git a/examples/rest/stocks-technical_indicators_rsi.py b/examples/rest/stocks-technical_indicators_rsi.py new file mode 100644 index 00000000..4fd62d29 --- /dev/null +++ b/examples/rest/stocks-technical_indicators_rsi.py @@ -0,0 +1,11 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_v1_indicators_rsi__stockticker +# https://github.com/polygon-io/client-python/blob/master/polygon/rest/indicators.py + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +rsi = client.get_rsi("AAPL") +print(rsi) diff --git a/examples/rest/stocks-technical_indicators_sma.py b/examples/rest/stocks-technical_indicators_sma.py new file mode 100644 index 00000000..bfc0796f --- /dev/null +++ b/examples/rest/stocks-technical_indicators_sma.py @@ -0,0 +1,11 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_v1_indicators_sma__stockticker +# https://github.com/polygon-io/client-python/blob/master/polygon/rest/indicators.py + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +sma = client.get_sma("AAPL") +print(sma) diff --git a/examples/rest/stocks-ticker_details.py b/examples/rest/stocks-ticker_details.py new file mode 100644 index 00000000..5f81b4bc --- /dev/null +++ b/examples/rest/stocks-ticker_details.py @@ -0,0 +1,11 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_v3_reference_tickers__ticker +# https://polygon-api-client.readthedocs.io/en/latest/Reference.html#get-ticker-details + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +details = client.get_ticker_details("AAPL") +print(details) diff --git a/examples/rest/stocks-ticker_events.py b/examples/rest/stocks-ticker_events.py new file mode 100644 index 00000000..09b13432 --- /dev/null +++ b/examples/rest/stocks-ticker_events.py @@ -0,0 +1,11 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_vx_reference_tickers__id__events +# https://github.com/polygon-io/client-python/blob/master/polygon/rest/reference.py + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +events = client.get_ticker_events("META") +print(events) diff --git a/examples/rest/stocks-ticker_news.py b/examples/rest/stocks-ticker_news.py new file mode 100644 index 00000000..41e08653 --- /dev/null +++ b/examples/rest/stocks-ticker_news.py @@ -0,0 +1,28 @@ +from polygon import RESTClient +from polygon.rest.models import ( + TickerNews, +) + +# docs +# https://polygon.io/docs/stocks/get_v2_reference_news +# https://polygon-api-client.readthedocs.io/en/latest/Reference.html#list-ticker-news + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +news = [] +for n in client.list_ticker_news("BBBY", order="desc", limit=1000): + news.append(n) + +# print(news) + +# print date + title +for index, item in enumerate(news): + + # verify this is an agg + if isinstance(item, TickerNews): + + print("{:<25}{:<15}".format(item.published_utc, item.title)) + + if index == 20: + break diff --git a/examples/rest/stocks-ticker_types.py b/examples/rest/stocks-ticker_types.py new file mode 100644 index 00000000..fa09338d --- /dev/null +++ b/examples/rest/stocks-ticker_types.py @@ -0,0 +1,11 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_v3_reference_tickers_types +# https://polygon-api-client.readthedocs.io/en/latest/Reference.html#get-ticker-types + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +types = client.get_ticker_types() +print(types) diff --git a/examples/rest/stocks-tickers.py b/examples/rest/stocks-tickers.py new file mode 100644 index 00000000..bffd518e --- /dev/null +++ b/examples/rest/stocks-tickers.py @@ -0,0 +1,13 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_v3_reference_tickers +# https://polygon-api-client.readthedocs.io/en/latest/Reference.html#list-tickers + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +tickers = [] +for t in client.list_tickers(limit=1000): + tickers.append(t) +print(tickers) diff --git a/examples/rest/stocks-trades.py b/examples/rest/stocks-trades.py new file mode 100644 index 00000000..8f2f147b --- /dev/null +++ b/examples/rest/stocks-trades.py @@ -0,0 +1,21 @@ +from polygon import RESTClient + +# docs +# https://polygon.io/docs/stocks/get_v3_trades__stockticker +# https://polygon-api-client.readthedocs.io/en/latest/Trades.html#polygon.RESTClient.list_trades + +# Trade data refers to the tick records of individual transactions that have +# taken place in a financial market, such as the price, size, and time of +# each trade. It provides a high-frequency, granular view of market activity, +# and is used by traders, investors, and researchers to gain insights into +# market behavior and inform their investment decisions. + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +trades = [] +for t in client.list_trades("IBIO", "2023-02-01", limit=50000): + trades.append(t) + +# prints each trade that took place +print(trades) diff --git a/examples/rest/stocks-trades_extra.py b/examples/rest/stocks-trades_extra.py new file mode 100644 index 00000000..1015f22a --- /dev/null +++ b/examples/rest/stocks-trades_extra.py @@ -0,0 +1,30 @@ +# This code retrieves trade records and counts the amount of money that changes hands. +from polygon import RESTClient +from polygon.rest.models import ( + Trade, +) + +# docs +# https://polygon.io/docs/stocks/get_v3_trades__stockticker +# https://polygon-api-client.readthedocs.io/en/latest/Trades.html#polygon.RESTClient.list_trades + +# client = RESTClient("XXXXXX") # hardcoded api_key is used +client = RESTClient() # POLYGON_API_KEY environment variable is used + +# used to track money across trades +money = float(0) + +# loop through and count price * volume +for t in client.list_trades("DIS", "2023-02-07", limit=50000): + + # verify this is an Trade + if isinstance(t, Trade): + + # verify these are float + if isinstance(t.price, float) and isinstance(t.size, float): + + money += t.price * t.size + +# format the number so it's human readable +formatted_number = "{:,.2f}".format(money) +print("Roughly " + formatted_number + " changed hands for DIS on 2023-02-07.") diff --git a/examples/websocket/stocks-ws.py b/examples/websocket/stocks-ws.py new file mode 100644 index 00000000..98064ece --- /dev/null +++ b/examples/websocket/stocks-ws.py @@ -0,0 +1,30 @@ +from polygon import WebSocketClient +from polygon.websocket.models import WebSocketMessage +from typing import List + +client = WebSocketClient("N_4QqOFs3X_pCHeIJjW4pCETSOBerS4_") # api_key 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) + +# 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 handle_msg(msgs: List[WebSocketMessage]): + for m in msgs: + print(m) + + +# print messages +client.run(handle_msg) diff --git a/examples/websocket/stocks-ws_extra.py b/examples/websocket/stocks-ws_extra.py new file mode 100644 index 00000000..59883e6c --- /dev/null +++ b/examples/websocket/stocks-ws_extra.py @@ -0,0 +1,82 @@ +from polygon import WebSocketClient +from polygon.websocket.models import WebSocketMessage +from typing import List +from typing import Dict +import time +import threading + + +# docs +# https://polygon.io/docs/stocks/ws_stocks_am +# https://polygon-api-client.readthedocs.io/en/latest/WebSocket.html# + +# This program connects to the Polygon WebSocket API, authenticates the +# connection, and subscribes to receive trades. Every 5 seconds, it counts +# the number of trades per symbol and stores the results in a map. The +# 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 + client = WebSocketClient() # POLYGON_API_KEY environment variable is used + client.subscribe("T.*") # all trades + client.run(handle_msg) + + +string_map: Dict[str, int] +string_map = {} # + + +def handle_msg(msgs: List[WebSocketMessage]): + for m in msgs: + # print(m) + + # verify this is a string + if isinstance(m, str): + + if m.symbol in string_map: + string_map[m.symbol] += 1 + else: + string_map[m.symbol] = 1 + + +# print messages +# client.run(handle_msg) + + +def top_function(): + 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]: + print("{:<15}{:<15}".format(index, item)) + string_map.clear() # clear map for next loop + + +def run_function_periodically(): + while True: + top_function() + time.sleep(5) + + +thread1 = threading.Thread(target=run_function_periodically) +thread2 = threading.Thread(target=run_websocket_client) + +thread1.start() +thread2.start() + +thread1.join() +thread2.join()