S. *_*Naj 3 asynchronous python-3.x python-asyncio yfinance
我需要异步运行 20 个任务(每个任务运行相同的函数,但具有不同的参数)。每个任务都使用Python 的yfinanceAPI 模块。这是我当前的方法:
args;每个元素都是要传递给相应任务的参数。get_data,我将运行该函数 20 次,每次使用不同的参数。main,用于asyncio.gather异步运行 20 个任务。这是(伪)代码:
import asyncio
stocks = []
args = ['arg1', 'arg2', ... , 'arg20']
async def get_data(arg):
stock = Stock(arg)
# do some yfinance calls
return stock
async def main():
global stocks
tasks = [asyncio.ensure_future(get_data(arg)) for arg in args]
stocks = await asyncio.gather(*tasks)
asyncio.run(main())
print(stocks) # should be a list of 20 return values from the 20 tasks
Run Code Online (Sandbox Code Playgroud)
假设每个任务单独运行需要 4 秒。如果异步运行,那么 20 个任务应该在 4 秒内运行。然而,它在 80 秒内运行。如果我删除所有异步代码并仅同步运行它,它会以相同的时间运行。有什么帮助吗?
谢谢。
我已经检查了文档yfinance并查看了requests需求中的库,该库不是异步的。这意味着您不应该将其与 asyncio 模块一起使用,而应该使用theading.Threadorconcurrent.futures.ThreadPoolExecutor来代替。
我为您做了以下示例,请运行它并分享您的结果。
from concurrent.futures import ThreadPoolExecutor
import yfinance as yf
from pprint import pprint
from time import monotonic
def get_stocks_data(name: str) -> dict:
"""some random function which extract some data"""
tick = yf.Ticker(name)
tick_info = tick.info
return tick_info
if __name__ == '__main__':
# some random stocks
stocks = [
'AAPL', 'AMD', 'AMZN', 'FB', 'GOOG', 'MSFT', 'TSLA', 'MSFT',
'AAPL', 'AMD', 'AMZN', 'FB', 'GOOG', 'MSFT', 'TSLA', 'MSFT',
]
start_time = monotonic()
# you can choose max_workers number higher and check if app works faster
# e.g choose 16 as max number of workers
with ThreadPoolExecutor(max_workers=4) as pool:
results = pool.map(get_stocks_data, stocks)
for r in results:
pprint(r)
print("*" * 150)
print(monotonic() - start_time)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2508 次 |
| 最近记录: |