Skip to content

Commit 787b7f1

Browse files
author
Shlomi Kushchi
authored
Merge pull request #283 from alpacahq/daily_bars_dont_include_last_date
Make sure that historic_aggs returns the 'to' data for daily bars
2 parents 5023fff + 03dbccc commit 787b7f1

File tree

2 files changed

+33
-8
lines changed

2 files changed

+33
-8
lines changed

alpaca_trade_api/polygon/rest.py

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,30 @@ def format_date_for_api_call(date):
4646
raise Exception(f"Unsupported date format: {date}")
4747

4848

49+
def fix_daily_bar_date(date, timespan):
50+
"""
51+
the polygon api does not include the end date for daily bars, or this:
52+
historic_agg_v2("SPY", 1, "day", _from="2020-07-22", to="2020-07-24").df
53+
results in this:
54+
timestamp
55+
2020-07-22 00:00:00-04:00 324.62 327.20 ... 57917101.0 325.8703
56+
2020-07-23 00:00:00-04:00 326.47 327.23 ... 75841843.0 324.3429
57+
58+
the 24th data is missing
59+
for minute bars, it does include the end date
60+
61+
so basically this method will add 1 day (if 'to' is not today, we don't
62+
have today's data until tomorrow) to the 'to' field
63+
"""
64+
if timespan == 'day':
65+
date = dateutil.parser.parse(date)
66+
today = datetime.datetime.utcnow().date()
67+
if today != date.date():
68+
date = date + datetime.timedelta(days=1)
69+
date = date.date().isoformat()
70+
return date
71+
72+
4973
class REST(object):
5074

5175
def __init__(self, api_key: str, staging: bool = False):
@@ -172,12 +196,13 @@ def historic_agg_v2(self,
172196
"""
173197
path_template = '/aggs/ticker/{symbol}/range/{multiplier}/' \
174198
'{timespan}/{_from}/{to}'
175-
path = path_template.format(symbol=symbol,
176-
multiplier=multiplier,
177-
timespan=timespan,
178-
_from=format_date_for_api_call(_from),
179-
to=format_date_for_api_call(to)
180-
)
199+
path = path_template.format(
200+
symbol=symbol,
201+
multiplier=multiplier,
202+
timespan=timespan,
203+
_from=format_date_for_api_call(_from),
204+
to=fix_daily_bar_date(format_date_for_api_call(to), timespan)
205+
)
181206
params = {'unadjusted': unadjusted}
182207
if limit:
183208
params['limit'] = limit

tests/test_polygon/test_rest.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,14 +78,14 @@ def test_polygon(reqmock):
7878

7979
reqmock.get(
8080
endpoint(
81-
'/aggs/ticker/AAPL/range/1/day/2018-02-02/2018-02-05',
81+
'/aggs/ticker/AAPL/range/1/day/2018-02-02/2018-02-06',
8282
params='unadjusted=False', api_version='v2'
8383
),
8484
text=aggs_response)
8585

8686
reqmock.get(
8787
endpoint(
88-
'/aggs/ticker/AAPL/range/1/day/1546300800000/2018-02-05',
88+
'/aggs/ticker/AAPL/range/1/day/1546300800000/2018-02-06',
8989
params='unadjusted=False', api_version='v2'
9090
),
9191
text=aggs_response)

0 commit comments

Comments
 (0)