简体   繁体   中英

How to increase a function variable each time the function is run

doing an alpha vantage api pull for stock data. in my code below, there are three variables in the api pull: fastperiod, slowperiod, and matype. i'm trying to figure out a way to run this function over and over again, each time those three variables change for the next pull. the matype can be an integer between 0-8. fastperiod and slowperiod can be an integer between 1-100. so theoretically, this thing would run over and over again, with those variables changing each time, until all possible variations of those three variables were exhausted.

any suggestions?

def get_ppo_close_8():
    pull_parameters = {
        'function': 'PPO',
        'symbol': stock,
        'interval': interval,
        'series_type': 'close',
        'fastperiod': 12,
        'slowperiod': 26,
        'matype': 8,
        'datatype': 'json',
        'apikey': key
    }
    pull = rq.get(url, params=pull_parameters)
    data = pull.json()
    df = pd.DataFrame.from_dict(data['Technical Analysis: PPO'], orient='index', dtype=float)
    df.reset_index(level=0, inplace=True)
    df.columns = ['Date', 'PPO Close 8']
    df.insert(0, 'Stock', stock)
    return df.tail(past_years * annual_trading_days)

METHOD 1: easily understandable

Use a nested for loop to iterate through all combination of your input variables. I've also modified the ranges assuming you actually want the values starting from 1

for matype in range(1,9):
    for slowperiod in range(1,101):
        for fastperiod in range(1,101):
            get_ppo_close_8(matype, slowperiod, fastperiod)

METHOD 2: itertools (from sal below https://stackoverflow.com/a/57245884/9510611 )

matype = range(1,9) 
slowperiod = range(1,101) 
fastperiod = range(1,101)

# product will make a generator that will produce all triplets 
combinations = product(matype, slowperiod, fastperiod) 

# efficiently use them in your function 
for matype, slowperiod, fastperiod in combinations: 
    get_ppo_close_8(matype, slowperiod, fastperiod)

To speed things up you can use itertools.product() . For your specific case it would look something like:

    from itertools import product

    def get_ppo_close_8(matype, slowperiod, fastperiod):
        # Replace the print with your code here
        print(">>>", matype, slowperiod, fastperiod)

    # define your ranges
    matype = range(8)
    slowperiod = range(100)
    fastperiod = range(100)

    # product will make a generator that will produce all triplets
    combinations = product(matype, slowperiod, fastperiod)

    # efficiently use them in your function
    for item in combinations:
        get_ppo_close_8(*item)  # use '*' to unpack

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM