pythonbacktrader

Python dynamic function parameters


When calling the function below, I can provide values that will be used instead of the default parameters in the function (see below).

cerebro.addstrategy(GoldenCross, fast=10, slow=25)

This works great for a small number of known parameters, but I am moving up to more complex systems. Essentially, I need to pass a fast_1, fast_2, fast_3, etc.... The total amount of these parameters will change (always around 100, but it can vary). Is there a statement that I can write that will dynamically add X amount of parameters to my function call?

I have tried using a for statement in the function call, but I received a syntax error.


Solution

  • I understood your question of two ways:

    1. You want to call your function passing to it different parameters (that are optional), you can accomplish it like this:
    def add(first, second=0, third=3):
        return (first+second+third)
        
    number_list = list(range(1, 200))  # Generates a list of numbers
    result = []  # Here will be stored the results
    
    
    for number in number_list:
        # For every number inside number_list the function add will
        # be called, sending the corresponding number from the list.
        returned_result = add(1,second=number)
        result.insert(int(len(result)), returned_result)
    
    print(result) # Can check the result printing it
    
    1. You want your function handles any number of optional parameters, as you don't know any way to determine how many they are, you can send a list or parameters, like this:
    def add(first,*argv):
        for number in argv:
            first += number
        return first
    
    number_list = (list(range(1, 200)))  # Generates a list of numbers
    result = add(1,*number_list)  # Store the result
    
    print(result) # Can check the result printing it
    

    Here you can find more information about *args