Build Your First Candlestick Chart with Streamlit

Naga Chitrika
Nerd For Tech
Published in
6 min readMay 20, 2024

Build your first interactive candlestick chart with Streamlit! Learn to visualize financial data effectively using Python, Streamlit, and Plotly in our step-by-step tutorial. Perfect for beginners!

Candlestick charts are powerful tools in financial analysis. They are visual representations of market price movements. Originating from Japan in the 18th century, candlestick charts became popular due to their ability to convey complex price data in a simple and intuitive format.

Streamlit, Python, Plotly: Candlestick Charts| Pixabay

At a glance, each candlestick encapsulates a wealth of information about a particular trading period, typically a day, week, or month. The body of the candlestick shows the price ranges between the opening and closing prices, with different colors indicating whether the closing price was higher or lower than the opening price.

Additionally, thin lines are known as “wicks” or “shadows.” They extend from the top and bottom of the body and represent the highest and lowest prices reached during the period. Traders and analysts can identify trends, reversals, and market sentiment shifts by analyzing patterns and formations formed by consecutive candlesticks.

Candlestick charts are:

  • The cornerstone of technical analysis.
  • Offering insights into supply and demand dynamics.
  • Market psychology.
  • Potential future price movements.

In this tutorial, we’ll explore how to develop interactive candlestick charts for visualizing financial data. Candlestick charts are a popular tool in financial analysis because they succinctly represent price movements over time.

They display four essential pieces of information for each period: the opening price, closing price, highest price (high), and lowest price (low). We can also plot Forex Charts in Excel.

Prerequisites

Before getting started, ensure you have the following installed:

Python (3.6+): Python is the programming language used to write the application code. Make sure you have Python installed on your system.

Streamlit: Streamlit is the primary framework used to build our web application. We can install it using pip, the Python package manager.

Plotly: Plotly is the graphing library we’ll use to create candlestick charts. It can be installed via pip.

Requests: The Requests library is needed to request HTTP to the TraderMade API to fetch historical financial data.

API Key: Let us sign up with TraderMade and get our dedicated API to create and work on the app

Installation

Once these prerequisites are met, you’ll be ready to start building your interactive candlestick chart application!

We provide a clearer understanding of the technologies and tools we’ll use in this tutorial, as well as the steps required to prepare your environment before getting started.

You can install Streamlit, Plotly, and Requests using the following pip commands:

pip install streamlit plotly requests

Let’s Code

Step 1: Setting Up the Environment

In this section, we import the necessary libraries to set up our environment for building the candlestick chart application:

Streamlit: Streamlit is a powerful Python library for creating web applications with simple Python scripts. It allows us to create interactive user interfaces easily.

Requests: The Requests library is needed to request HTTP to the TraderMade API. We’ll use it to fetch historical financial data.

plotly.graph_objs: Plotly is a graphing library that provides various chart types. Here, we’re importing the graph_objs module to create candlestick charts.

datetime: The Datetime module provides classes for manipulating dates and times in Python.

import streamlit as st
import requests
import plotly.graph_objs as go
from datetime import datetime

Step 2: Fetching Historical Data

This section defines a function called fetch_historical_data, which is responsible for fetching historical financial data from an external API. Here’s what each part does:

Function Definition: We define a function named fetch_historical_data that takes parameters such as product type, instrument, start date, and end date.

API Request: We construct the URL and query parameters for the API request based on the input parameters.

Making the Request: We use the requests. Get function to make a GET request to the API endpoint with the constructed query parameters.

Handling the Response: We return the historical data if the request is successful (status code 200). Otherwise, we return None.

def fetch_historical_data(product, instrument, start_date, end_date):
# API parameters and URL
historical_url = "https://marketdata.tradermade.com/api/v1/timeseries"
api_key = "your_actual_api_key" # Replace with your API key

# Construct the query parameters
querystring = {
"currency": instrument,
"api_key": api_key,
"start_date": start_date,
"end_date": end_date
}

# Make the API request
response = requests.get(historical_url, params=querystring)

