How to iterate through a list of keywords to fill a function in Python?

594 Views Asked by At

I am doing a Finance project in Python. I am using pandas dataframes and DataReader to get stock data for different banks. I have a list of 'tickers' which are an input for the following function:

tickers= ['BAC','C','GS','JPM','MS','WFC']            # list of tickers
BAC = data.DataReader('BAC', 'stooq', start, end).    # example function for 1st element 

I could write the function for each element of the list and store it in a different variable. But I would like to automate this process and instead create a function which iterates through the tickers and calls a variable to fill it in with whichever element in the list. Help me out?

4

There are 4 best solutions below

0
RMRiver On

I believe what you want is a simple for loop as a starting point:

returned_values = []
for tick in tickers:
    returned_values.append(data.DataReader(tick, 'stooq', start, end))

The returned_values list will contain all your returned values.

0
Tom McLean On

You can use setattr() to add a variable to a class, but you would need a class to hold the variables:

class DataReader:
    
    def __init__(self, ticker, something, start, stop):
        self.ticker = ticker
        self.something = something
        self.start = start
        self.stop = stop

class test:
    
    def __init__(self, tickers):
        
        for t in tickers:
            setattr(self, t, DataReader(t, 'stooq', 1, 1))

new = test(['BAC','C','GS','JPM','MS','WFC'])

test:

print(new.BAC)
<__main__.DataReader object at 0x0000017847C10128>

However a better way would be holding the objects in a dictionary:

tickers = {t: DataReader(t, 'stooq', 1, 1) for t in ['BAC','C','GS','JPM','MS','WFC']}

output:

{'BAC': <__main__.DataReader at 0x17847d6af28>,
 'C': <__main__.DataReader at 0x17847d6ac18>,
 'GS': <__main__.DataReader at 0x17847d6af60>,
 'JPM': <__main__.DataReader at 0x17847d6afd0>,
 'MS': <__main__.DataReader at 0x17847d6a7f0>,
 'WFC': <__main__.DataReader at 0x17847d6a828>}
0
not_speshal On

You could just store all the results in a dict and access whichever one you need:

my_dict = {t: data.DataReader(t, 'stooq', start, end) for t in tickers}
0
Andreas On

You can fill a dictionary like this:

tickers = ['BAC','C','GS','JPM','MS','WFC']
BAC = {tick:data.DataReader(tick, 'stooq', start, end) for tick in tickers}