MaltheNybjerg
MaltheNybjerg

Reputation: 11

How can i append a list to a dataframe via for loop in a for loop

I have made a for loop which uses a list of stock tickers to get day closing prices. Once collected, I ask the code to store the data in a dataframe. This works fine, but I am having trouble creating a way to append the dataframe over and over again, such that I am left with one large dataframe. Can anybody help with that? Please note that the API connection allows a certain amount of calls pr. minutes and so there should be a time-extension if the call fails - I have tried to account for this. Please see code below:

C20 = ['AMBU-B.CPH', 'MAERSK-B.CPH']

df = pd.DataFrame()

def getdata(symbol_input):

for i in symbol_input:

    try:

        API_KEY = 'XXXXXXXXX' #MY API KEY

        symbol = i #søg på google efter firmanavnet og "stock price". Tickeren er den der skal bruges

        r = requests.get('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=' + i + '&apikey=' + API_KEY)

        result = r.json()
        AllData = result['Time Series (Daily)']
        alldays = list(AllData.keys())
        alldays.sort()
        timeinterval = 10
        days = alldays[len(alldays)-timeinterval:len(alldays)]
        #print(days)

        SymbolList = []
        for i in range(timeinterval):
            SymbolList.append(symbol)
        #print(SymbolList)

        StockPriceList = []


        if (r.status_code == 200):

            for i, day in enumerate(days):
                result = r.json()
                dataForAllDays = result['Time Series (Daily)']
                dataForSingleDate = dataForAllDays[days[i]]
                #print (days[i], dataForSingleDate['4. close']) 
                StockPriceList.append(dataForSingleDate['4. close'])  


        #print(StockPriceList)

        combined_lists = list(zip(days, StockPriceList, SymbolList)) #create tuples to feed into dataframe from multiple lists

        df1 = pd.DataFrame(combined_lists, columns = ['Date', 'Price', 'Stock Ticker'])
        print(df1)

        time.sleep(10)

    except:
        print('could not get data for: ' + i)
        time.sleep(1)  # wait for 1 seconds before trying to fetch the data again
        continue

print(getdata(C20))

Upvotes: 1

Views: 141

Answers (1)

High-Octane
High-Octane

Reputation: 1112

You can use pd.concat and then joining everything by using temporary dataframe into one final dataframe.

You can use this code as an example for concatenating two different dataframes into a single final dataframe.

dataset1 = pd.DataFrame([[1,2],[2,3],[3,4]],columns=['A','B'])
dataset2 = pd.DataFrame([[4,5],[5,6],[6,7]],columns=['A','B'])
full_dataset = pd.concat([dataset1,dataset2])
full_dataset
   A  B
0  1  2
1  2  3
2  3  4
0  4  5
1  5  6
2  6  7

Reference: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.concat.html

Let me know if you require anything else. Have a great day!

Upvotes: 1

Related Questions