Skip to content

Commit 63aba0e

Browse files
author
clickingbuttons
authored
move examples to example dir (#167)
* move examples to example dir * update readme * update readme (2)
1 parent a465ba5 commit 63aba0e

File tree

14 files changed

+226
-397
lines changed

14 files changed

+226
-397
lines changed

README.md

Lines changed: 4 additions & 115 deletions
Original file line numberDiff line numberDiff line change
@@ -9,119 +9,8 @@ Python client for the [Polygon.io API](https://polygon.io).
99

1010
`pip install polygon-api-client`
1111

12-
Requires python version >= 3.7
12+
Requires Python >= 3.7.
1313

14-
## REST getting started
15-
### Getting aggs
16-
```python
17-
from polygon import RESTClient
18-
19-
client = RESTClient() # Uses POLYGON_API_KEY env var. Can optionally supply your key.
20-
aggs = client.get_aggs("AAPL", 1, "day", "2005-04-01", "2005-04-04")
21-
```
22-
23-
### Getting trades
24-
```python
25-
from polygon import RESTClient
26-
from polygon.rest.models import Sort
27-
28-
client = RESTClient() # Uses POLYGON_API_KEY env var. Can optionally supply your key.
29-
30-
trades = []
31-
for t in client.list_trades("AAA", timestamp="2022-04-20", limit=5, sort=Sort.ASC):
32-
trades.append(t)
33-
```
34-
35-
### Getting raw response
36-
To handle the raw [urllib3 response](https://urllib3.readthedocs.io/en/stable/reference/urllib3.response.html?highlight=response#response) yourself, pass `raw=True`:
37-
38-
```python
39-
from polygon import RESTClient
40-
41-
client = RESTClient() # Uses POLYGON_API_KEY env var. Can optionally supply your key.
42-
response = client.get_aggs("AAPL", 1, "day", "2005-04-01", "2005-04-04", raw=True)
43-
```
44-
45-
## WebSocket getting started
46-
47-
### Simple synchronous callback
48-
```python
49-
from polygon import WebSocketClient
50-
from polygon.websocket.models import WebSocketMessage
51-
from typing import List
52-
53-
c = WebSocketClient(subscriptions=['T.AAPL']) # Uses POLYGON_API_KEY env var. Can optionally supply your key.
54-
55-
def handle_msg(msgs: List[WebSocketMessage]):
56-
for m in msgs:
57-
print(m)
58-
59-
c.run(handle_msg)
60-
```
61-
62-
### Synchronous aggregates
63-
```python
64-
from polygon import WebSocketClient
65-
from polygon.websocket.models import WebSocketMessage
66-
from typing import List
67-
68-
class MessageHandler:
69-
count = 0
70-
71-
def handle_msg(self, msgs: List[WebSocketMessage]):
72-
for m in msgs:
73-
if type(m) == EquityTrade:
74-
print(self.count, m)
75-
self.count += 1
76-
77-
h = MessageHandler()
78-
79-
def handle_msg(msgs: List[WebSocketMessage]):
80-
h.handle_msg(msgs)
81-
82-
c.run(handle_msg)
83-
```
84-
85-
### Asynchronous callback
86-
```python
87-
from polygon import WebSocketClient
88-
from polygon.websocket.models import WebSocketMessage
89-
from typing import List
90-
91-
c = WebSocketClient(subscriptions=['T.AAPL']) # Uses POLYGON_API_KEY env var. Can optionally supply your key.
92-
93-
async def handle_msg(msgs: List[WebSocketMessage]):
94-
for m in msgs:
95-
print(m)
96-
97-
async def timeout():
98-
await asyncio.sleep(1)
99-
print('unsubscribe_all')
100-
c.unsubscribe_all()
101-
await asyncio.sleep(1)
102-
print('close')
103-
await c.close()
104-
105-
async def main():
106-
await asyncio.gather(
107-
c.connect(handle_msg),
108-
timeout()
109-
)
110-
111-
asyncio.run(main())
112-
```
113-
114-
### Getting raw response
115-
```python
116-
from polygon import WebSocketClient
117-
from polygon.websocket.models import WebSocketMessage
118-
from typing import Union
119-
import json
120-
121-
c = WebSocketClient(subscriptions=['T.*'], raw=True)
122-
123-
def handle_msg(msgs: Union[str, bytes]):
124-
print(json.loads(msgs))
125-
126-
c.run(handle_msg)
127-
```
14+
## Getting started
15+
See the [Getting Started](https://polygon-api-client.readthedocs.io/en/latest/Getting-Started.html)
16+
section in our docs or view the [examples](./examples) directory.

docs/source/Getting-Started.rst

Lines changed: 10 additions & 202 deletions
Original file line numberDiff line numberDiff line change
@@ -26,19 +26,11 @@ You can pass your API key via the environment variable :code:`POLYGON_API_KEY` o
2626
2727
For non-paginated endpoints call :code:`get_*`:
2828

29-
.. code-block:: python
30-
31-
aggs = client.get_aggs("AAPL", 1, "day", "2022-04-01", "2022-04-04")
32-
print(aggs)
29+
.. literalinclude:: ../../examples/rest/simple-get.py
3330

3431
For paginated endpoints call :code:`list_*` and use the provided iterator:
3532

36-
.. code-block:: python
37-
38-
trades = []
39-
for t in client.list_trades("AAA", timestamp="2022-04-20", limit=5, sort=Sort.ASC)
40-
trades.append(t)
41-
print(trades)
33+
.. literalinclude:: ../../examples/rest/simple-list.py
4234

4335
.. note::
4436
The number of network requests made by the iterator depends on the value of the parameter :code:`limit`.
@@ -55,125 +47,11 @@ For endpoints that have a set of parameters you can use the provided :doc:`enums
5547
5648
To handle the raw `urllib3 response <https://urllib3.readthedocs.io/en/stable/reference/urllib3.response.html?highlight=response#response) yourself, pass `raw=True>`_ yourself pass :code:`raw=True`:
5749

58-
.. code-block:: python
59-
60-
aggs = client.get_aggs("AAPL", 1, "day", "2022-04-01", "2022-04-04", raw=True)
61-
print(aggs.geturl())
62-
# https://api.polygon.io/v2/aggs/ticker/AAPL/range/1/day/2022-04-01/2022-04-04
63-
print(aggs.status)
64-
# 200
65-
print(aggs.data)
66-
# b'{
67-
# "ticker": "AAPL",
68-
# "queryCount": 2,
69-
# "resultsCount": 2,
70-
# "adjusted": true,
71-
# "results": [
72-
# {
73-
# "v": 78251328,
74-
# "vw": 173.4143,
75-
# "o": 174.03,
76-
# "c": 174.31,
77-
# "h": 174.88,
78-
# "l": 171.94,
79-
# "t": 1648785600000,
80-
# "n": 661160
81-
# },
82-
# {
83-
# "v": 76545983,
84-
# "vw": 177.4855,
85-
# "o": 174.57,
86-
# "c": 178.44,
87-
# "h": 178.49,
88-
# "l": 174.44,
89-
# "t": 1649044800000,
90-
# "n": 630374
91-
# }
92-
# ],
93-
# "status": "OK",
94-
# "request_id": "d8882a9d5194978819777f49c44b09c6",
95-
# "count": 2
96-
# }'
50+
.. literalinclude:: ../../examples/rest/raw-get.py
9751

9852
If it is a paginated :code:`list_*` response it's up to you to handle the "next_url" iteration:
9953

100-
.. code-block:: python
101-
102-
trades = client.list_trades("AAA", timestamp="2022-04-20", limit=5)
103-
print(aggs.data)
104-
# b'{
105-
# "results": [
106-
# {
107-
# "conditions": [
108-
# 15
109-
# ],
110-
# "exchange": 11,
111-
# "id": "52983575627601",
112-
# "participant_timestamp": 1650499200029279200,
113-
# "price": 24.875,
114-
# "sequence_number": 1591291,
115-
# "sip_timestamp": 1650499200029316600,
116-
# "size": 100,
117-
# "tape": 1
118-
# },
119-
# {
120-
# "conditions": [
121-
# 38,
122-
# 41
123-
# ],
124-
# "exchange": 11,
125-
# "id": "52983575627600",
126-
# "participant_timestamp": 1650499200029279200,
127-
# "price": 24.875,
128-
# "sequence_number": 1591290,
129-
# "sip_timestamp": 1650499200029316600,
130-
# "tape": 1
131-
# },
132-
# {
133-
# "conditions": [
134-
# 15
135-
# ],
136-
# "exchange": 11,
137-
# "id": "52983575622470",
138-
# "participant_timestamp": 1650493800003024000,
139-
# "price": 24.875,
140-
# "sequence_number": 1571279,
141-
# "sip_timestamp": 1650493800003645400,
142-
# "size": 100,
143-
# "tape": 1
144-
# },
145-
# {
146-
# "conditions": [
147-
# 38,
148-
# 41
149-
# ],
150-
# "exchange": 11,
151-
# "id": "52983575622469",
152-
# "participant_timestamp": 1650493800003024000,
153-
# "price": 24.875,
154-
# "sequence_number": 1571276,
155-
# "sip_timestamp": 1650493800003635500,
156-
# "tape": 1
157-
# },
158-
# {
159-
# "conditions": [
160-
# 15
161-
# ],
162-
# "exchange": 11,
163-
# "id": "52983575556178",
164-
# "participant_timestamp": 1650485400002987800,
165-
# "price": 24.875,
166-
# "sequence_number": 1536223,
167-
# "sip_timestamp": 1650485400003870000,
168-
# "size": 100,
169-
# "tape": 1
170-
# }
171-
# ],
172-
# "status": "OK",
173-
# "request_id": "618bb99e7a632ed9f55454a541404b44",
174-
# "next_url": "https://api.polygon.io/v3/trades/AAA?cursor=YXA9NSZhcz0mbGltaXQ9NSZvcmRlcj1kZXNjJnNvcnQ9dGltZXN0YW1wJnRpbWVzdGFtcC5ndGU9MjAyMi0wNC0yMFQwNCUzQTAwJTNBMDBaJnRpbWVzdGFtcC5sdGU9MjAyMi0wNC0yMFQyMCUzQTEwJTNBMDAuMDAzODY5OTUyWg"
175-
# }'
176-
54+
.. literalinclude:: ../../examples/rest/raw-list.py
17755

17856
WebSocket client usage
17957
----------------------
@@ -182,93 +60,23 @@ WebSocket client usage
18260

18361
The simplest way to use the websocket client is to just provide a callback:
18462

185-
.. code-block:: python
186-
187-
from polygon import WebSocketClient
188-
from polygon.websocket.models import WebSocketMessage
189-
from typing import List
190-
191-
c = WebSocketClient(subscriptions=['T.AAPL'])
192-
193-
def handle_msg(msgs: List[WebSocketMessage]):
194-
for m in msgs:
195-
print(m)
196-
197-
c.run(handle_msg)
63+
.. literalinclude:: ../../examples/websocket/simple.py
19864

19965
.. note::
20066
Raises :code:`AuthError` if invalid API key is provided.
20167

20268
If you want to capture state you can use a global variable inside the callback.
20369
Alternatively, you can wrap a class method in a closure.
20470

205-
.. code-block:: python
206-
207-
from polygon import WebSocketClient
208-
from polygon.websocket.models import WebSocketMessage
209-
from typing import List
210-
211-
class MessageHandler:
212-
count = 0
213-
214-
def handle_msg(self, msgs: List[WebSocketMessage]):
215-
for m in msgs:
216-
if type(m) == EquityTrade:
217-
print(self.count, m)
218-
self.count += 1
219-
220-
h = MessageHandler()
221-
222-
def handle_msg(msgs: List[WebSocketMessage]):
223-
h.handle_msg(msgs)
224-
225-
c.run(handle_msg)
71+
.. literalinclude:: ../../examples/websocket/aggs.py
22672

22773
Under the hood our client uses an asynchronous runtime. To manage the runtime
228-
yourself (including unsubscribing and subscribing) you'll need to use asyncio
229-
and the :code:`.connect` method:
230-
231-
.. code-block:: python
232-
233-
from polygon import WebSocketClient
234-
from polygon.websocket.models import WebSocketMessage
235-
from typing import List
236-
237-
c = WebSocketClient(subscriptions=['T.AAPL']) # Uses POLYGON_API_KEY env var. Can optionally supply your key.
74+
yourself (including unsubscribing and subscribing) you can use asyncio and the
75+
:code:`.connect` method:
23876

239-
async def handle_msg(msgs: List[WebSocketMessage]):
240-
for m in msgs:
241-
print(m)
242-
243-
async def timeout():
244-
await asyncio.sleep(1)
245-
print('unsubscribe_all')
246-
c.unsubscribe_all()
247-
await asyncio.sleep(1)
248-
print('close')
249-
await c.close()
250-
251-
async def main():
252-
await asyncio.gather(
253-
c.connect(handle_msg),
254-
timeout()
255-
)
256-
257-
asyncio.run(main())
77+
.. literalinclude:: ../../examples/websocket/async.py
25878

25979
To handle raw messages yourself pass `raw=True`:
26080

261-
.. code-block:: python
262-
263-
from polygon import WebSocketClient
264-
from polygon.websocket.models import WebSocketMessage
265-
from typing import Union
266-
import json
267-
268-
c = WebSocketClient(subscriptions=['T.*'], raw=True)
269-
270-
def handle_msg(msgs: Union[str, bytes]):
271-
print(json.loads(msgs))
272-
273-
c.run(handle_msg)
81+
.. literalinclude:: ../../examples/websocket/raw.py
27482

docs/source/WebSocket.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ WebSocket
77
Init client
88
===========
99
.. automethod:: polygon.WebSocketClient.__init__
10+
:noindex:
1011

1112
============================
1213
Connect

docs/source/index.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ This documentation is for the Python client only. For details about the response
77
:maxdepth: 1
88
:caption: Contents:
99

10-
Getting-Started
10+
Getting-started
1111
Aggs
1212
WebSocket
1313
Snapshot
@@ -17,7 +17,7 @@ This documentation is for the Python client only. For details about the response
1717
vX
1818
Models
1919
Enums
20-
WebSocket-Enums
20+
WebSocket-enums
2121

2222
Indices and tables
2323
==================

0 commit comments

Comments
 (0)