Plotting stock prices in Python

A common tool used for visualizing stock price changes over time is an OHLC (open, high, low, close) chart. This is a chart of “candles” where each candle contains the open, high, low, and close of a stock price over a set time interval. If we use a daily OHLC chart, the time interval for each candle is one trading day. Other common time intervals used are month, hour, and minute.

Let’s use minute OHLC data to demonstrate. Use Polygon’s API to retrieve this data. Polygon’s API requires either a Polygon key or Alpaca key. If you don’t have this set up, another way you can retrieve this data is with the yfinance library. Pull AAPL stock price minute bar data for trading day of July 31, 2020.

Construct the OHLC chart with minute bars for the first hour of trading with the Python library mplfinance. Note that time is plotted in UTC.

Add more attributes to the chart by passing additional parameters to the plot function. Include a moving average by using the “mav” keyword. Pass in an integer for a single moving average. Use a tuple or list of integers for multiple moving averages.

We can add a volume chart at the bottom with the volume keyword.

Plot data across multiple trading days. You can choose whether to include non-trading time in the chart with the show_nontrading parameter. Plot this with the chart type “line” instead of “candle” because of the number of candles it would contain. Retrieve trading data from July 30, 2020 to July 31, 2020. Plot data from July 30th 3:30pm EST to July 31st 10am EST.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store