Reputation: 101
I am trying to leverage multithreading to get this code to run faster and to call the API in a non-sequential way. Does anyone have any ideas on how I can implement it?
# 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))
Upvotes: 0
Views: 34
Reputation: 23624
You can use a 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
Upvotes: 1
Reputation: 94
You should use the asyncio
library. The documentation has some good examples, e.g:
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def main():
print(f"started at {time.strftime('%X')}")
await say_after(1, 'hello')
await say_after(2, 'world')
print(f"finished at {time.strftime('%X')}")
asyncio.run(main())
Upvotes: 0