user7351541
user7351541

Reputation: 3

Adding stock price data frames to a list so you have a list of stock prices histories

I'm trying to get the historical stock price data for all these tickers going back to 2014. All of these companies went public in 2014, so it will automatically get them from the day they first traded.

What I would like is for the stocklist list to contain at the end is a list of dataframes/price histories for each company, but separately and not put together.

So stocklist would be data frames/stock histories for each company, i.e. ['LC', 'ZAYO'] etc.

tickers = ['LC', 'ZAYO', 'GPRO', 'ANET', 'GRUB', 'CSLT', 'ONDK', 'QUOT', 'NEWR', 'ATEN']
stocklist = []

for i in tickers:
    stock = Share(i)
    adj = stock.get_historical('2014-1-1', '2016-12-27')
    df = pd.DataFrame(adj)
    df = df.set_index('Date')
    df['Adj_Close'] = df['Adj_Close'].astype(float, errors='coerce')
    price = df.sort()

i = price
stocklist.append(i)

Upvotes: 0

Views: 1202

Answers (1)

akaihola
akaihola

Reputation: 26835

You're not appending to stocklist inside the loop due to bad indentation.

Also, you're messing with the loop variable i needlessly.

This might work, although it's difficult to test since the Share class is not available:

tickers = ['LC', 'ZAYO', 'GPRO', 'ANET', 'GRUB',
           'CSLT', 'ONDK', 'QUOT', 'NEWR', 'ATEN']
stocklist = []

for ticker in tickers:
    stock = Share(ticker)
    adj = stock.get_historical('2014-1-1', '2016-12-27')
    df = pd.DataFrame(adj)
    df.set_index('Date', inplace=True)
    df['Adj_Close'] = df['Adj_Close'].astype(float, errors='coerce')
    df.sort_index(inplace=True)
    stocklist.append(df)

Changes I made:

  • use tickers as a variable name instead of list which is the name of a built-in type
  • set index and sort the dataframe in-place instead of making copies
  • use DataFrame.sort_index() for sorting since DataFrame.sort() is deprecated
  • fixed indentation so stocklist is populated inside the loop
  • removed the unnecessary assignment before stocklist appending

It might also be more useful to collect the dataframes in a dictionary keyed by tickers. So you would initialize stocklist = {} and instead of appending do stocklist[ticker] = df.

Upvotes: 1

Related Questions