Candlestick Charts in Python

Jatin
2 min readApr 2, 2023

--

The candlestick charts show the price movement of different trading instruments such as equity, currency, commodity, ETF, etc. By looking at a candlestick one can see the opening, high, low, and closing price for a given time value (hour, day, month, etc). The candlestick charts are used in technical analysis.

A red candlestick means the stock closed at a lower price than open.

A green candlestick means the stock closed at a higher price than open.

This article will show how to generate Candlestick charts using Python.

We are going to get Google’s (ticker: GOOG) stock market data (open, close, high, low, volume) for January 2022 and generate Candlestick charts for each day. Additionally, we will also visualize the trading volume.

import pandas as pd
import datetime
import yfinance as yf
import plotly.graph_objects as go

# Get Google's stock data for 2022
start = datetime.datetime(2022, 1, 1)
end = datetime.datetime(2022, 1, 31)
goog = yf.download("GOOG", start , end)
goog.head()
# Visualize using plotly's go.Candlestick
fig = go.Figure(data=[go.Candlestick(x=goog.index,
open=goog['Open'],
high=goog['High'],
low=goog['Low'],
close=goog['Close'])])

fig.show()

You can hover over a candlestick and see the details of that candle. Below the chart, you can see a slider by adjusting that you can filter on dates.

Next, we’re going to replace this slider with a volume trend. For that, we need to create a “Grid” to accommodate multiple plots.

# Create subplots and mention plot grid size
# we need 2 rows, 1 column. we will add one plot in each row
from plotly.subplots import make_subplots
fig = make_subplots(rows=2, cols=1, shared_xaxes=True,
vertical_spacing=0.03, subplot_titles=('Candlestick', 'Volume'),
row_width=[0.2, 0.7])
fig.data = []

# Add Candlestick on first row

fig.add_trace(go.Candlestick(x=goog.index,
open=goog['Open'],
high=goog['High'],
low=goog['Low'],
close=goog['Close'], name="Candlestick"),
row=1, col=1
)

# Add Bar chart for volume on second row
fig.add_trace(go.Bar(x=goog.index, y=goog['Volume'],marker_color='rgb(158,202,225)', showlegend=False), row=2, col=1)

# remove slider
fig.update(layout_xaxis_rangeslider_visible=False)
fig.show()

References:

https://www.wikipedia.org/

--

--

Jatin
Jatin

Written by Jatin

Data Analyst in San Francisco

No responses yet