Skip to content

Commit 9db0beb

Browse files
author
clickingbuttons
committed
Date param support (#131)
* add time mult * add example
1 parent 2d57f39 commit 9db0beb

File tree

6 files changed

+76
-49
lines changed

6 files changed

+76
-49
lines changed

polygon/rest/aggs.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
from email.headerregistry import Group
21
from .base import BaseClient
32
from typing import Optional, Any, Dict, List, Union
43
from .models import Agg, GroupedDailyAgg, DailyOpenCloseAgg, PreviousCloseAgg, Sort
54
from urllib3 import HTTPResponse
6-
from datetime import datetime
5+
from datetime import datetime, date
76

87
# https://polygon.io/docs/stocks
98
class AggsClient(BaseClient):
@@ -13,8 +12,8 @@ def get_aggs(
1312
multiplier: int,
1413
timespan: str,
1514
# "from" is a keyword in python https://www.w3schools.com/python/python_ref_keywords.asp
16-
from_: Union[str, int, datetime],
17-
to: Union[str, int, datetime],
15+
from_: Union[str, int, datetime, date],
16+
to: Union[str, int, datetime, date],
1817
adjusted: Optional[bool] = None,
1918
sort: Optional[Union[str, Sort]] = None,
2019
limit: Optional[int] = None,
@@ -23,11 +22,12 @@ def get_aggs(
2322
) -> Union[List[Agg], HTTPResponse]:
2423
"""
2524
Get aggregate bars for a ticker over a given date range in custom time window sizes.
25+
2626
:param ticker: The ticker symbol.
2727
:param multiplier: The size of the timespan multiplier.
2828
:param timespan: The size of the time window.
29-
:param _from: The start of the aggregate time window as YYYY-MM-DD, Unix MS Timestamps, or a datetime.
30-
:param to: The end of the aggregate time window as YYYY-MM-DD, Unix MS Timestamps, or a datetime.
29+
:param _from: The start of the aggregate time window as YYYY-MM-DD, a date, Unix MS Timestamp, or a datetime.
30+
:param to: The end of the aggregate time window as YYYY-MM-DD, a date, Unix MS Timestamp, or a datetime.
3131
:param adjusted: Whether or not the results are adjusted for splits. By default, results are adjusted. Set this to false to get results that are NOT adjusted for splits.
3232
:param sort: Sort the results by timestamp. asc will return results in ascending order (oldest at the top), desc will return results in descending order (newest at the top).The end of the aggregate time window.
3333
:param limit: Limits the number of base aggregates queried to create the aggregate results. Max 50000 and Default 5000. Read more about how limit is used to calculate aggregate results in our article on Aggregate Data API Improvements.
@@ -36,10 +36,10 @@ def get_aggs(
3636
:return: List of aggregates
3737
"""
3838
if isinstance(from_, datetime):
39-
from_ = int(from_.timestamp() * 1000)
39+
from_ = int(from_.timestamp() * self.time_mult("millis"))
4040

4141
if isinstance(to, datetime):
42-
to = int(to.timestamp() * 1000)
42+
to = int(to.timestamp() * self.time_mult("millis"))
4343
url = f"/v2/aggs/ticker/{ticker}/range/{multiplier}/{timespan}/{from_}/{to}"
4444

4545
return self._get(

polygon/rest/base.py

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,13 @@
33
import urllib3
44
import inspect
55
from enum import Enum
6-
from typing import Optional, Any
6+
from typing import Optional, Any, Dict
7+
from datetime import datetime
78

89
base = "https://api.polygon.io"
910
env_key = "POLYGON_API_KEY"
1011

11-
# https://urllib3.readthedocs.io/en/stable/reference/urllib3.poolmanager.html
12+
1213
class BaseClient:
1314
def __init__(
1415
self,
@@ -18,6 +19,7 @@ def __init__(
1819
num_pools: int = 10,
1920
retries=3,
2021
base: str = base,
22+
verbose: bool = False,
2123
):
2224
if api_key is None:
2325
raise Exception(
@@ -26,12 +28,14 @@ def __init__(
2628
self.API_KEY = api_key
2729
self.BASE = base
2830

31+
# https://urllib3.readthedocs.io/en/stable/reference/urllib3.poolmanager.html
2932
# https://urllib3.readthedocs.io/en/stable/reference/urllib3.connectionpool.html#urllib3.HTTPConnectionPool
3033
self.client = urllib3.PoolManager(
3134
num_pools=num_pools, headers={"Authorization": "Bearer " + self.API_KEY}
3235
)
3336
self.timeout = urllib3.Timeout(connect=connect_timeout, read=read_timeout)
3437
self.retries = retries
38+
self.verbose = verbose
3539

3640
def _decode(self, resp):
3741
return json.loads(resp.data.decode("utf-8"))
@@ -47,6 +51,8 @@ def _get(
4751
if params is None:
4852
params = {}
4953
params = {str(k): str(v) for k, v in params.items() if v is not None}
54+
if self.verbose:
55+
print("_get", path, params)
5056
resp = self.client.request(
5157
"GET", self.BASE + path, fields=params, retries=self.retries
5258
)
@@ -70,7 +76,20 @@ def _get(
7076

7177
return obj
7278

73-
def _get_params(self, fn, caller_locals):
79+
@staticmethod
80+
def time_mult(timestamp_res: str) -> int:
81+
if timestamp_res == "nanos":
82+
return 1000000000
83+
elif timestamp_res == "micros":
84+
return 1000000
85+
elif timestamp_res == "millis":
86+
return 1000
87+
88+
return 1
89+
90+
def _get_params(
91+
self, fn, caller_locals: Dict[str, Any], datetime_res: str = "nanos"
92+
):
7493
params = caller_locals["params"]
7594
if params is None:
7695
params = {}
@@ -84,6 +103,8 @@ def _get_params(self, fn, caller_locals):
84103
val = caller_locals.get(argname, v.default)
85104
if isinstance(val, Enum):
86105
val = val.value
106+
elif isinstance(val, datetime):
107+
val = int(val.timestamp() * self.time_mult(datetime_res))
87108
if val is not None:
88109
params[argname.replace("_", ".")] = val
89110

polygon/rest/quotes.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,18 @@
22
from typing import Optional, Any, Dict, List, Union
33
from .models import Quote, LastQuote, Sort, Order
44
from urllib3 import HTTPResponse
5+
from datetime import datetime, date
56

67
# https://polygon.io/docs/stocks
78
class QuotesClient(BaseClient):
89
def list_quotes(
910
self,
1011
ticker: str,
11-
timestamp: Optional[str] = None,
12-
timestamp_lt: Optional[str] = None,
13-
timestamp_lte: Optional[str] = None,
14-
timestamp_gt: Optional[str] = None,
15-
timestamp_gte: Optional[str] = None,
12+
timestamp: Optional[Union[str, int, datetime, date]] = None,
13+
timestamp_lt: Optional[Union[str, int, datetime, date]] = None,
14+
timestamp_lte: Optional[Union[str, int, datetime, date]] = None,
15+
timestamp_gt: Optional[Union[str, int, datetime, date]] = None,
16+
timestamp_gte: Optional[Union[str, int, datetime, date]] = None,
1617
limit: Optional[int] = None,
1718
sort: Optional[Union[str, Sort]] = None,
1819
order: Optional[Union[str, Order]] = None,

polygon/rest/reference.py

Lines changed: 26 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
Exchange,
2222
)
2323
from urllib3 import HTTPResponse
24+
from datetime import date
2425

2526
# https://polygon.io/docs/stocks
2627
class MarketsClient(BaseClient):
@@ -200,11 +201,11 @@ def list_splits(
200201
ticker_lte: Optional[str] = None,
201202
ticker_gt: Optional[str] = None,
202203
ticker_gte: Optional[str] = None,
203-
execution_date: Optional[str] = None,
204-
execution_date_lt: Optional[str] = None,
205-
execution_date_lte: Optional[str] = None,
206-
execution_date_gt: Optional[str] = None,
207-
execution_date_gte: Optional[str] = None,
204+
execution_date: Optional[Union[str, date]] = None,
205+
execution_date_lt: Optional[Union[str, date]] = None,
206+
execution_date_lte: Optional[Union[str, date]] = None,
207+
execution_date_gt: Optional[Union[str, date]] = None,
208+
execution_date_gte: Optional[Union[str, date]] = None,
208209
reverse_split: Optional[bool] = None,
209210
limit: Optional[int] = None,
210211
sort: Optional[Union[str, Sort]] = None,
@@ -251,26 +252,26 @@ def list_dividends(
251252
ticker_lte: Optional[str] = None,
252253
ticker_gt: Optional[str] = None,
253254
ticker_gte: Optional[str] = None,
254-
ex_dividend_date: Optional[str] = None,
255-
ex_dividend_date_lt: Optional[str] = None,
256-
ex_dividend_date_lte: Optional[str] = None,
257-
ex_dividend_date_gt: Optional[str] = None,
258-
ex_dividend_date_gte: Optional[str] = None,
259-
record_date: Optional[str] = None,
260-
record_date_lt: Optional[str] = None,
261-
record_date_lte: Optional[str] = None,
262-
record_date_gt: Optional[str] = None,
263-
record_date_gte: Optional[str] = None,
264-
declaration_date: Optional[str] = None,
265-
declaration_date_lt: Optional[str] = None,
266-
declaration_date_lte: Optional[str] = None,
267-
declaration_date_gt: Optional[str] = None,
268-
declaration_date_gte: Optional[str] = None,
269-
pay_date: Optional[str] = None,
270-
pay_date_lt: Optional[str] = None,
271-
pay_date_lte: Optional[str] = None,
272-
pay_date_gt: Optional[str] = None,
273-
pay_date_gte: Optional[str] = None,
255+
ex_dividend_date: Optional[Union[str, date]] = None,
256+
ex_dividend_date_lt: Optional[Union[str, date]] = None,
257+
ex_dividend_date_lte: Optional[Union[str, date]] = None,
258+
ex_dividend_date_gt: Optional[Union[str, date]] = None,
259+
ex_dividend_date_gte: Optional[Union[str, date]] = None,
260+
record_date: Optional[Union[str, date]] = None,
261+
record_date_lt: Optional[Union[str, date]] = None,
262+
record_date_lte: Optional[Union[str, date]] = None,
263+
record_date_gt: Optional[Union[str, date]] = None,
264+
record_date_gte: Optional[Union[str, date]] = None,
265+
declaration_date: Optional[Union[str, date]] = None,
266+
declaration_date_lt: Optional[Union[str, date]] = None,
267+
declaration_date_lte: Optional[Union[str, date]] = None,
268+
declaration_date_gt: Optional[Union[str, date]] = None,
269+
declaration_date_gte: Optional[Union[str, date]] = None,
270+
pay_date: Optional[Union[str, date]] = None,
271+
pay_date_lt: Optional[Union[str, date]] = None,
272+
pay_date_lte: Optional[Union[str, date]] = None,
273+
pay_date_gt: Optional[Union[str, date]] = None,
274+
pay_date_gte: Optional[Union[str, date]] = None,
274275
frequency: Optional[Union[int, Frequency]] = None,
275276
cash_amount: Optional[float] = None,
276277
cash_amount_lt: Optional[float] = None,

polygon/rest/trades.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2,17 +2,18 @@
22
from typing import Optional, Any, Dict, Union, Iterator
33
from .models import Trade, Sort, Order
44
from urllib3 import HTTPResponse
5+
from datetime import datetime, date
6+
57

6-
# https://polygon.io/docs/stocks
78
class TradesClient(BaseClient):
89
def list_trades(
910
self,
1011
ticker: str,
11-
timestamp: Optional[str] = None,
12-
timestamp_lt: Optional[str] = None,
13-
timestamp_lte: Optional[str] = None,
14-
timestamp_gt: Optional[str] = None,
15-
timestamp_gte: Optional[str] = None,
12+
timestamp: Optional[Union[str, int, datetime, date]] = None,
13+
timestamp_lt: Optional[Union[str, int, datetime, date]] = None,
14+
timestamp_lte: Optional[Union[str, int, datetime, date]] = None,
15+
timestamp_gt: Optional[Union[str, int, datetime, date]] = None,
16+
timestamp_gte: Optional[Union[str, int, datetime, date]] = None,
1617
limit: Optional[int] = None,
1718
sort: Optional[Union[str, Sort]] = None,
1819
order: Optional[Union[str, Order]] = None,

rest-example.py

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,12 @@
11
from polygon import RESTClient
22
from polygon.rest.models import Sort
3+
from datetime import date, datetime
34

4-
client = RESTClient()
5+
client = RESTClient(verbose=True)
56

6-
aggs = client.get_aggs("AAPL", 1, "day", "2005-04-01", "2005-04-04")
7+
aggs = client.get_aggs("AAPL", 1, "day", "2005-04-04", "2005-04-04")
8+
print(aggs)
9+
aggs = client.get_aggs("AAPL", 1, "day", date(2005, 4, 4), datetime(2005, 4, 4))
710
print(aggs)
811

912
trades = []

0 commit comments

Comments
 (0)