【问题标题】:Python Plotly How to remove datetime gaps in candle stick chart?Python Plotly 如何删除烛台图表中的日期时间间隔?
【发布时间】:2020-09-07 15:15:33
【问题描述】:

我正在尝试消除烛台中的日期时间间隔(这些间隔是股市收盘的时间段,因此没有数据)。似乎找不到使用绘图对象的好解决方案。有没有可行的办法?

我的代码如下(使用 plotly graph 对象):

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)

【问题讨论】:

    标签: python plotly-dash python-datetime yahoo-finance candlestick-chart


    【解决方案1】:

    您可以通过 plotly 中的 rangebreaks 来实现这一点。

    下面是隐藏交易时间和周末以外的代码。

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

    这里是Plotly's doc

    【讨论】:

      【解决方案2】:

      TLDR: 我遇到了同样的问题,无法从 plotly 文档中找到任何解决方案。我在 plotly R 社区找到的唯一建议是将 x 轴作为类别而不是日期时间。我仍然无法让它工作,因为fig.layout() 没有这样的可用属性。

      对于您的代码,将 Datetime 更改为字符串以将其强制为无 datetime 类型轴

      df["Datetime"] = df.index.dt.strftime("%Y/%m/%d %H:%M")
      

      这应该可以解决日期时间间隔问题。

      【讨论】:

        【解决方案3】:

        我们可以设置rangebreaks选项:

        1. 填补nan我们有差距的地方(即重新索引数据框);
        2. 为所有nan 值创建datebreaks
        3. xaxes config 上设置rangebreak 值
        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)])
        

        【讨论】:

          猜你喜欢
          • 2014-04-10
          • 1970-01-01
          • 1970-01-01
          • 2023-04-02
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多