Search code examples
pythondatetimematplotlibpandas-datareader

Two time series won't graph on same x axis (date format issue)?


I'm trying to import data from both iex and FRED. Although both time series are over the same time period, when I graph them together the data does not show up correctly on the same x axis. I suspect this is due to differences between how to iex dates are formatted and how the FRED dates are formatted.

Code below:

import matplotlib.pyplot as plt

import pandas as pd
from pandas_datareader.data import DataReader 

from datetime import date 

start = date(2016,1,1)
end = date(2016,12,31)

ticker = 'AAPL'

data_source = 'iex'

stock_prices = DataReader(ticker, data_source, start, end)

print(stock_prices.head())
stock_prices.info()

stock_prices['close'].plot(title=ticker)
plt.show()

series = 'DCOILWTICO'
start = date(2016,1,1)
end = date(2016,12,31)
oil = DataReader(series,'fred',start,end)
print(oil.head())
oil.info()

data = pd.concat([stock_prices[['close']],oil],axis=1)
print(data.head())

data.columns = ['AAPL','Oil Price']
data.plot()
plt.show()

Solution

  • Using join instead of pd.concat will give you what you want:

    data = stock_prices[['close']].join(oil)
    

    enter image description here

    Main issue with pd.concat is that the index of your data are not aligned, therefore the weird stiched DataFrame. pd.join will take care of the misalignment