简体   繁体   中英

Multiplie time-series into dataframe

I need to create a dataframe from multiple stock price time-series. Source of time-series is quandl. My loop creates a dataframe but doesn't add time-series correctly.

import quandl
import datetime
tickers=['MMM','AOS','ABT']

for stock in range(len(tickers)):
    series = (quandl.get("WIKI/" + tickers[stock], start_date='2014-12-31', end_date='2018-12-31')['Adj. Close'])
    data = pd.DataFrame({'Date':series.index, tickers[stock]:series.values})
    portfolio = portfolio.append(data)

Ok, trying to help here, my guess is you want the data for all 3 tickers in separate columns in the same dataframe. You can do this as follows:

import quandl

First you create an empty dataframe portfolio to which you can merge your downloaded data. This dataframe gets an index with all possible dates:

datetime_index = pd.DatetimeIndex(start='2014-12-31', end='2018-12-31', freq='D')
portfolio = pd.DataFrame(index=datetime_index)

Then you download the ticker data and merge that with the portfolio dataframe as follows:

tickers=['MMM','AOS','ABT']
for ticker in tickers:
    ticker_data = (
        quandl.get('WIKI/' + ticker, 
                   start_date='2014-12-31', 
                   end_date='2018-12-31')['Adj. Close']
              .rename(ticker)
    )
    portfolio = pd.concat([portfolio, ticker_data], axis=1)

Now check the result:

portfolio.head(3)
            MMM     AOS     ABT
2014-12-31  153.100 27.278  42.024
2015-01-01  nan     nan     nan
2015-01-02  152.857 27.084  41.912

Please let me know if this is what you need and upvote/accept the result when correct. In the future: when you ask questions, always add an example of what you want the end result to be.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM