Search code examples
pythonpython-3.6pandas-datareader

How to create a dataframe from dictionary with details of stocks


I need to create a dataframe with closing prices of the stocks of the companies that I have given in the list.

import pandas_datareader.data as web
from pandas import Series,DataFrame
from datetime import datetime
start = datetime(2017,1,1)
end = datetime(2017,1,12)    
f = web.DataReader(['BP','CVX'], 'iex',start,end)

f in the code is returning a dictionary as shown below. How can I get the closing price of the stocks of listed companies in a DataFrame.

{'BP': open high low close volume date
2017-01-03 38.100 38.1218 37.79 38.00 8779164 2017-01-04 38.045 38.3400 37.94 38.29 6883266 2017-01-05 38.140 38.6800 38.14 38.57 6505685 2017-01-06 38.160 38.1900 37.85 37.91 5800932 2017-01-09 37.580 37.6500 37.31 37.31 5533626 2017-01-10 37.250 37.4500 37.11 37.11 3922015 2017-01-11 37.200 37.6550 37.06 37.55 4422586 2017-01-12 37.990 38.0000 37.66 37.76 4698473, 'CVX': open high low close volume date
2017-01-03 118.38 119.00 116.59 117.85 7404774 2017-01-04 118.41 118.65 117.60 117.82 6679943 2017-01-05 118.00 118.48 116.72 117.31 5928637 2017-01-06 117.45 117.58 116.38 116.84 4762474 2017-01-09 116.29 116.36 115.11 115.84 6891790


Solution

  • I think you need concat with parameter axis=1 for concatenate along columns and select by xs second level of MultiIndex in columns:

    df = pd.concat(f, axis=1).xs('close', axis=1, level=1)
    print (df)
                   BP     CVX
    date                     
    2017-01-03  38.00  117.85
    2017-01-04  38.29  117.82
    2017-01-05  38.57  117.31
    2017-01-06  37.91  116.84
    2017-01-09  37.31  115.84
    2017-01-10  37.11     NaN
    2017-01-11  37.55     NaN
    2017-01-12  37.76     NaN
    

    Or concatenate along indices, but get MultiIndex in indices:

    df = pd.concat(f)['close']
    print (df)
         date      
    BP   2017-01-03     38.00
         2017-01-04     38.29
         2017-01-05     38.57
         2017-01-06     37.91
         2017-01-09     37.31
         2017-01-10     37.11
         2017-01-11     37.55
         2017-01-12     37.76
    CVX  2017-01-03    117.85
         2017-01-04    117.82
         2017-01-05    117.31
         2017-01-06    116.84
         2017-01-09    115.84
    Name: close, dtype: float64