Plotly - add_hline 来自指定的蜡烛

时间:2021-07-06 22:36:44

标签: pandas plotly

我正在尝试添加从 candleOfInterest ('2020-03-21') 开始的水平线。

我可以使用 fig.add_hline(y=orh) 添加,但如何将 x 值设置为从 candleOfInterest 开始并在“2020-03-31”结束?

enter image description here

代码

import pandas as pd
import numpy as np
import plotly.graph_objects as go

def genMockDataFrame(days,startPrice,colName,startDate,seed=None): 
   
    periods = days*24
    np.random.seed(seed)
    steps = np.random.normal(loc=0, scale=0.0018, size=periods)
    steps[0]=0
    P = startPrice+np.cumsum(steps)
    P = [round(i,4) for i in P]

    fxDF = pd.DataFrame({ 
        'ticker':np.repeat( [colName], periods ),
        'date':np.tile( pd.date_range(startDate, periods=periods, freq='H'), 1 ),
        'price':(P)})
    fxDF.index = pd.to_datetime(fxDF.date)
    fxDF = fxDF.price.resample('D').ohlc()
    fxDF.columns = [i.title() for i in fxDF.columns]
    return fxDF


df = genMockDataFrame(15,1.1904,'eurusd','19/3/2020',seed=157)


candleOfInterest = '2020-03-21'

#open range high and low
orh = df.loc[candleOfInterest]["High"]
orl = df.loc[candleOfInterest]["Low"]

fig = go.Figure(data=[go.Candlestick(x=df.index,

                open=df['Open'],
                high=df['High'],
                low=df['Low'],
                close=df['Close'])])

fig.add_hline(y=orh)
fig.add_hline(y=orl)


fig.show()

1 个答案:

答案 0 :(得分:2)

您可以在每个水平线段的起点和终点之间使用 go.Scatter,参数 mode='lines'showlegend=False 取决于您是希望这些注释显示在图例中还是不是。

fig.add_trace(go.Scatter(x=[candleOfInterest, '2020-03-31'], y=[orh]*2, mode='lines', line=dict(color='black'), showlegend=False))
fig.add_trace(go.Scatter(x=[candleOfInterest, '2020-03-31'], y=[orl]*2, mode='lines', line=dict(color='black'), showlegend=False))

输出: enter image description here