Search code examples
pythonpandasconcatenationpandas-datareader

Python Pandas concat stock data returns NaN values instead


I am working on a Python Pandas project and got stuck with concat part. Basically, I have retrieved stock data as following

df = data.DataReader(['BAC','C','GS','JPM','MS','WFC'],'morningstar',start,end)

head shows this: df.head()

Then I use pd.concat() to join them, and add the column names with the following

bank_stocks = pd.concat([BAC,C,GS,JPM,MS,WF],axis=1,keys=tickers)
bank_stocks.columns.names = ['Bank Ticker','Stock Info']

but when I look at bank_stocks.head() I have many NaN values:

like this

what I need to get is like this

It might be something very simple, but being a rookie I can't figure it out by myself. Anyone can give me hand out please? Thank you.


Solution

  • There is problem in your concat statement. You need to pass individual data frames that you wish concatenated. As per your requirement you need to concatenate information for each ticker, so each ticker represents a data-frame that needs to be concatenated.

    The correct syntax would be: pd.concat([df.loc['BAC'],df.loc['C'],df.loc['GS'],df.loc['JPM'],df.loc['MS'],df.loc'WF']],axis=1,keys=tickers)

    I believe tickers is defined in your program as some list containing all the ticker symbols.