首页 > 解决方案 > 每次运行函数时如何增加函数变量

问题描述

对股票数据进行 alpha vantage api pull。在我下面的代码中,api pull 中有三个变量:fastperiod、slowperiod 和 matype。我试图找出一种方法来一遍又一遍地运行这个函数,每次这三个变量为下一次拉动而改变。matype 可以是 0-8 之间的整数。fastperiod 和slowperiod 可以是1-100 之间的整数。所以理论上,这个东西会一遍又一遍地运行,这些变量每次都在变化,直到这三个变量的所有可能变化都用尽了。

有什么建议么?

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)

标签: python

解决方案


为了加快速度,您可以使用itertools.product(). 对于您的具体情况,它看起来像:

    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

推荐阅读