Visualize Historical Stock Data with a Candlestick Chart
Candlestick charts are popular way to visualize price movements and trading patterns in the financial industry. This template generates an interactive candlestick chart of a stock of your choice.
Step 1. Download and load packages
In this template, you'll be using the yfinance package, which allows you to download market data from the Yahoo! Finance API.
# Load packages
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import yfinance as yf
from datetime import datetime, timedelta
Step 2. Select a stock and date range
Which stock do you want to visualize? Set symbol
to the stock ticker symbol of your choice in the next code cell.
⚠️ If you get this error: No data found for this date range, symbol may be delisted
, you're not entering a valid stock symbol. You can look up companies and their symbols here.
# Select a stock ticker symbol
symbol = "FB"
# Get historical market prices and range of dates
prices = yf.Ticker(symbol)
prices = prices.history(period="max")
max_date = prices.index.max().date()
min_date = prices.index.min().date()
# Get the company's full name and logo (if available)
stock_info = yf.Ticker(symbol).info
logo_url = stock_info["logo_url"]
company_name = stock_info['longName']
# Preview the data
print(f"Prices available from {min_date} to {max_date}.")
prices.head()
Once you've chosen a valid stock symbol, you can specify a date range as short or long as you would like. Just make sure it's within the available date range provided in the last cell's output. If you don't set your own range, all dates will be plotted by default.
# Select a date range (by default all dates will be plotted)
start_date = min_date
end_date = max_date
# Slice prices based on the provided date range
prices = prices[start_date:end_date]
Step 3. Plot the data
This code cell creates a the candlestick chart using Plotly. Code comments are provided if you are interested in customizing the chart.
# Create a candlesitck chart
fig = go.Figure(
data=[
go.Candlestick(
x=prices.index,
open=prices["Open"],
high=prices["High"],
low=prices["Low"],
close=prices["Close"],
# Set line colors
increasing_line_color="tomato",
decreasing_line_color="forestgreen",
)
]
)
# Add image (if available)
if not logo_url == "":
fig.add_layout_image(
dict(
source=logo_url,
xref="paper",
yref="paper",
x=1,
y=1.05,
sizex=0.2,
sizey=0.2,
xanchor="right",
yanchor="bottom",
)
)
# Customize the layout
fig.update_layout(
title=f"{company_name} ({symbol}) Stock Prices", # Set title
width=900, # Set width
height=500, # Set height
xaxis_rangeslider_visible=True, # Set to False to remove Rangeslider
template="ggplot2", # Set a Plotly theme
)
fig.show()
The plot is interactive - you can zoom into specific periods using the range slider at the bottom of the plot. Depending on how zoomed in you are, you can hover over the candlesticks to read information about that day's price. You can always reset to the plot's original state by double-clicking anywhere in the plot.
Looking to customize the plot further? Read through the code comments to customize the title, colors, and dimensions!
If you're interested in learning more, check out DataCamp's Financial Trading in Python course!