Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Build a Custom Candlestick Plot | Visualizing Market Trends and Indicators
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Python for Traders

bookChallenge: Build a Custom Candlestick Plot

In this challenge, you will use matplotlib to create a custom candlestick chart from a hardcoded DataFrame containing OHLC (open, high, low, close) data for seven days. Candlestick charts are essential tools for traders, offering a clear visual representation of price movements and patterns over time. Each "candle" shows the open and close prices as well as the high and low for each trading period, helping you quickly spot bullish and bearish trends. Your goal is to plot each candle in green if the close is higher than the open (bullish) and in red if the close is lower than the open (bearish). Additionally, you will annotate the chart with the highest high and the lowest low values to highlight significant price levels.

123456789101112131415161718192021222324252627282930313233343536373839404142434445
import pandas as pd import matplotlib.pyplot as plt # Hardcoded OHLC data for 7 days data = { "Date": pd.date_range("2024-06-01", periods=7, freq="D"), "Open": [100, 102, 101, 103, 102, 105, 104], "High": [105, 104, 103, 106, 107, 108, 107], "Low": [99, 100, 100, 102, 101, 104, 103], "Close": [104, 101, 103, 105, 106, 106, 104], } df = pd.DataFrame(data) fig, ax = plt.subplots(figsize=(10, 6)) width = 0.6 # width of the candlestick body for idx, row in df.iterrows(): color = "green" if row["Close"] >= row["Open"] else "red" # Draw the wick (high-low line) ax.plot([idx, idx], [row["Low"], row["High"]], color="black", linewidth=1) # Draw the candle body (open-close rectangle) lower = min(row["Open"], row["Close"]) height = abs(row["Close"] - row["Open"]) rect = plt.Rectangle((idx - width/2, lower), width, height or 0.1, color=color, alpha=0.8) ax.add_patch(rect) # Annotate highest high and lowest low highest_high = df["High"].max() highest_idx = df["High"].idxmax() ax.annotate(f"High: {highest_high}", xy=(highest_idx, highest_high), xytext=(highest_idx, highest_high+0.5), arrowprops=dict(facecolor='blue', shrink=0.05), ha='center', color='blue') lowest_low = df["Low"].min() lowest_idx = df["Low"].idxmin() ax.annotate(f"Low: {lowest_low}", xy=(lowest_idx, lowest_low), xytext=(lowest_idx, lowest_low-1), arrowprops=dict(facecolor='blue', shrink=0.05), ha='center', color='blue') # Formatting the x-axis with dates ax.set_xticks(range(len(df))) ax.set_xticklabels(df["Date"].dt.strftime("%b %d"), rotation=45) ax.set_title("Custom Candlestick Chart") ax.set_xlabel("Date") ax.set_ylabel("Price") plt.tight_layout() plt.show()
copy
Note
Note

Candlestick charts are widely used in technical analysis because they provide more information than simple line charts. By visualizing the relationship between open, close, high, and low prices, you can quickly identify market sentiment and potential reversal points.

For more on candlestick charting techniques, consider reading "Japanese Candlestick Charting Techniques" by Steve Nison.

Task

Swipe to start coding

Plot a candlestick chart using the provided DataFrame, following these steps:

  • Draw each candlestick with rectangles and lines using matplotlib.
  • Color each candle body green if close >= open, or red if close < open.
  • Annotate the chart with the highest high and lowest low values using ax.annotate.
  • Format the x-axis to display the dates from the DataFrame.

Solution

Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 2. ChapterΒ 5
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

close

bookChallenge: Build a Custom Candlestick Plot

Swipe to show menu

In this challenge, you will use matplotlib to create a custom candlestick chart from a hardcoded DataFrame containing OHLC (open, high, low, close) data for seven days. Candlestick charts are essential tools for traders, offering a clear visual representation of price movements and patterns over time. Each "candle" shows the open and close prices as well as the high and low for each trading period, helping you quickly spot bullish and bearish trends. Your goal is to plot each candle in green if the close is higher than the open (bullish) and in red if the close is lower than the open (bearish). Additionally, you will annotate the chart with the highest high and the lowest low values to highlight significant price levels.

123456789101112131415161718192021222324252627282930313233343536373839404142434445
import pandas as pd import matplotlib.pyplot as plt # Hardcoded OHLC data for 7 days data = { "Date": pd.date_range("2024-06-01", periods=7, freq="D"), "Open": [100, 102, 101, 103, 102, 105, 104], "High": [105, 104, 103, 106, 107, 108, 107], "Low": [99, 100, 100, 102, 101, 104, 103], "Close": [104, 101, 103, 105, 106, 106, 104], } df = pd.DataFrame(data) fig, ax = plt.subplots(figsize=(10, 6)) width = 0.6 # width of the candlestick body for idx, row in df.iterrows(): color = "green" if row["Close"] >= row["Open"] else "red" # Draw the wick (high-low line) ax.plot([idx, idx], [row["Low"], row["High"]], color="black", linewidth=1) # Draw the candle body (open-close rectangle) lower = min(row["Open"], row["Close"]) height = abs(row["Close"] - row["Open"]) rect = plt.Rectangle((idx - width/2, lower), width, height or 0.1, color=color, alpha=0.8) ax.add_patch(rect) # Annotate highest high and lowest low highest_high = df["High"].max() highest_idx = df["High"].idxmax() ax.annotate(f"High: {highest_high}", xy=(highest_idx, highest_high), xytext=(highest_idx, highest_high+0.5), arrowprops=dict(facecolor='blue', shrink=0.05), ha='center', color='blue') lowest_low = df["Low"].min() lowest_idx = df["Low"].idxmin() ax.annotate(f"Low: {lowest_low}", xy=(lowest_idx, lowest_low), xytext=(lowest_idx, lowest_low-1), arrowprops=dict(facecolor='blue', shrink=0.05), ha='center', color='blue') # Formatting the x-axis with dates ax.set_xticks(range(len(df))) ax.set_xticklabels(df["Date"].dt.strftime("%b %d"), rotation=45) ax.set_title("Custom Candlestick Chart") ax.set_xlabel("Date") ax.set_ylabel("Price") plt.tight_layout() plt.show()
copy
Note
Note

Candlestick charts are widely used in technical analysis because they provide more information than simple line charts. By visualizing the relationship between open, close, high, and low prices, you can quickly identify market sentiment and potential reversal points.

For more on candlestick charting techniques, consider reading "Japanese Candlestick Charting Techniques" by Steve Nison.

Task

Swipe to start coding

Plot a candlestick chart using the provided DataFrame, following these steps:

  • Draw each candlestick with rectangles and lines using matplotlib.
  • Color each candle body green if close >= open, or red if close < open.
  • Annotate the chart with the highest high and lowest low values using ax.annotate.
  • Format the x-axis to display the dates from the DataFrame.

Solution

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

SectionΒ 2. ChapterΒ 5
single

single

some-alt