Retrieve daily bar data from the Polygon REST API

Retrieve daily bar data for AAPL from 2020-01-01 to 2020-04-30

In [1]:
import requests
import json
import time
import pandas as pd
import pytz
from datetime import datetime

# retrieve alpaca keys
%run alpaca_keys.py

ticker = 'AAPL'
multiplier = '1'
date_start = '2020-01-01'
date_end = '2020-04-30'
timespan = 'day'

request_string = (
    f'https://api.polygon.io/v2/aggs/ticker/{ticker}'
    f'/range/{multiplier}/{timespan}/{date_start}/{date_end}'
    f'?apiKey={KEY_ID}'
)

r = requests.get(request_string)

Insert into dataframe with a pd.Timestamp index (in the EST timezone)

In [2]:
df = pd.DataFrame(r.json()['results'])

est = pytz.timezone('US/Eastern')
utc = pytz.utc
# convert index time UTC to EST
df.index = [datetime.utcfromtimestamp(ts / 1000.).replace(tzinfo=utc).astimezone(est) for ts in df['t']]
df.index.name = 'Date'
df.head()
Out[2]:
v vw o c h l t n
Date
2020-01-02 00:00:00-05:00 135647456.0 298.4396 74.0600 75.0875 75.150 73.7975 1577941200000 1
2020-01-03 00:00:00-05:00 146535512.0 298.8104 74.2875 74.3575 75.145 74.1250 1578027600000 1
2020-01-06 00:00:00-05:00 118518576.0 297.7997 73.4475 74.9500 74.990 73.1875 1578286800000 1
2020-01-07 00:00:00-05:00 111510620.0 298.9243 74.9600 74.5975 75.225 74.3700 1578373200000 1
2020-01-08 00:00:00-05:00 132363784.0 301.1655 74.2900 75.7975 76.110 74.2890 1578459600000 1