jcsun
jcsun

Reputation: 197

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

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 sample:** (pandas dataframe)

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

enter image description here

Intraday (bad result):

enter image description here

Upvotes: 2

Views: 1350

Answers (1)

Heath Raftery
Heath Raftery

Reputation: 4169

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:

Upvotes: 2

Related Questions