pythonmplfinancepandas-ta

Adding ichimoku to mplfinance chart


ichimoku data is calculated with pandas_ta and i want to add them to ETH chart with mplfinance.

import pandas as pd
import pandas_ta as ta
import mplfinance as mpl
import matplotlib.pyplot as plt

df=pd.read_csv('.../ETH-USD.csv',index_col=0,parse_dates=True)
df_org=df.copy()

new_names = {
    'ISA_9': 'tenkan_sen', 
    'ISB_26': 'kijun_sen', 
    'ITS_9': 'senkou_span_a', 
    'IKS_26': 'senkou_span_b', 
    'ICS_26': 'chikou_span'
}

ich= ta.ichimoku(df['High'], df['Low'], df['Close'],senkou=True)[0].rename(columns=new_names)
df=pd.concat([df,ich]).drop(columns=['senkou_span_a','senkou_span_b'])

The problem is that when i add the ichimoku to the chart with mpl.plot method, the result would't be satisfied because the (tenkan_sen,kijun_sen and chikou_span) data is shifted to the right.

fig=mpl.figure(figsize=(12,5))
ax = fig.add_subplot(1,1,1)
apds =[mpl.make_addplot(df.tenkan_sen,color='blue',ax=ax),
       mpl.make_addplot(df.kijun_sen,color='r',ax=ax),
       mpl.make_addplot(df.chikou_span,color='green',ax=ax),]

mpl.plot(df,type='candle',style='yahoo',addplot=apds,ax=ax)

image_result (mplfinance chart)

i think the problem is with the Null value with the shifted ichimoku data. i would appreciate for anyone who helps me to fix this issue....

I used matplotlib and it can handle thenull value in plotting, But the goal is to plot the data into mplfinance.....


Solution

  • The problem is in your pd.concat(). You have to add axis=1

    df=pd.concat([df,ich],axis=1).drop(columns=['senkou_span_a','senkou_span_b'])
    

    That should do the trick.


    That said, note that you do not have to create subplots and access the Axes objects. Mplfinance will do that for you. As a general rule, avoid contact with the Axes objects when using mplfinance, unless there is no other way to accomplish what you are trying to do. This will keep your code simpler, and give you the full benefits of mplfinance:

    import pandas as pd
    import pandas_ta as ta
    import mplfinance as mpl
    
    df=pd.read_csv('ETH-USD.csv',index_col=0,parse_dates=True)
    #df_org=df.copy()
    
    new_names = {
        'ISA_9': 'tenkan_sen', 
        'ISB_26': 'kijun_sen', 
        'ITS_9': 'senkou_span_a', 
        'IKS_26': 'senkou_span_b', 
        'ICS_26': 'chikou_span'
    }
    
    ich= ta.ichimoku(df['High'], df['Low'], df['Close'],senkou=True)[0].rename(columns=new_names)
    df=pd.concat([df,ich],axis=1).drop(columns=['senkou_span_a','senkou_span_b'])
    
    apds =[mpl.make_addplot(df.tenkan_sen,color='blue'),
           mpl.make_addplot(df.kijun_sen,color='r'),
           mpl.make_addplot(df.chikou_span,color='green')]
    
    mpl.plot(df,type='candle',style='yahoo',addplot=apds)
    
    

    The result:

    enter image description here