Functions to fetch from Twelve Data API
request_twelvedata_api.py: function
This module is a gate between the Twelve Data API and this app.
- src.request_twelvedata_api.check_twelvedata_api_response(response: Response) Dict[str, str | list]
Format Twelve Data API response.
This function take care of the data output from Twelve Data API.
- Parameters:
response (requests.Response) – The Twelve Data API response.
- Returns:
This is the result format of the backend.
- Return type:
Dict[str, str | list]
- Raises:
TwelveDataApiException – Exception with the Twelve Data API code: the error code message: message related to the exception
Examples
If the Twelve Data API returns good quality results for the ressource :
>>> check_twelvedata_api_response(requests.get("http://api.twelvedata.com/ressource")) {"status": "ok", "data": ...}
If the URL is ressources does not exists on the API :
>>> check_twelvedata_api_response(requests.get("http://api.twelvedata.com/badRessource")) {"status": "error", "code": 404, "message": "Not found"}
If an error happened server-side from Twelve Data API :
>>> check_twelvedata_api_response(requests.get("http://api.twelvedata.com/badRessource")) {"status": "error", "code": 429, "message": "You have run out of API credits for the current minute."}
For a full list of errors, see https://twelvedata.com/docs#errors
If the ressource is not what was expected :
>>> check_twelvedata_api_response(requests.get("http://api.twelvedata.com/badRessource")) {"status": "error", "code": 500, "message": AssertionError or TypeCheckError message}
- src.request_twelvedata_api.get_available_symbols_list(api_key: str, plan: str = 'Basic') Dict[str, str | Dict[str, List[str]]]
Retrieves available symbol.
Fetch Twelve data API for symbols available with the given plan?
- Parameters:
api_key (str) – The API key
plan (str, optional) – The desired plan, by default “Basic”.
- Returns:
Dict with result
- Return type:
Dict[str, str | Dict[str, List[str]]]
Examples
If all goes right :
>>> res = get_available_symbols_list(API_KEY, "Basic") >>> res['status'] ok >>> res['data'] {'ASE': ['HTO'], 'ASX': ['ADS', 'PKO', 'TRP', 'WBC'], 'BCBA': ['AAPL', 'ADS', 'INFY', 'MELI', 'QQQ'], 'BIST': ['THYAO'], ... 'XETR': ['ADS', 'VOW3'], 'XHAN': ['ADS', 'VOW3'], 'XKUW': ['CGCK'], 'XSTU': ['4BD', 'ADS', 'MAOA']}
If something went wrong :
>>> get_available_symbols_list(API_KEY, "Basic") {"status": "error", "code": 500, "message": "Erreur"}
See
src.exceptions_twelvedata_api.handle_exception()
for more informations on possible errors.
- src.request_twelvedata_api.get_markets_state(api_key: str) Dict[str, str | int | DataFrame]
Retrieves market state from Twelve Data API.
If request fails (not enough token), status is “ko” and df is None. If request succeeds, status is “ok” and df contains the dataframe with columns name, country, is_market_open, time_to_open, time_to_close, time_after_open, date_check.
- Parameters:
api_key (str) – API key for the Twelve Data API.
- Returns:
Dict[str, str | int | pd.DataFrame] res[“status”] is ok or error If status is error, dict contains code of error and message If status is ok, dict contains market state dataframe
- Return type:
Dict[str, str | int | pd.DataFrame]
Examples
If all goes right :
>>> res = get_markets_state(API_KEY) >>> res['status'] ok >>> res['data'] exchange country isMarketOpen timeToOpen timeToClose 0 NYSE United States True 0 days 00:00:00 0 days 02:56:09 3 NASDAQ United States True 0 days 00:00:00 0 days 02:56:09
If something went wrong :
>>> get_markets_state(API_KEY) {"status": "error", "code": 500, "message": "Erreur"}
See
src.exceptions_twelvedata_api.handle_exception()
for more informations on possible errors.
- src.request_twelvedata_api.get_stock_timeseries(symbol: str, time_delta: str, api_key: str) Dict[str, str | int | DataFrame]
Request the twelve data API for stock informations.
This function requests meta and time series for the requested instrument. It also evaluates the cumulative return, the annualized cumulative return and annualized volatility.
- Parameters:
symbol (str) – The instrument symbol.
- Returns:
- res[“status”] is ok or error
if status is error, dict contains code of error and message
if status is ok, dict contains exchange and data in dataframe
- Return type:
Dict[str, str | int | pd.DataFrame]
Examples
Request time series for Apple :
>>> res = get_stock_timeseries("AAPL", API_KEY) >>> res['status'] ok >>> res['exchange'] NASDAQ >>> res['timezone'] America/New_York >>> res['data'] datetime 2019-06-20 04:00:00 49.69750 2019-06-20 12:00:00 49.84485 2019-06-21 04:00:00 50.06215 2019-06-21 12:00:00 49.69250 2019-06-24 04:00:00 49.87000 ... 2023-06-06 09:30:00 179.16000 2023-06-07 09:30:00 177.82001 2023-06-08 09:30:00 180.53999 2023-06-09 09:30:00 181.03999 2023-06-12 09:30:00 183.84000 Name: close, Length: 1228, dtype: float64
If something went wrong :
>>> get_stock_timeseries("AAPL", API_KEY) {"status": "error", "code": 500, "message": "Erreur"}
See
src.exceptions_twelvedata_api.handle_exception()
for more informations on possible errors.