对股票数据进行Alpha Vantage API拉动。在下面的代码中,api pull中包含三个变量:fastperiod,slowperiod和matype。我试图找出一种反复运行此功能的方法,每次这三个变量在下一次拉动时都会更改。 matype可以是0到8之间的整数。快周期和慢周期可以是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)
答案 0 :(得分:2)
要加快进度,您可以使用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
答案 1 :(得分:1)
方法1:易于理解
使用嵌套的for循环迭代输入变量的所有组合。我还修改了范围,假设您实际上想要从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)
方法2:itertools(来自https://stackoverflow.com/a/57245884/9510611以下的sal)
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)