Search code examples
pandasdataframecandlestick-chartmplfinance

Python datframe plotting


I would like to plot a dataframe in pandas containing candlesticks, both increasing and decreasing candles must all be of the same color, except for some of my choice.

I'm really struggling to find a solution.

I tried mplfinance, plotly, finplot, and I can change the colors of all the candles, but not only change those of some.

If it wasn t possible to modify the colors individually, I would at least like vertical lines to be drawn along the graph in correspondence with the candlesticks.

I can identify the candles affected by both the dataframe index and their time.

Help would be useful, thanks in advance.

some lines of code:

import finplot as fplt

...
    # I receive the data from yahoo finance and save it in the pdOHLCVs dataframe

colorBlue = "#0509fc"

fplt.candle_bear_color = colorBlue
fplt.candle_bull_color = colorBlue
fplt.candle_bull_body_color = colorBlue
fplt.candlestick_ochl (pdOHLCVs [['open', 'close', 'high', 'low']])

    # here I want to be able to change the color for example at candle 12
    # here I want to be able to change the color for example at candle 29
    # here I want to be able to change the color for example at candle 56

fplt.show()

Solution

  • I am not very familiar with plotly and finplot, however (full disclosure) I am the maintainer of mplfinance. Coloring of specific candles in mplfinance is not yet supported, however we have had requests for this and plan to support it in the future.

    In the meantime, this can be done using mplfinance with some extra work. The basic idea is this:

    1. Split your dataframe in two, for the two different colors that you want, each dataframe including only the candles of the color that you want, and NaN values for all other candles.
    2. Create two custom "mplfinance styles", each with the candles only one color, but each style is a different color from the other.
    3. Plot the two dataframes on the same Axes, each with its specified color style.

    Here is some example code. The data for this example can be found here.

    import pandas as pd
    import mplfinance as mpf
    
    # Read in S&P500 November 2019 OHLCV:
    df1 = pd.read_csv('data/SP500_NOV2019_Hist.csv',index_col=0,parse_dates=True)
    df1.drop('Volume',axis=1,inplace=True) # Drop Volume (not needed for this demo)
    
    # Create a DataFrame with the same shape, but all NaN values:
    nc = [float('nan')]*len(df1)  # nc = Nan Column
    df2 = pd.DataFrame(dict(Open=nc,High=nc,Low=nc,Close=nc))
    df2.index = df1.index
    
    # Copy specific values from one DataFrame to the Other
    df2.loc['11/8/2019']  = df1.loc['11/8/2019'].copy()
    df2.loc['11/15/2019'] = df1.loc['11/15/2019'].copy()
    df2.loc['11/21/2019'] = df1.loc['11/21/2019'].copy()
    df2.loc['11/27/2019'] = df1.loc['11/27/2019'].copy()
    
    # Set the same values to NaN back in the original DataFrame:
    df1.loc[ '11/8/2019'] = [float('nan')]*4
    df1.loc['11/15/2019'] = [float('nan')]*4
    df1.loc['11/21/2019'] = [float('nan')]*4
    df1.loc['11/27/2019'] = [float('nan')]*4
    
    # Now make 2 custom styles where the candles are all the same color
    # (But a different color for each style)
    
    # style1 has all candles 'blue'
    m = mpf.make_marketcolors(base_mpf_style='default',up='b',down='b')
    style1 = mpf.make_mpf_style(base_mpf_style='default',marketcolors=m)
    
    # style2 has all candles 'lime'
    m = mpf.make_marketcolors(base_mpf_style='default',up='lime',down='lime')
    style2 = mpf.make_mpf_style(base_mpf_style='default',marketcolors=m)
    
    # Now plot each DataFrame on the same Axes but with different styles:
    # Use returnfig=True to get the Axes and pass to the next call:
    fig, ax = mpf.plot(df1,type='candle',style=style1,returnfig=True)
    mpf.plot(df2,type='candle',style=style2,ax=ax[0])
    mpf.show()
    

    Result of the above code: enter image description here


    By the way, since you mentioned vertical lines, highlighting specific candles with vertical lines is simple with mplfinance's vlines (vertical lines) kwarg:

    ##  Easier just to add vertical lines:
    # Read in S&P500 November 2019 OHLCV:
    df1 = pd.read_csv('data/SP500_NOV2019_Hist.csv',index_col=0,parse_dates=True)
    
    v = dict(vlines=['11/7/2019','11/15/2019','11/21/2019','11/27/2019'],
             alpha=0.3,colors=['lime'],linewidths=[7])
    
    mpf.plot(df1,type='candle',vlines=v)
    

    Result: enter image description here