Home > Enterprise >  How do I save each iteration of a for loop in one big DataFrame - Python
How do I save each iteration of a for loop in one big DataFrame - Python

Time:11-03

I want to gather all the historical prices of each stock in the S&P500 in Python. I'm using a package from IEX Cloud which gives me the historical prices of an individual stock. I want a for loop to run through a list of the tickers/symbols from the stock index so that I get all the data in a single DataFrame.

This is the code that produces a DataFrame - in this example I've chosen AAPL for a two year period:

import pyEX as p
sym = 'AAPL'
stock_list = stocks['Ticker'].tolist()
c = p.Client(api_token='TOKEN', version='stable')
timeframe = '2y'
df = c.chartDF(symbol=sym, timeframe=timeframe)[['close']]
df

This DataFrame contains the date and the daily closing price. Now do any of you have any ideas how to loop through my list of tickers, so that I get a comprehensive DataFrame of all the historical prices?

Thank you.

CodePudding user response:

Create an empty list to append to and concat everything together after you iterate over all the tickers

import pyEX as p
import pandas as pd


stock_list = stocks['Ticker'].tolist()
c = p.Client(api_token='TOKEN', version='stable')
timeframe = '2y'

dfs = []  # create an empty list
for sym in stock_list:  # iterate over your ticker list
    df = c.chartDF(symbol=sym, timeframe=timeframe)[['close']]  # create your frame
    dfs.append(df)  # append frame to list
    
final_df = pd.concat(dfs)  # concat all your frames together into one

Update with Try-Except

import pyEX as p
import pandas as pd


stock_list = stocks['Ticker'].tolist()
c = p.Client(api_token='TOKEN', version='stable')
timeframe = '2y'

dfs = []  # create an empty list
for sym in stock_list:  # iterate over your ticker list
    try:
        df = c.chartDF(symbol=sym, timeframe=timeframe)[['close']]  # create your frame
        dfs.append(df)  # append frame to list
    except KeyError:
        print(f'KeyError for {sym}')
    
final_df = pd.concat(dfs)  # concat all your frames together into one
  • Related