Python 如何将多线程应用于此循环和api调用以缩短运行时间?
我正试图利用多线程技术使代码运行得更快,并以非顺序方式调用API。有人对我如何实施它有什么想法吗Python 如何将多线程应用于此循环和api调用以缩短运行时间?,python,pandas,multithreading,api,Python,Pandas,Multithreading,Api,我正试图利用多线程技术使代码运行得更快,并以非顺序方式调用API。有人对我如何实施它有什么想法吗 # START RSI LOOP start_time = time.time() i = 0 for s in Stock: RSI_url = "https://www.alphavantage.co/query?function=RSI&symbol=" + s + "&interval=daily&time_
# START RSI LOOP
start_time = time.time()
i = 0
for s in Stock:
RSI_url = "https://www.alphavantage.co/query?function=RSI&symbol=" + s + "&interval=daily&time_period=14&series_type=close&apikey=" + Token + "&datatype=csv"
rsi=pd.read_csv(RSI_url,usecols= [1],nrows = 1)
#print(rsi)
#print(rsi.loc[i,'RSI'])
df.loc[s,'RSI']=rsi.loc[i,'RSI']
i == i + 1
print(((time.time() - start_time)/60))
你应该使用图书馆。有一些很好的例子,例如:
导入异步IO
导入时间
异步定义在(延迟,什么)之后说:
等待异步睡眠(延迟)
打印(什么)
异步def main():
打印(f“开始于{time.strftime('%X')}”)
等待在(1,‘你好’)之后说
等待在(2,‘世界’)之后说
打印(f“在{time.strftime('%X')}完成”)
asyncio.run(main())
您可以使用ThreadPoolExecutor
:
from concurrent.futures.thread import ThreadPoolExecutor
def get_rsi(stock):
rsi_url = (
"https://www.alphavantage.co/query"
"?function=RSI"
f"&symbol={stock}"
"&interval=daily"
"&time_period=14"
"&series_type=close"
f"&apikey={token}"
"&datatype=csv"
)
rsi = pd.read_csv(rsi_url, usecols=[1], nrows=1)
return stock, rsi
with ThreadPoolExecutor(max_workers=5) as ex:
for stock, rsi in ex.map(get_id, stocks):
df.loc[stock, 'RSI'] = rsi.loc[i, 'RSI']
i = i + 1
谢谢,我会试试看,看看文档