-
-
Notifications
You must be signed in to change notification settings - Fork 338
Simple Parallel Execution of HTTP Daily Candles Example
hmanfarmer edited this page Sep 3, 2020
·
2 revisions
This example demonstrates the following:
- Uses the asyncio library to run multiple calls to HTTP get_price_history in parallel.
- Parallel execution of http API calls can speed up execution times considerably.
The example queries TD Ameritrade for the previous 10 day's daily candles for GOOG, AAPL, and NFLX. Then, the example prints the closing prices for those days.
from tda.auth import easy_client
from tda.client import Client
from tda.streaming import StreamClient
import asyncio
from datetime import datetime, timezone, timedelta
client = easy_client(
api_key='11111111',
redirect_uri='https://localhost:8080',
token_path='tokens.ini')
# asyncio.loop.run_in_executor only accepts *args and not **kwargs. Since client.get_price_history()
# accepts 8 arguments, this wrapper is used to keep the code cleaner.
def price_history_wrapper(ticker, start, end):
request = client.get_price_history(ticker,
period_type=client.PriceHistory.PeriodType.MONTH,
frequency_type=client.PriceHistory.FrequencyType.DAILY,
start_datetime=start,
end_datetime=end)
return request
async def main():
# defining date range for price history
end_date = datetime.now(timezone.utc)
start_date = end_date - timedelta(days=10)
tickers = ['NFLX', 'GOOG', 'AAPL']
# submit all asset histories in parralel.
futures = []
for ticker in tickers:
futures.append(loop.run_in_executor(None, price_history_wrapper, ticker, start_date, end_date))
# retrieve results.
for future in futures:
response_json = (await future).json()
ticker = response_json['symbol']
candles = response_json['candles']
closing_prices = []
for candle in candles:
closing_prices.append(candle['close'])
print('{}: {}'.format(ticker,closing_prices))
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
NFLX: [488.81, 490.58, 547.53, 526.27, 523.89, 529.56, 556.55, 552.84, 526.27]
GOOG: [1588.2, 1608.22, 1652.38, 1634.33, 1644.41, 1634.18, 1660.71, 1728.28, 1639.3421]
AAPL: [125.8575, 124.825, 126.5225, 125.01, 124.8075, 129.04, 134.18, 131.4, 123.24]