ASH
ASH

Reputation: 20342

How to convert a list to a dataframe without dropping all data?

I am testing the code below.

import pandas as pd
from pandas_datareader import data as wb

tickers = ['SBUX', 'AAPL', 'MSFT']
AllData = []

for ticker in tickers:
    print('appending prices for ' + ticker)
    tickers = wb.DataReader(ticker,start='2018-7-26',data_source='yahoo')
    AllData.append(tickers)

AllData = pd.DataFrame(AllData)
print(AllData)

When I convert the list to a dataframe, everything gets dropped.

Also, I'm trying to get the ticker variable inserted into the relevant spot, so I can tell which one is which. I'd like the final result to look like this.

   date         ticker   adj_close
0  2018-02-13   MSFT     164.34
1  2018-02-12   MSFT     162.71
...
265  2018-02-13   SBUX     81.30
266  2018-02-12   SBUX     82.11

How can I do that? TIA.

Upvotes: 2

Views: 110

Answers (1)

Alexander
Alexander

Reputation: 109636

There are a couple of issues with your code.

First, you are iterating through tickers via for ticker in tickers: but you then reassign that variable in the loop via tickers = wb.DataReader(...). Never change the object over which you are iterating. Although this actually does not cause an issue in this case, it is clearly undesirable.

Second, AllData is a list containing three dataframes, none of which have a reference to their relevant ticker. You could concatenate at this stage, but you should first include the ticker as an additional column to the dataframe via .assign(ticker).

price_data = []
for ticker in tickers:
    prices = wb.DataReader(ticker, start='2018-7-26', data_source='yahoo')[['Adj Close']]
    price_data.append(prices.assign(ticker=ticker)[['ticker', 'Adj Close']])

df = pd.concat(price_data)
>>> df
           ticker   Adj Close
Date                         
2018-07-26   SBUX   50.324104
2018-07-27   SBUX   51.008789
2018-07-30   SBUX   50.764256
...

>>> df.set_index('ticker', append=True).unstack('ticker')
             Adj Close                       
ticker            AAPL        MSFT       SBUX
Date                                         
2018-07-26  191.298080  107.868378  50.324104
2018-07-27  188.116501  105.959373  51.008789
2018-07-30  187.062546  103.686295  50.764256
...

Upvotes: 3

Related Questions