How can I get multiple dataframes returned from a class function?

Tags: , , ,

So I have made a class that takes in a ticker symbol, and it returns a dataframe with all the price information for the dates specified. here is the code below:

import pandas as pd
import numpy as np
import pandas_datareader as pdr

# class to get stock price

class GetStockInfo():

    Class to retrieve stock info and returns it as a dataframe

    def __init__(self, ticker):

        self.ticker = ticker.upper()

    def build_df(self, start_date, end_date):

        df = pd.DataFrame(pdr.DataReader(self.ticker, 'yahoo', start_date, end_date))

        return df

now this works perfectly, but ideally id like to pass in a list of symbols and have it return a seperate df for each symbol. so for example,

symbols = ['aapl','googl','msft','tsla']

and id like it to return 4 seperate dfs, each named aapl_df, msft_df etc. is there any way to do this?

ive tried using a for loop like so

for i in symbols:
    stock = GetStockInfo(i)

    i_df = stock.build_df('2019-01-01', '2020-01-01')

but im not sure how to get it to return seperate dfs.


As I commented, you can also do something like this:


I guess you don’t need to __init__ at all

class GetStockInfo():

    Class to retrieve stock info and returns it as a dataframe

    def __init__(self):


    def build_df(self, stock, start_date, end_date):

        df = pd.DataFrame(pdr.DataReader(stock.upper(), 'yahoo', start_date, end_date))

        return df

    def build_multiple(self,symbols,start_dates,end_dates):
        result = {}
        for i in range(len(symbols)):
            result[symbols[i]] = self.build_df(symbols[i],start_dates[i],end_dates[i])
        return result

Also, I think your question more about how to access those dfs like you mentioned aapl_df,msft_df...?

You can just do results['aapl'] instead of writing aapl_df – and so on.

Source: stackoverflow