Goal: highlight regular trading market hours in a plotly chart.
-Using a df with standard datetime and 1 minute intervals. -Regular trading hours = 9:30am EST to 4pm EST —-Incase interested: ——-pre market = 4am to 9:30am ——-post market = 4pm to 8pm
Stack overflow has great links for highlighting weekend data like this: Nevermind that link was just removed by the author as I tried to post it, but it’s too difficult for me to translate that to specific times of day anyway.
CodePudding user response:
This is relatively easy to do using fig.add_vrect()
I built a similar highlighting system for night and day:
time = df.index.get_level_values("time")
# Getting info for plotting the day/night indicator
# time[0].date() picks out 00:00 (midnight) and then we add 6 hours to get 6 am.
start_morning = pd.to_datetime(time[0].date()) pd.Timedelta(
hours=6
)
end_morning = pd.to_datetime(time[-1].date()) pd.Timedelta(
hours=30
)
num_mornings = (end_morning - start_morning).days
# Now we build up the morning times, every day at 6 am
mornings = [
start_morning timedelta(days=x) for x in range(num_mornings)
]
for morning in mornings:
fig.add_vrect(
# Highlighted region starts at 6 am and ends at 6 pm, every day.
x0=morning,
x1=morning timedelta(hours=12),
fillcolor="white",
opacity=0.1,
line_width=0,
)
For you, it would just be a simple matter of adjusting the times. So for instance, for 9:30 am you can use
morning = pd.to_datetime(time[0].date()) pd.Timedelta(hours=9.5)
to get the first day of your data, at 9:30 am. Now in fig.add_vrect()
use
x0= morning
x1= morning timedelta(hours=6.5)
to highlight between 9:30 am and 4 pm.