Purpose
The point of this mini project is to quickly gather data from a website's API and combine the collected DataFrames into a "master" DataFrame with all of the stocks I am interested in looking at. I do this using the iexfinance
module. If needed, here is the code behind iexfinance
.
Improvements?
While this module does a great job of dealing with the API, I'm not sure my code is as fast as it could be. Because the iexfinance
module uses requests
to make GET requests, I believe there should be a faster way to asynchronously send GET requests instead of having to use multiprocessing
. Below is my code:
import pandas as pd
import numpy as np
from iexfinance import Stock
from multiprocessing import Pool
import os
def iex_get_stat(batch):
"""
:param batch: batch is a list of stock tickers (ex: ["AAPL", "MSFT", "TSLA"]
Gets and returns DataFrames of stats on a list of stocks
"""
frame = Stock(batch, output_format="pandas").get_key_stats().T
return frame
def get_stats(symbols):
"""
:param symbols: List of symbols (can only send 100 at a time,
so these may need to be broken up)
:return: Pandas DataFrame with stats
"""
symbols = [symbols[i : i + 99] for i in range(0, len(symbols), 99)]
frames = []
pool = Pool(processes=os.cpu_count())
frames.append(pool.starmap(iex_get_stat, [[batch] for batch in symbols]))
pool.close()
pool.join()
stats = pd.concat(frames[0])
return stats
if __name__ == "__main__":
symbols = ["AAPL", "TSLA", "MSFT"]
stats = get_stats(symbols)
print(stats)