I have a candle stick graph created to show monthly candles of a stock using plotly in python. I want to customize only one candle for April 2022 (see figure). Here is the complete code.
fig = make_subplots(rows=1, cols=1, subplot_titles=[], \
specs=[[{"secondary_y": True}]], \
vertical_spacing=0, shared_xaxes=True, row_width=[1.0])
fig.add_trace(go.Scatter(x=df.index, y=df['Pivot'], marker=dict(color='black'), line=dict( width=2),
mode='lines', name='Pivot Point'), row=1, col=1)
fig.add_trace(go.Scatter(x=df.index, y=df['R1'], marker=dict(color='olive'), line=dict( width=1,dash='dot'),
mode='lines', name='Resistance 1'), row=1, col=1)
fig.add_trace(go.Scatter(x=df.index, y=df['S1'], marker=dict(color='turquoise'), line=dict( width=2,dash='dot'),
mode='lines', name='Support 1'), row=1, col=1)
# Adding Candlestick graph
fig.add_trace(go.Candlestick(x=df.index,
open=df['Open'],
close=df['Close'],
low=df['Low'],
high=df['High'],
increasing_line_color='green', decreasing_line_color='red', name='HRC Price'),row=1, col=1,)
fig.update_layout(
title='HRC Monthly Price',
yaxis_title='Price',
shapes = [dict(
x0='2022-03-14', x1='2022-03-14', y0=0, y1=1, xref='x', yref='paper',
line_width=2)],
annotations=[dict(
x='2022-03-14', y=0.05, xref='x', yref='paper',
showarrow=False, xanchor='left', text='Ukraine - Russia War Starts')]
)
return fig
How do i color the last candle with a different color?
You can split your df into two separate dataframes called df_before
and df_last
using iloc
:
df_before = df.iloc[:len(df)-1]
df_last = df.iloc[len(df)-1:]
Then plot these in separate traces and specify the desired color for the last candle:
# Adding Candlestick graph
fig.add_trace(go.Candlestick(x=df_before.index,
open=df_before['Open'],
close=df_before['Close'],
low=df_before['Low'],
high=df_before['High'],
increasing_line_color='green', decreasing_line_color='red', name='HRC Price'),row=1, col=1,)
fig.add_trace(go.Candlestick(x=df_last.index,
open=df_last['Open'],
close=df_last['Close'],
low=df_last['Low'],
high=df_last['High'],
increasing_line_color='purple', decreasing_line_color='blue', name='HRC Price'),row=1, col=1,)
Using some sample data, I get the following result: