For your code change the Datetime to string to force it to none datetime type axis
df["Datetime"] = df.index.dt.strftime("%Y/%m/%d %H:%M")
Below is the code to hide outside trading hours and weekends.
fig = go.Figure(data = [go.Candlestick(x = df['date'], open = df['Open'], high = df['High'], low = df['Low'], close = df['Close'])]) fig.update_xaxes( rangeslider_visible = True, rangebreaks = [ # NOTE: Below values are bound(not single values), ie.hide x to y dict(bounds = ["sat", "mon"]), # hide weekends, eg.hide sat to before mon dict(bounds = [16, 9.5], pattern = "hour"), # hide hours outside of 9.30 am - 4 pm # dict(values = ["2019-12-25", "2020-12-24"]) # hide holidays(Christmas and New Year 's, etc)] ) fig.update_layout( title = 'Stock Analysis', yaxis_title = f '{symbol} Stock' ) fig.show()
- fill
nan
where we have gaps (i.e. reindexing the dataframe); - create
datebreaks
for allnan
values; - set rangebreak values on
xaxes
config
begin_date, end_date = [df.iloc[0].name, df.iloc[-1].name]
df = df.reindex(pd.date_range(begin_date, end_date, freq = 'D'))
datebreaks = df['Close'][df_plot['Close'].isnull()].index
fig.update_xaxes(rangebreaks = [dict(values = datebreaks)])
Time series can be represented using either plotly.express functions (px.line, px.scatter, px.bar etc) or plotly.graph_objects charts objects (go.Scatter, go.Bar etc). For more examples of such charts, see the documentation of line and scatter plots or bar charts.,The data range can be set manually using either datetime.datetime objects, or date strings.,Note: a known limitation of this feature is that it does not support scattergl traces. When using this feature on plots with more than a few hundred data points with px.scatter or px.line or px.area, you may need to pass in render_mode="svg" to ensure that the underlying trace type is scatter and not scattergl.,Any kind of cartesian chart can be placed on date axes, for example this bar chart of relative stock ticker values.
# Using plotly.express import plotly.express as px df = px.data.stocks() fig = px.line(df, x = 'date', y = "GOOG") fig.show()
# Using graph_objects import plotly.graph_objects as go import pandas as pd df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv') fig = go.Figure([go.Scatter(x = df['Date'], y = df['AAPL.High'])]) fig.show()
import plotly.express as px
df = px.data.stocks(indexed = True) - 1
fig = px.bar(df, x = df.index, y = "GOOG")
fig.show()
import plotly.express as px
df = px.data.stocks(indexed = True) - 1
fig = px.area(df, facet_col = "company", facet_col_wrap = 2)
fig.show()
import plotly.express as px
df = px.data.stocks()
fig = px.line(df, x = "date", y = df.columns,
hover_data = {
"date": "|%B %d, %Y"
},
title = 'custom tick labels')
fig.update_xaxes(
dtick = "M1",
tickformat = "%b\n%Y")
fig.show()
import plotly.express as px
df = px.data.stocks()
fig = px.line(df, x = "date", y = df.columns,
hover_data = {
"date": "|%B %d, %Y"
},
title = 'custom tick labels with ticklabelmode="period"')
fig.update_xaxes(
dtick = "M1",
tickformat = "%b\n%Y",
ticklabelmode = "period")
fig.show()
This Answer says xaxis=dict(type = "category") but I don't know where to use that argument (fresh from matplotlib only for candlesticks),There are other answers to Plotly: How to remove empty dates from x axis that will suit your use-case better. This can be a bit tricky for 5 minute intervals. Just consider the formatting of your timestamps, and follow these steps carefully:,find out which of your observations that occur in that complete timeline,isolate the rest of the dates and include them in the rangebreaks attribute of the x-axis
Following some Links, I found that running the below code on Day
data, I can easily remove gaps:
dt_all = pd.date_range(start = stocks.iloc[0, 0], end = stocks.iloc[-1, 0], freq = f '{freq}min')
dt_obs = [d.strftime("%Y-%m-%d %H:%M:%S") for d in pd.to_datetime(stocks.DATE)]
dt_breaks = [d
for d in dt_all.strftime("%Y-%m-%d %H:%M:%S").tolist() if not d in dt_obs
]
range_selector = dict(buttons = list([
dict(count = 5, label = '5Min', step = 'minute', stepmode = 'backward'),
dict(count = 15, label = '15Min', step = 'minute', stepmode = 'backward'),
dict(count = 75, label = '75M', step = 'minute', stepmode = 'backward'),
dict(count = 1, label = '1D', step = 'day', stepmode = 'backward'),
dict(step = 'all')
]))
candle = go.Figure(data = [go.Candlestick(opacity = 0.9, x = stocks['Date'], name = 'X',
open = stocks['Open'],
high = stocks['High'],
low = stocks['Low'],
close = stocks['Close']), ])
candle.update_xaxes(
title_text = 'Date',
rangeslider_visible = True,
rangebreaks = [dict(values = dt_breaks)],
range_selector = range_selector)
But I have 5 Minute Data as:
DATE OPEN HIGH LOW CLOSE 52 W H 52 W L SYMBOL 374 2022 - 01 - 14 15: 25: 00 + 05: 30 720.25 722.35 720.25 721.55 NaN NaN BHARTIARTL 373 2022 - 01 - 14 15: 20: 00 + 05: 30 720.30 720.45 719.45 720.25 NaN NaN BHARTIARTL 372 2022 - 01 - 14 15: 15: 00 + 05: 30 720.75 720.90 720.15 720.30 NaN NaN BHARTIARTL 371 2022 - 01 - 14 15: 10: 00 + 05: 30 720.35 720.90 720.20 720.70 NaN NaN BHARTIARTL 370 2022 - 01 - 14 15: 05: 00 + 05: 30 720.70 720.90 720.05 720.20 NaN NaN BHARTIARTL ........................... 4 2022 - 01 - 10 09: 35: 00 + 05: 30 706.05 707.15 705.65 706.55 NaN NaN BHARTIARTL 3 2022 - 01 - 10 09: 30: 00 + 05: 30 705.90 706.40 705.05 706.05 NaN NaN BHARTIARTL 2 2022 - 01 - 10 09: 25: 00 + 05: 30 707.10 707.95 705.60 705.60 NaN NaN BHARTIARTL 1 2022 - 01 - 10 09: 20: 00 + 05: 30 709.00 709.40 706.15 707.10 NaN NaN BHARTIARTL 0 2022 - 01 - 10 09: 15: 00 + 05: 30 705.40 709.00 705.40 708.55 NaN NaN BHARTIARTL
Essential code elements:
# grab first and last observations from df.date and make a continuous date range from that dt_all = pd.date_range(start = df['Date'].iloc[0], end = df['Date'].iloc[-1], freq = '5min') # check which dates from your source that also accur in the continuous date range dt_obs = [d.strftime("%Y-%m-%d %H:%M:%S") for d in df['Date']] # isolate missing timestamps dt_breaks = [d for d in dt_all.strftime("%Y-%m-%d %H:%M:%S").tolist() if not d in dt_obs ] # adjust xaxis for rangebreaks fig.update_xaxes(rangebreaks = [dict(dvalue = 5 * 60 * 1000, values = dt_breaks)])
Complete code:
import plotly.graph_objects as go from plotly.subplots import make_subplots import pandas as pd import numpy as np # sample data df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv').tail(90) df = df[df.columns[: 6]] df['Date'] = pd.date_range("2018-01-01", periods = len(df), freq = "5min") df.columns = ['Date', 'Open', 'High', 'Low', 'Close', 'Volume'] df = df.tail(10) # remove some data np.random.seed(0) remove_n = 4 drop_indices = np.random.choice(df.index, remove_n, replace = False) df = df.drop(drop_indices) # plotly candlestick figure fig = go.Figure(data = [go.Candlestick( x = df['Date'], open = df['Open'], high = df['High'], low = df['Low'], close = df['Close'], )]) # grab first and last observations from df.date and make a continuous date range from that dt_all = pd.date_range(start = df['Date'].iloc[0], end = df['Date'].iloc[-1], freq = '5min') # check which dates from your source that also accur in the continuous date range dt_obs = [d.strftime("%Y-%m-%d %H:%M:%S") for d in df['Date']] # isolate missing timestamps dt_breaks = [d for d in dt_all.strftime("%Y-%m-%d %H:%M:%S").tolist() if not d in dt_obs ] dt_breaks = pd.to_datetime(dt_breaks) fig.show() fig.update_xaxes(rangebreaks = [dict(dvalue = 5 * 60 * 1000, values = dt_breaks)]) print(fig.layout.xaxis.rangebreaks) fig.show()
Candlestick Chart in Python (mplfinance, plotly, bokeh, bqplot & cufflinks),Plotly is another Python library that provides functionality to create candlestick charts. It allows us to create interactive candlestick charts.,The first library which we'll explore for plotting candlestick charts in Python is mplfinance. It used to be available as a matplotlib module earlier but now it has moved out and has become an independent library. We can generate static candlestick charts using it.,Below we have explained another example of creating a candlestick chart using cufflinks. We have added Bollinger bands, simple moving average, and relative strength index studies to the chart as well this time.
import mplfinance as fplt
print("MPLFinance Version : {}".format(fplt.__version__))
MPLFinance Version: 0.12 .3 a3
import plotly
print("Plotly Version : {}".format(plotly.__version__))
Plotly Version: 4.5 .2
import bokeh
print("Bokeh Version : {}".format(bokeh.__version__))
Bokeh Version: 2.0 .2