pythonplotlycandlestick-chart

How to add an indicator of certain value on x-axis in plotly candlestick chart


I have a simple candle stick chart made with plotly.

import yfinance as yf
import pandas as pd
import plotly.graph_objects as go
from plotly.subplots import make_subplots

djia = yf.Ticker("DJIA")
df = djia.history(start="2022-01-01", end="2022-12-31", interval="1d")

fig = go.Figure()
fig = make_subplots(rows=1, cols=1)

# candlestick
fig.append_trace(
    go.Candlestick(
        x=df.index,
        open=df["Open"],
        high=df["High"],
        low=df["Low"],
        close=df["Close"]
    ), row=1, col=1
)

fig.update_xaxes(rangebreaks=[dict(bounds=["sat", "mon"])])
fig.show()

plotly candlestick chart

I don't know what it is called but I would like to add an indicator on x-axis to tell if certain condition is true during that the time frame of each candle. Here is a reference picture that explains what I'm looking for. The yellow and purple dots that are marked with the red square.

reference candle stick chart

The idea would be to have an extra column in the dataframe with True/False values for each candle and that would be used to decide the color of the indicator dots. How could I achieve this?


Solution

  • A scatter plot is drawn on the current candlestick graph at the price 18 location. The color is determined by comparing the opening and closing prices. The easiest way to do this is to add a column of colors to the original data frame and set it to the color of the marker.

    import yfinance as yf
    import pandas as pd
    import plotly.graph_objects as go
    from plotly.subplots import make_subplots
    
    djia = yf.Ticker("DJIA")
    df = djia.history(start="2022-01-01", end="2022-12-31", interval="1d")
    # color column add
    df['colors'] = df[['Open', 'Close']].apply(lambda x: 'green' if x['Open'] <= x['Close'] else 'red', axis=1)
    
    fig = go.Figure()
    fig = make_subplots(rows=1, cols=1)
    
    # candlestick
    fig.append_trace(
        go.Candlestick(
            x=df.index,
            open=df["Open"],
            high=df["High"],
            low=df["Low"],
            close=df["Close"]
        ), row=1, col=1
    )
    fig.add_trace(go.Scatter(mode='markers', x=df.index, y=[18]*len(df), marker=dict(size=5, color=df['colors'])),row=1, col=1)
    
    fig.update_xaxes(rangebreaks=[dict(bounds=["sat", "mon"])])
    fig.update_layout(height=500)
    fig.show()
    

    enter image description here