Skip to content

Commit 0ba11f2

Browse files
committed
make sure that historic_aggs returns the 'to' data for daily bars
1 parent 0605371 commit 0ba11f2

File tree

1 file changed

+31
-6
lines changed

1 file changed

+31
-6
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

0 commit comments

Comments
 (0)