python Matplotlib candlestick plot works only on daily data, not for intraday

五迷三道 提交于 2020-01-03 02:14:06

问题


I'm trying to plot candlestick data using matplotlib. Starting from 1 minute data I group them using pd.Timegrouper in various time frame , from 5minute to daily, but plot only works on daily data. Below you can find a sample of the 1 minute data i'm using:

data_indexed_5M = data_indexed.groupby([pd.TimeGrouper(freq=pd.offsets.Minute('5'))]).agg({'<LOW>': lambda s: s.min(), 
                                     '<HIGH>': lambda s: s.max(),
                                     '<OPEN>': lambda s: s[0],
                                     '<CLOSE>': lambda s: s[-1]})

ata_indexed_Daily = data_indexed.groupby([pd.TimeGrouper(freq='D')]).agg({'<LOW>': lambda s: s.min(), 
                                     '<HIGH>': lambda s: s.max(),
                                     '<OPEN>': lambda s: s[0],
                                     '<CLOSE>': lambda s: s[-1]})

data_indexed_Daily['Date2'] = data_indexed_Daily['dateTime'].apply(lambda d: mdates.date2num(d.to_pydatetime()))
data_indexed_Daily = data_indexed_Daily.set_index('dateTime')

data_indexed_5M['Date2'] = data_indexed_5M['dateTime'].apply(lambda d: mdates.date2num(d.to_pydatetime()))
data_indexed_5M = data_indexed_5M.set_index('dateTime')


def plotWithMatplot(dataevento):
    deltatime = timedelta(minutes=100*5)  #...(days=100) for daily plot

    pre_data = dataevento - deltatime
    post_data= dataevento + deltatime

    data_slice = data_indexed_5M.loc[pre_data:post_data]   #data_indexed_Daily --> for daily plot

    tuples = [tuple(x) for x in     data_slice[['Date2','<OPEN>','<HIGH>','<LOW>','<CLOSE>']].values]

    fig, ax = plt.subplots()
    ax.xaxis_date()
    ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d %H:%M:"))    

    plt.xticks(rotation=45)
    plt.xlabel("Date")
    plt.ylabel("Price")
    plt.title("EURUSD 5M")
    candlestick_ohlc(ax, tuples, width=.6, colorup='g', alpha =.4);

    plt.show()

but then when i plot same event on the Daily and 5 minute (ot any other intraday time frame) i obtain following results:

Daily (good result):

Intraday (bad result):


回答1:


It seems the undocumented width argument to candlestick_ohlc is the key. Multiply it by the fraction of a day between each of your data points. Since your data is in minute increments, this should do:

candlestick_ohlc(ax, tuples, width=.6/(24*60), colorup='g', alpha =.4);

Note this turns out to be an FAQ, though the links are not obvious. See:

  • Charting Candlestick_OHLC one minute bars with Pandas and Matplotlib
  • Matplotlib Candlestick (Intraday) Chart is One Big Blob
  • Matplotlib candlestick in minutes


来源:https://stackoverflow.com/questions/36823880/python-matplotlib-candlestick-plot-works-only-on-daily-data-not-for-intraday

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!