Search code examples
pythonplotly

Add Annotations to Plotly Candlestick Chart


I have been using plotly to create charts using OHLC data in a dataframe. The chart contains candlesticks on the top and volume bars at the bottom:

enter image description here

I want to annotate the candlestick chart (not the volume chart) but cannot work out how to do it.

This code works to create the charts:

# Plot chart

# Create subplots and mention plot grid size
fig = make_subplots(rows=2, cols=1, shared_xaxes=True,
                    vertical_spacing=0.03,
                    row_width=[0.2, 0.7])

# Plot OHLC on 1st row
fig.add_trace(go.Candlestick(x=df.index, open=df["Open"], high=df["High"],
                             low=df["Low"], close=df["Close"], name="OHLC"),
              row=1, col=1
              )

# Bar trace for volumes on 2nd row without legend
fig.add_trace(go.Bar(x=df.index, y=df['Volume'], showlegend=False), row=2, col=1)

fig.update_layout(xaxis_rangeslider_visible=False, title_text=f'{ticker}')

fig.write_html(fr"E:\Documents\PycharmProjects\xxxxxxxx.html")

And I tried adding the following after the candlestick add_trace but it doesn't work:

fig.add_annotation(x=i, y=df["Close"],
                   text="Test text",
                   showarrow=True,
                   arrowhead=1)

What am I doing wrong?


Solution

  • The issue is that you pass the whole df["Close"] series where you should pass only the value at index i, that is df.loc[i, "Close"].

    This should work :

    fig.add_annotation(x=i, y=df.loc[i, "Close"],
                       text="Test text",
                       showarrow=True,
                       arrowhead=1)