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)
Insert into dataframe with a pd.Timestamp index (in the EST timezone)
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()
Plot minute bars during the last two hours of trading hours
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
)