ThreadPoolExecutor – How can you bring results to Excel?

Question:

I’m using the Yahoo finance API to extract data using ThreadPoolExecutor. Can anyone show me how to bring the output to excel if possible? Thanks

Code

import yfinance as yf
from concurrent.futures import ThreadPoolExecutor

def get_stats(ticker):
    info = yf.Tickers(ticker).tickers[ticker].info
    print(f"{ticker} {info['currentPrice']} {info['marketCap']}")

ticker_list = ['AAPL', 'ORCL', 'PREM.L', 'UKOG.L', 'KOD.L', 'TOM.L', 'VELA.L', 'MSFT', 'AMZN', 'GOOG']

with ThreadPoolExecutor() as executor:
    executor.map(get_stats, ticker_list)

Output

VELA.L 0.035 6004320
UKOG.L 0.1139 18496450
PREM.L 0.461 89516976
ORCL 76.755 204970377216
MSFT 294.8669 2210578825216
TOM.L 0.604 10558403
KOD.L 0.3 47496900
AMZN 3152.02 1603886514176
AAPL 171.425 2797553057792
GOOG 2698.05 1784584732672
Asked By: user3444610

||

Answers:

First, you can make a empty list and feed id with every returned result by the API, then construct a dataframe from it and finally use pandas.to_excel to make the Excel spreadsheet.

Try this :

import yfinance as yf
from concurrent.futures import ThreadPoolExecutor
import pandas as pd


list_of_futures= []

def get_stats(ticker):
    info = yf.Tickers(ticker).tickers[ticker].info
    s= f"{ticker} {info['currentPrice']} {info['marketCap']}"
    list_of_futures.append(s)

ticker_list = ['AAPL', 'ORCL', 'PREM.L', 'UKOG.L', 'KOD.L', 'TOM.L', 'VELA.L', 'MSFT', 'AMZN', 'GOOG']

with ThreadPoolExecutor() as executor:
    executor.map(get_stats, ticker_list)
    
(
    pd.DataFrame(list_of_futures)
        [0].str.split(expand=True)
        .rename(columns={0: "Ticker", 1: "Price", 2: "Market Cap"})
        .to_excel("yahoo_futures.xlsx", index=False)
)

# Output (dataframe)

   Ticker   Price     Market Cap
0  UKOG.L   0.064       14417024
1  VELA.L  0.0205        3331721
2    AMZN   93.41   952940888064
3    GOOG    97.6  1261313982464
4    ORCL   82.72   223027183616
5   KOD.L    0.28       47330360
6    AAPL  148.11  2356148699136
7    MSFT  247.49  1844906819584
8   TOM.L   0.455        9117245
9  PREM.L    0.57      127782592
Answered By: abokey