# Check if the request was successful
if response.status_code == 200:
return response.json()['quotes'] # Extract quotes from the response
else:
return None

Step 3: Creating the Sidebar

This section sets up the sidebar using Streamlit, providing a user-friendly interface for selecting financial instruments and date ranges:

Sidebar Title: We use st.sidebar.title to set the sidebar title to “Candlestick Charts”.

Product and Instrument Selection: Users can select the financial product (Forex, CFD, or Crypto) and the specific instrument (e.g., GBPUSD, NATGAS) from dropdown menus.

Date Range Selection: Users can choose the start and end dates for the historical data they want to visualize.

# Sidebar
st.sidebar.title("Candlestick Charts")

# Select product (Forex, CFD, or Crypto)
product = st.sidebar.selectbox("Select Financial Instrument", ["Forex", "CFD", "Crypto"])

# Select instrument based on the product type
if product == "Forex":
instruments = ["GBPUSD", "EURUSD", "USDJPY"]
elif product == "CFD":
instruments = ["NATGAS", "OIL", "XAUUSD", "XAGUSD"]
else: # Assuming Crypto
instruments = ["BTCUSD", "ETHUSD", "XRPUSD"]

instrument = st.sidebar.selectbox("Select Instrument", instruments)

# Select date range
start_date = st.sidebar.date_input("Start Date", value=datetime(2024, 4, 1))
end_date = st.sidebar.date_input("End Date", value=datetime(2024, 4, 30))

Step 4: Fetching and Displaying Data

In this final section, we fetch the historical data based on the user’s selections and display the candlestick chart:

  • Fetching Data: To fetch historical financial data, we call the fetch_historical_data function with the selected product, instrument, and date range.
  • Data Validation: If data is successfully fetched, we extract relevant information such as dates open, high, low, and close prices from the fetched data.
  • Creating the Candlestick Chart: We use Plotly’s Candlestick object to create a candlestick chart with the extracted data.
  • Displaying the Chart: Finally, we use Streamlit’s st.plotly_chart function to display the candlestick chart in the Streamlit web application. If data fetching fails, we display an error message.
# Fetch historical data
historical_data = fetch_historical_data(product, instrument, start_date.strftime("%Y-%m-%d"), end_date.strftime("%Y-%m-%d"))

# Display candlestick chart
if historical_data is not None:
# Extract data for plotting
dates = [quote['date'] for quote in historical_data]
open_prices = [quote['open'] for quote in historical_data]
high_prices = [quote['high'] for quote in historical_data]
low_prices = [quote['low'] for quote in historical_data]
close_prices = [quote['close'] for quote in historical_data]

# Create candlestick chart using Plotly
candlestick = go.Candlestick(x=dates,
open=open_prices,
high=high_prices,
low=low_prices,
close=close_prices)

layout = go.Layout(title=f'Candlestick Chart for {instrument}',
xaxis=dict(title='Date'),
yaxis=dict(title='Price'))

fig = go.Figure(data=[candlestick], layout=layout)

# Display the chart using Streamlit
st.plotly_chart(fig)
else:
st.error("Failed to fetch historical data. Please check your API key and selected instrument.")



Execute the code:

The below command executes our program. Runs the Streamlit application specified in candlestick.py. You can name your program accordingly, but .py shows a system that is a Python program.

Starts a local web server for the app, which is necessary for hosting the application locally.Opens the app in your web browser using the given local URL.

python -m streamlit run candlestick.py

Viola! We got our app ready

Conclusion:

By following this tutorial, you have learned how to build an interactive candlestick chart using Streamlit, TraderMade API, and Plotly. This application helps visualize financial data effectively by simplifying the analysis of market trends and price movements, making it accessible even to those with limited coding experience.

With this knowledge, you can now create powerful financial visualization tools tailored to your needs.

--

--

Naga Chitrika
Nerd For Tech

Experienced fintech enthusiast with over 3 years of industry knowledge. Sharing ideas on technology in financial services and the latest innovations.