Polygon minute-bar data

Table of contents

Retrieve minute bar data from the Polygon REST API

Retrieve minute bar data for AAPL on 2020-05-04

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-05-04'
date_end = '2020-05-04'
timespan = 'minute'

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)

Put response into a pandas DataFrame

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-05-04 04:00:00-04:00 4972.0 72.0518 72.0625 72.0625 72.0625 72.0625 1588579200000 10
2020-05-04 04:01:00-04:00 3400.0 71.8663 71.8750 71.8700 71.8750 71.8425 1588579260000 12
2020-05-04 04:02:00-04:00 2144.0 71.8106 71.7875 71.7875 71.7875 71.7875 1588579320000 18
2020-05-04 04:03:00-04:00 1836.0 71.9074 71.9850 71.9850 71.9850 71.9850 1588579380000 8
2020-05-04 04:05:00-04:00 1476.0 71.9960 72.0000 72.0000 72.0000 72.0000 1588579500000 5

Visualize data

Plot minute bars during the last two hours of trading hours

In [16]:
import matplotlib.pyplot as plt
import mplfinance as mpf
%matplotlib inline

df.columns = ['Volume', 'Volume Weighted', 'Open', 'Close', 'High', 'Low', 'Time', 'Num Trades']
mpf.plot(
    df['2020-05-04 14:00:00-04:00':'2020-05-04 16:00:00-04:00'], 
    type='candle',
    volume=True
)
In [ ]: