Home > Mobile >  How to run same function multiple times and save as new variable
How to run same function multiple times and save as new variable

Time:04-25

Just as the title says, I am trying to run a function about 30 times, but with each time running different variables. I am trying to save each time it runs as a different variable because afterwards, different calculations will be ran on them. Here is a sample:

first = my_func(name = a, desc = b, ticker = c)
first.dict_name1 = z_score(first.data,12)

second = my_func(name = d, desc = e, ticker = f)
second.dict_name1 = ... (a diff calculation)

third = my_func(.....same process....)


class my_func:

    def __init__(
                 self,
                 name       = [],
                 desc       = '',
                 # tickers can be loaded as a list of strings, or if a custom field is needed it can use a tuple
                 tickers    = [],
                 indicator  = [],
                 signal     = []
                ):
    
        self.name       = name
        self.desc       = desc
        self.tickers    = tickers
    
        self.data       = {}
        self._data      = {}
    
        for ticker in tickers:
        
            # check if the ticker is a tuple, if so call the custom field
            if isinstance(ticker, tuple):
                self.load_data(ticker[0],ticker[1])
            else:
                self.load_data(ticker)

    def load_data(self,ticker, field='PX_LAST'):
    
        self.data[ticker] = bbg.bdh(ticker, fld_list = field, start_date='19300101')

CodePudding user response:

Keep the parameters of each run in a list and iterate over it.

lst = [(a, b, c), (d, e, f)]
results = [my_func(name=name, desc=desc, ticker=ticker) for name, desc, ticker in lst]

CodePudding user response:

This is a great use case for loops and lists. A list of lists holds the parameters for each call and they are collected in a results list

my_func_table = 
    # name, desc, ticker
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9] ]

results = []
for name, desc, ticker in my_func_table:
    val = my_func(name=name, desc=desc, ticker=ticker)
    val.dict_name1 = z_score(val.data,12)
    results.append(val)

You could also associate these results with names. Perhaps a dictionary with the names, the global namespace or even a trivial class that has the name as an attribute.

result_names = ["first", "second", etc...]

for var, vals in zip(result_names, my_func_table):
    name, desc, ticker = vals
    val = my_func(name=name, desc=desc, ticker=ticker)
    val.dict_name1 = z_score(val.data,12)
    globals()[var] = val
  • Related