【问题标题】:How do you make faster A.P.I calls using multithreading without using requests in Python?如何在不使用 Python 请求的情况下使用多线程进行更快的 A.P.I 调用?
【发布时间】:2023-02-26 22:00:52
【问题描述】:

我正在尝试接收标准普尔 500 指数中每家公司的历史股票数据。问题是获取数据需要很长时间。

from ApiStuff import ApiStuff
import fundamentalanalysis as fa
import pickle

tickers = pickle.load(open('S&P500_TICKERS.dat','rb'))

api_key = ApiStuff.api_key
data_from_tickers = []

for ticker in tickers:
    balance_sheet_annually  = fa.balance_sheet_statement(ticker, api_key, period="annual")
    data_from_tickers.append(balance_sheet_annually)

我尝试在互联网上搜索如何加快速度,但他们使用其他模块(即请求、aiohttp)来更快地检索数据,我依赖这个模块(基本面分析)来检索基本数据。

有没有办法让我仍然使用这个模块并通过描述的方法更快地发出 api 请求?

【问题讨论】:

    标签: python python-3.x api python-asyncio python-multithreading


    【解决方案1】:

    如果 fundamentalanalysis 支持多线程,可以通过将 for 循环替换为:

    from concurrent.futures import ThreadPoolExecutor
    
    with ThreadPoolExecutor(max_workers=10) as e:
        data_from_tickers = list(e.map(lambda t: fa.balance_sheet_statement(t, api_key, period="annual"), tickers))
    

    工人的最大数量可以调整。

    【讨论】:

      【解决方案2】:

      您当然可以使用多个进程来做到这一点; concurrent.futures 就是为满足这种需求而设计的。另一方面,这也是一个很好的学习使用开源的机会。 fundamentalanalysis 的来源可在Github 上找到。您使用的函数 balance_sheet_statement 非常简单,基本上由 GET 请求、几个数据映射和 Pandas 数据框的构造组成。

      使用aiohttprequests 复制此逻辑将比争论多处理模块更容易!

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-01-02
        • 2019-11-16
        • 2022-06-12
        • 1970-01-01
        • 1970-01-01
        • 2012-08-12
        • 1970-01-01
        • 2016-05-09
        相关资源
        最近更新 更多