Skip to content

ENH: Add ohlc / candlestick plotting option for DataFrame #783

Closed

Description

@wesm

Not sure if possible to do in a generic way. But maybe will make sense once we have an OHLC aggregator implemented

Activity

  1. esthers commented on Feb 17, 2013

    @esthers

    Yes please implement candlestick plotting for DataFrame. It is so nice to make instant plots of financial data from yahoo with pandas but candelstick charts for many, like me, really are a must to analyze the data.

  2. wesm commented on Feb 17, 2013

    @wesm
    MemberAuthor

    I'd be happy to accept a pull request for this

  3. dalejung commented on Feb 19, 2013

    @dalejung
    Contributor

    I have this here:
    http://nbviewer.ipython.org/4982660/

    In order to support financial data I send mpl an ordinal index, essential np.arange(len(df.index)) and draw the ticks with a Locator/Formatter. Doing this with DatetimeIndex actually speeds up plotting #1579 and gets rid of weekend gaps. However, a side effect of this is that you have to keep the previous data around for future plots on the same axes. For that I have a Figure class that handles translating any future plots into an ordinal index. I chose to keep all plotted data around for plot specific fillnas, but that's probably unnecessary.

    I'd like to merge this stuff in but I'm not sure how compatible it is. trtools.charting is fairly heavy handed in assuming you're not touching matplotlib directly. Mixing ordinal and datetime index plots on the same axes wouldn't work.

    The module itself is self-contained outside of a small column_grep utility, so it can be made to be cleanly import-able as an add-on.

  4. esthers commented on Feb 20, 2013

    @esthers

    @dalejung, if you could find a way to merge your code it would be greatly appreciated.

  5. woodb commented on Jul 9, 2013

    @woodb

    @dalejung, have you had any luck implementing this?

    I agree that importing a big library for something like a candlestick plot seems heavy handed, maybe there's a lighter weight way we can get this going.

  6. woodb commented on Jul 9, 2013

    @woodb

    @wesm, how do you think this should work syntactically?

    Rolling this functionality into plot might be neat.

    For example, if the DataFrame has a datetime index and columns "open", "high", "low", "close", and a DataFrame.plot() is called, would it make sense for the result to be a candlestick plot by default?

    Would this be better as a kwarg for DataFrame.plot() or as a separate function (e.g. ohlc_plot)

  7. dalejung commented on Jul 9, 2013

    @dalejung
    Contributor

    @woodb Sort of. I split out the charting work into its own project https://github.com/dalejung/ts-charting. The heaviness was due to me keeping the plotted data around in a DataFrame. I was doing this to use the DataFrame.__setitem__'s auto-reindexing to keep the plots aligned. I'm a bit smarter now and keep only index around.

    I think ts-charting should be straight-forward to merge into pandas, at least a portion of it. When I get the time I'll open a PR.

  8. woodb commented on Jul 9, 2013

    @woodb

    @dalejung Prima, let me know if you need any help, I've got some time here and there.

  9. dalejung commented on Jul 9, 2013

    @dalejung
    Contributor

    @woodb Actually, a smaller first pass could be done with http://nbviewer.ipython.org/5864433. That uses the matplotlib datetime handling.

    ts-charting converts the DatetimeIndex to ints and translates the labels back with a custom Formatter. I'm pretty sure this could be made pandas compatible by always checking the current ax for our TimestampFormatter and reindexing to the current x-axis. I suppose the Figure and Grapher classes would need their methods refactored into flat functions or hidden away onto the Formatter.

    Converting to an int-index is better but it means that every plot to that ax will need the translation. It's convenient to call fig.hl_span("2012-01-02", "2012-01-05"), but the base matplotlib method would not work ax.axvspan("2012-01-02", "2012-01-05") unless I monkey patched it.

    Actually, thinking about it more. I dunno if that's acceptable for inclusion into pandas. Part of the reason for the Figure abstraction is to create a namespace where all methods are aware of the Datetime -> int translation. hm.

    Go Gators??!

  10. phobson commented on Dec 13, 2013

    @phobson

    Thought y'all might be interesting in this:
    matplotlib/matplotlib#2643

    If merged, you'll be able to feed a matplotlib axes object a list of dictionaries "stats" describing the boxplots via a bxp method

  11. phobson commented on Dec 16, 2013

    @phobson

    @y-p -- yeah. What I've heard is that matplotlib.finance will be deprecated in mpl 1.4 and removed by 1.5.

  12. jreback commented on Dec 16, 2013

    @jreback
    Contributor

    @phobson new champion for a combined viz library? (built on pandas of course) :)

  13. jtratner commented on Dec 16, 2013

    @jtratner
    Contributor

    I was discussing this out of band with @olgabot. @mwaskom 's seaborn could be a good candidate (and it already appears to use pandas).

  14. 6 remaining items

  15. removed this from the 0.14.0 milestone on Feb 18, 2014
  16. modified the milestones: 0.16.0, 0.17.0 on Jan 26, 2015
  17. wesm commented on Sep 29, 2016

    @wesm
    MemberAuthor

    Won't fix

  18. modified the milestones: , on Sep 30, 2016
  19. femtotrader commented on Oct 12, 2016

    @femtotrader

    Some basic code to display daily OHLCV data

    import pandas as pd
    from pandas.compat import StringIO
    
    import matplotlib.pyplot as plt
    from matplotlib.finance import candlestick_ohlc
    import matplotlib.dates as mdates
    
    def plot_candlestick(df, ax=None, fmt="%Y-%m-%d"):
        if ax is None:
            fig, ax = plt.subplots()
        idx_name = df.index.name
        dat = df.reset_index()[[idx_name, "Open", "High", "Low", "Close"]]
        dat[df.index.name] = dat[df.index.name].map(mdates.date2num)
        ax.xaxis_date()
        ax.xaxis.set_major_formatter(mdates.DateFormatter(fmt))
        plt.xticks(rotation=45)
        _ = candlestick_ohlc(ax, dat.values, width=.6, colorup='g', alpha =1)
        ax.set_xlabel(idx_name)
        ax.set_ylabel("OHLC")
        return ax
    
    
    data="""Date,Stock,Open,High,Low,Close,Volume
    2016-09-29,KESM,7.92,7.98,7.92,7.97,149400
    2016-09-30,KESM,7.96,7.97,7.84,7.9,29900
    2016-10-04,KESM,7.8,7.94,7.8,7.93,99900
    2016-10-05,KESM,7.93,7.95,7.89,7.93,77500
    2016-10-06,KESM,7.93,7.93,7.89,7.92,130600
    2016-10-07,KESM,7.91,7.94,7.91,7.92,103000"""
    df = pd.read_csv(StringIO(data), index_col='Date', parse_dates=True)
    
    ax = plot_candlestick(df)
    
    print(ax)
    
    plt.tight_layout()
    #plt.savefig("candle.png")
    plt.show()

    candle

    Related SO questions:

  20. jreback commented on Oct 12, 2016

    @jreback
    Contributor
  21. femtotrader commented on Oct 12, 2016

    @femtotrader

    An example of box-plot with such a DataFrame will be nice.

    I tried

    df[["Open", "High", "Low", "Close"]].transpose().plot.box()

    and get

    boxplot

    It doesn't look very well

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions