Search code examples
pythonmatplotlibyfinance

Trying to plot Earnings and Stock price in the same graph


I'm trying to plot the stock price and the earnings on the graph but for some reason I'm getting this:

Graph1

Please see my code below:

import matplotlib.pyplot as plt
import yfinance as yf
import pandas
import pandas_datareader
import matplotlib

t = yf.Ticker("T")

df1 = t.earnings
df1['Earnings'].plot(label = 'earnings', figsize = (15,7), color='green')
print(df1)

df2 = t.history(start = '2018-01-01', end = '2021-01-01', actions = False, rounding = True)
df2['Close'].plot(label = 'price', figsize = (15,7),color = 'blue')

plt.show()

Could someone help me?

Thanks in advance.


Solution

  • Plotting in pandas is easy to create graphs, but if you try to overlay them with time series data, as in this example, you will encounter problems. There are many approaches, but the method that I find easiest is to convert the data level to the gregorian calendar managed by matplotlib and create the graph. Finally, you can either convert it to your preferred formatting, etc., or use the automatic formatter and locator.

    import matplotlib.pyplot as plt
    import matplotlib.dates as mdates
    import yfinance as yf
    import pandas as pd
    
    t = yf.Ticker("T")
    
    df1 = t.earnings
    df1.index = pd.to_datetime(df1.index, format='%Y')
    df1.index = mdates.date2num(df1.index)
    ax = df1['Earnings'].plot(label='earnings', figsize=(15, 7), color='green')
    
    df2 = t.history(start='2018-01-01', end='2021-01-01', actions=False, rounding=True)
    df2.index = mdates.date2num(df2.index)
    df2['Close'].plot(label='price',  ax=ax,color='blue', secondary_y=True)
    
    #ax.set_xticklabels([x.strftime('%Y-%m') for x in mdates.num2date(df2.index)][::125])
    
    locator = mdates.AutoDateLocator()
    formatter = mdates.ConciseDateFormatter(locator)
    
    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(formatter)
    
    plt.show()
    

    enter image description here