Python Plotly How to remove datetime gaps in candle stick chart?
Asked Answered
T

4

10

I am trying to remove the datetime gaps in my candlestick (the gaps are the time periods when the stock market is closed, hence there are not data). Can't seem to find a good solution for using plotly graph object. Is there a feasible way to do so?

enter image description here

My code is as follows (using plotly graph object):

import dash
import dash_core_components as dcc
import dash_table
import pandas as pd
import dash_html_components as html
import numpy as np
from dash.dependencies import Output, Input, State
import plotly.graph_objects as go
import yfinance as yf
import plotly.express as px
from datetime import datetime, timedelta
from pytz import timezone
import dash_bootstrap_components as dbc

df= yf.Ticker('aapl')
df = df.history(interval="5m",period="5d")
df["Datetime"] = df.index

trace1 = {
    'x': df.Datetime,
    'open': df.Open,
    'close': df.Close,
    'high': df.High,
    'low': df.Low,
    'type': 'candlestick',
    'name': 'apple,
    'showlegend': False
    }

data = [trace1]

# Config graph layout
layout = go.Layout({
        'title': {
            'text': str(input_value) + ' Stock',
            'font': {
                'size': 15
            }
        },
        'plot_bgcolor': '#2E2E2E'
    })
fig = go.Figure(data=data, layout=layout)
fig.update_layout(xaxis_rangeslider_visible=False)

if __name__ == '__main__':
    app.run_server(debug=True)
Trudietrudnak answered 7/9, 2020 at 15:15 Comment(0)
W
5

You can set rangebreaks option:

  1. you must find missing values(holiday,weekend,closed days etc.)
    You can use this two lines code

  2. Place the fig.update before fig.show().

    alldays =set(df.Datetime[0]+timedelta(x) for x in range((df.Datetime[len(df.Datetime)-1]- df.Datetime[0]).days))
    missing=sorted(set(alldays)-set(df.Datetime))
    
    fig.update_xaxes(rangebreaks=[dict(values=missing)])
    
Weedy answered 18/10, 2022 at 8:12 Comment(1)
Works perfrect to me! thanksSloat
F
4

You can achieve this by rangebreaks in plotly.

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.30am-4pm
            # 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()

here's Plotly's doc.

Florrie answered 10/1, 2021 at 21:43 Comment(2)
I tried doing it here but it isn't working. #71881139Lollapalooza
Which points are not working? I have confirmed that it is continuous in my environment.Parkins
L
2

TLDR: I was stuck with same problem and couldn't found any solution from the plotly documentation. Only suggestion I found on plotly R community is to make the x axis as category instead of datetime. Still I couldn't make it work as the fig.layout() has no such property available.

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")

This should resolve issue the datetime gaps.

Lefton answered 25/12, 2020 at 12:36 Comment(1)
index doesn't need .dt if it's already in datetime format.Walleye
C
1

We can set rangebreaks option:

  1. fill nan where we have gaps (i.e. reindexing the dataframe);
  2. create datebreaks for all nan values;
  3. 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)])
Carty answered 10/7, 2021 at 0:14 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.