Skip to content

Commit

Permalink
Add stocks demo scripts (#377)
Browse files Browse the repository at this point in the history
* added demo scripts
  • Loading branch information
justinpolygon authored Feb 13, 2023
1 parent e1ae814 commit 4d8ab1c
Show file tree
Hide file tree
Showing 31 changed files with 700 additions and 0 deletions.
27 changes: 27 additions & 0 deletions examples/rest/stocks-aggregates_bars.py
Original file line number Diff line number Diff line change
@@ -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 "<your_api_key>" <- windows
# export POLYGON_API_KEY="<your_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)
78 changes: 78 additions & 0 deletions examples/rest/stocks-aggregates_bars_extra.py
Original file line number Diff line number Diff line change
@@ -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())
13 changes: 13 additions & 0 deletions examples/rest/stocks-conditions.py
Original file line number Diff line number Diff line change
@@ -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)
16 changes: 16 additions & 0 deletions examples/rest/stocks-daily_open_close.py
Original file line number Diff line number Diff line change
@@ -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)
13 changes: 13 additions & 0 deletions examples/rest/stocks-dividends.py
Original file line number Diff line number Diff line change
@@ -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)
27 changes: 27 additions & 0 deletions examples/rest/stocks-exchanges.py
Original file line number Diff line number Diff line change
@@ -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
)
)
20 changes: 20 additions & 0 deletions examples/rest/stocks-grouped_daily_bars.py
Original file line number Diff line number Diff line change
@@ -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)
14 changes: 14 additions & 0 deletions examples/rest/stocks-last_quote.py
Original file line number Diff line number Diff line change
@@ -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)
14 changes: 14 additions & 0 deletions examples/rest/stocks-last_trade.py
Original file line number Diff line number Diff line change
@@ -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)
22 changes: 22 additions & 0 deletions examples/rest/stocks-market_holidays.py
Original file line number Diff line number Diff line change
@@ -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))
11 changes: 11 additions & 0 deletions examples/rest/stocks-market_status.py
Original file line number Diff line number Diff line change
@@ -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)
14 changes: 14 additions & 0 deletions examples/rest/stocks-previous_close.py
Original file line number Diff line number Diff line change
@@ -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)
21 changes: 21 additions & 0 deletions examples/rest/stocks-quotes.py
Original file line number Diff line number Diff line change
@@ -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)
49 changes: 49 additions & 0 deletions examples/rest/stocks-snapshots_all.py
Original file line number Diff line number Diff line change
@@ -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,
)
)
43 changes: 43 additions & 0 deletions examples/rest/stocks-snapshots_gainers_losers.py
Original file line number Diff line number Diff line change
@@ -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))
Loading

0 comments on commit 4d8ab1c

Please sign in to comment.