|
| 1 | +import json |
| 2 | + |
| 3 | +from py_alpaca_api.exceptions import APIRequestError, ValidationError |
| 4 | +from py_alpaca_api.http.requests import Requests |
| 5 | + |
| 6 | + |
| 7 | +class Metadata: |
| 8 | + """Market metadata API for condition codes and exchange codes.""" |
| 9 | + |
| 10 | + def __init__(self, headers: dict[str, str]) -> None: |
| 11 | + """Initialize the Metadata class. |
| 12 | +
|
| 13 | + Args: |
| 14 | + headers: Dictionary containing authentication headers. |
| 15 | + """ |
| 16 | + self.headers = headers |
| 17 | + self.base_url = "https://data.alpaca.markets/v2/stocks/meta" |
| 18 | + # Cache for metadata that rarely changes |
| 19 | + self._exchange_cache: dict[str, str] | None = None |
| 20 | + self._condition_cache: dict[str, dict[str, str]] = {} |
| 21 | + |
| 22 | + def get_exchange_codes(self, use_cache: bool = True) -> dict[str, str]: |
| 23 | + """Get the mapping between exchange codes and exchange names. |
| 24 | +
|
| 25 | + Args: |
| 26 | + use_cache: Whether to use cached data if available. Defaults to True. |
| 27 | +
|
| 28 | + Returns: |
| 29 | + Dictionary mapping exchange codes to exchange names. |
| 30 | +
|
| 31 | + Raises: |
| 32 | + APIRequestError: If the API request fails. |
| 33 | + """ |
| 34 | + if use_cache and self._exchange_cache is not None: |
| 35 | + return self._exchange_cache |
| 36 | + |
| 37 | + url = f"{self.base_url}/exchanges" |
| 38 | + |
| 39 | + try: |
| 40 | + response = json.loads( |
| 41 | + Requests().request(method="GET", url=url, headers=self.headers).text |
| 42 | + ) |
| 43 | + except Exception as e: |
| 44 | + raise APIRequestError(message=f"Failed to get exchange codes: {e!s}") from e |
| 45 | + |
| 46 | + if not response: |
| 47 | + raise APIRequestError(message="No exchange data returned") |
| 48 | + |
| 49 | + # Cache the result |
| 50 | + self._exchange_cache = response |
| 51 | + return response |
| 52 | + |
| 53 | + def get_condition_codes( |
| 54 | + self, |
| 55 | + ticktype: str = "trade", |
| 56 | + tape: str = "A", |
| 57 | + use_cache: bool = True, |
| 58 | + ) -> dict[str, str]: |
| 59 | + """Get the mapping between condition codes and condition names. |
| 60 | +
|
| 61 | + Args: |
| 62 | + ticktype: Type of conditions to retrieve ("trade" or "quote"). Defaults to "trade". |
| 63 | + tape: Market tape ("A" for NYSE, "B" for NASDAQ, "C" for other). Defaults to "A". |
| 64 | + use_cache: Whether to use cached data if available. Defaults to True. |
| 65 | +
|
| 66 | + Returns: |
| 67 | + Dictionary mapping condition codes to condition descriptions. |
| 68 | +
|
| 69 | + Raises: |
| 70 | + ValidationError: If invalid parameters are provided. |
| 71 | + APIRequestError: If the API request fails. |
| 72 | + """ |
| 73 | + # Validate parameters |
| 74 | + valid_ticktypes = ["trade", "quote"] |
| 75 | + if ticktype not in valid_ticktypes: |
| 76 | + raise ValidationError( |
| 77 | + f"Invalid ticktype. Must be one of: {', '.join(valid_ticktypes)}" |
| 78 | + ) |
| 79 | + |
| 80 | + valid_tapes = ["A", "B", "C"] |
| 81 | + if tape not in valid_tapes: |
| 82 | + raise ValidationError( |
| 83 | + f"Invalid tape. Must be one of: {', '.join(valid_tapes)}" |
| 84 | + ) |
| 85 | + |
| 86 | + # Check cache |
| 87 | + cache_key = f"{ticktype}_{tape}" |
| 88 | + if use_cache and cache_key in self._condition_cache: |
| 89 | + return self._condition_cache[cache_key] |
| 90 | + |
| 91 | + url = f"{self.base_url}/conditions/{ticktype}" |
| 92 | + params: dict[str, str | bool | float | int] = {"tape": tape} |
| 93 | + |
| 94 | + try: |
| 95 | + response = json.loads( |
| 96 | + Requests() |
| 97 | + .request(method="GET", url=url, headers=self.headers, params=params) |
| 98 | + .text |
| 99 | + ) |
| 100 | + except Exception as e: |
| 101 | + raise APIRequestError( |
| 102 | + message=f"Failed to get condition codes: {e!s}" |
| 103 | + ) from e |
| 104 | + |
| 105 | + if response is None: |
| 106 | + raise APIRequestError(message="No condition data returned") |
| 107 | + |
| 108 | + # Cache the result |
| 109 | + self._condition_cache[cache_key] = response |
| 110 | + return response |
| 111 | + |
| 112 | + def get_all_condition_codes( |
| 113 | + self, use_cache: bool = True |
| 114 | + ) -> dict[str, dict[str, dict[str, str]]]: |
| 115 | + """Get all condition codes for all tick types and tapes. |
| 116 | +
|
| 117 | + Args: |
| 118 | + use_cache: Whether to use cached data if available. Defaults to True. |
| 119 | +
|
| 120 | + Returns: |
| 121 | + Nested dictionary with structure: |
| 122 | + { |
| 123 | + "trade": { |
| 124 | + "A": {condition_code: description, ...}, |
| 125 | + "B": {condition_code: description, ...}, |
| 126 | + "C": {condition_code: description, ...} |
| 127 | + }, |
| 128 | + "quote": { |
| 129 | + "A": {condition_code: description, ...}, |
| 130 | + "B": {condition_code: description, ...}, |
| 131 | + "C": {condition_code: description, ...} |
| 132 | + } |
| 133 | + } |
| 134 | +
|
| 135 | + Raises: |
| 136 | + APIRequestError: If any API request fails. |
| 137 | + """ |
| 138 | + result: dict[str, dict[str, dict[str, str]]] = {} |
| 139 | + |
| 140 | + for ticktype in ["trade", "quote"]: |
| 141 | + result[ticktype] = {} |
| 142 | + for tape in ["A", "B", "C"]: |
| 143 | + try: |
| 144 | + result[ticktype][tape] = self.get_condition_codes( |
| 145 | + ticktype=ticktype, tape=tape, use_cache=use_cache |
| 146 | + ) |
| 147 | + except APIRequestError: |
| 148 | + # Some tape/ticktype combinations might not be available |
| 149 | + result[ticktype][tape] = {} |
| 150 | + |
| 151 | + return result |
| 152 | + |
| 153 | + def clear_cache(self) -> None: |
| 154 | + """Clear all cached metadata. |
| 155 | +
|
| 156 | + This forces the next request to fetch fresh data from the API. |
| 157 | + """ |
| 158 | + self._exchange_cache = None |
| 159 | + self._condition_cache = {} |
| 160 | + |
| 161 | + def lookup_exchange(self, code: str) -> str | None: |
| 162 | + """Look up an exchange name by its code. |
| 163 | +
|
| 164 | + Args: |
| 165 | + code: The exchange code to look up. |
| 166 | +
|
| 167 | + Returns: |
| 168 | + The exchange name if found, None otherwise. |
| 169 | + """ |
| 170 | + exchanges = self.get_exchange_codes() |
| 171 | + return exchanges.get(code) |
| 172 | + |
| 173 | + def lookup_condition( |
| 174 | + self, code: str, ticktype: str = "trade", tape: str = "A" |
| 175 | + ) -> str | None: |
| 176 | + """Look up a condition description by its code. |
| 177 | +
|
| 178 | + Args: |
| 179 | + code: The condition code to look up. |
| 180 | + ticktype: Type of condition ("trade" or "quote"). Defaults to "trade". |
| 181 | + tape: Market tape ("A", "B", or "C"). Defaults to "A". |
| 182 | +
|
| 183 | + Returns: |
| 184 | + The condition description if found, None otherwise. |
| 185 | + """ |
| 186 | + conditions = self.get_condition_codes(ticktype=ticktype, tape=tape) |
| 187 | + return conditions.get(code) |
0 commit comments