我试图制作一个图表,绘制股票价格的时间序列数据。然而,市场仅在 9:30-16:00 开放,但图表会自动绘制市场不开放的时间。这导致图表上的数据点之间有很大的线条,这在我所附的图片中应该更加明显。如果有人可以帮助解决这个问题,我将不胜感激。
import pandas as pd
import datetime as dt
import yfinance as yf
import plotly.graph_objects as go
#Initial data & get dataframe
start = dt.date(2022,3,1)
end = dt.date(2022,3,7)
ticker = 'SPY'
df = yf.download(ticker,start,end,progress=False,interval='1m')
#Make Graph
fig = go.Figure()
fig.add_trace(go.Scatter(
x=df.index,
y=df['Adj Close'],
mode='lines'))
fig.show()
您需要创建范围断点来创建不连续的 x 轴刻度。这里我使用bounds方法来做到这一点。
import pandas as pd
import datetime as dt
# !pip install yfinance
import yfinance as yf
import plotly.graph_objects as go
import numpy as np
#Initial data & get dataframe
start = dt.date(2023,4,15)
end = dt.date(2023,4,21)
ticker = 'SPY'
df = yf.download(ticker,start,end,progress=False,interval='1m')
def calc_rangebreak(time_series:pd.Series):
""" Caculate the bounds of missing data
returns: list of dictionaries suitable for plotly rangebreak
"""
timedeltas = time_series.diff()
if len(time_series) < 2:
return []
# find index of the gaps where it is 50% greater than the median time interval
missing_times = np.where([timedeltas > timedeltas.median()*1.5])[1]
#Tiny offset to account for numerical precision
off = pd.Timedelta(seconds=0.0001)
rb = [{'bounds': [str((time_series.iloc[t-1]+off)), str((time_series.iloc[t]-off))]} for t in missing_times]
return rb
#Make Graph
fig = go.Figure()
fig.add_trace(go.Scatter(
x=df.index,
y=df['Adj Close'],
mode='lines'))
rangebreak_bounds = calc_rangebreak(df.index.to_series())
fig.update_xaxes(rangebreaks=rangebreak_bounds)
fig.show()
非常感谢您的帮助! 您的决定不仅帮助我消除了价格差距,还帮助我消除了下面子图指标上的差距。 简单的决定:fig.update_layout(xaxis={'type':'category'}) - 仅消除价格差距。因此,如果您使用下面的一些指标,它会留下缺口。