{"record":{"id":"34c257f9c72f4fdb","repo":"ZhuLinsen/daily_stock_analysis","slug":"alphavantage-stock-code-is-not-a-us-stock","errorCode":null,"errorMessage":"[AlphaVantage] {stock_code} is not a US stock","messagePattern":"\\[AlphaVantage\\] (.+?) is not a US stock","errorType":"exception","errorClass":"DataFetchError","httpStatus":null,"severity":"warning","filePath":"data_provider/alphavantage_fetcher.py","lineNumber":45,"sourceCode":"class AlphaVantageFetcher(BaseFetcher):\n    name = \"AlphaVantageFetcher\"\n    priority = 3\n\n    def __init__(self):\n        from src.config import get_config\n        config = get_config()\n        self._api_key = getattr(config, 'alphavantage_api_key', None) or os.getenv('ALPHAVANTAGE_API_KEY')\n        if not self._api_key:\n            logger.debug(\"[AlphaVantage] API key not configured, fetcher disabled\")\n\n    def _is_us_stock(self, stock_code: str) -> bool:\n        return is_us_stock_code(stock_code)\n\n    def _fetch_raw_data(self, stock_code: str, start_date: str, end_date: str) -> pd.DataFrame:\n        if not self._api_key:\n            raise DataFetchError(\"[AlphaVantage] API key not configured\")\n        if not self._is_us_stock(stock_code):\n            raise DataFetchError(f\"[AlphaVantage] {stock_code} is not a US stock\")\n\n        symbol = stock_code.strip().upper()\n        params = {\n            'function': 'TIME_SERIES_DAILY',\n            'symbol': symbol,\n            'outputsize': 'compact',\n            'apikey': self._api_key,\n        }\n\n        try:\n            self.random_sleep(0.5, 1.5)\n            resp = requests.get(_AV_BASE_URL, params=params, timeout=30)\n            resp.raise_for_status()\n            data = resp.json()\n        except Exception as e:\n            raise DataFetchError(f\"[AlphaVantage] HTTP request failed for {symbol}: {e}\") from e\n\n        if 'Note' in data:","sourceCodeStart":27,"sourceCodeEnd":63,"githubUrl":"https://github.com/ZhuLinsen/daily_stock_analysis/blob/5159bd72e8373d215492dff122acc9d389e219c9/data_provider/alphavantage_fetcher.py#L27-L63","documentation":"A guard DataFetchError raised by AlphaVantageFetcher._fetch_raw_data when is_us_stock_code(stock_code) returns False. AlphaVantage's TIME_SERIES_DAILY only covers US symbols, so the fetcher rejects A-share/HK/ETF codes upfront with a clear message instead of sending a doomed API call. The intent is that DataFetcherManager routes the code to a source that supports its market.","triggerScenarios":"Passing codes like '600519' (A-share), 'hk00700' (HK), or an ETF code to AlphaVantageFetcher; also US-like strings that the is_us_stock_code heuristic rejects (e.g. lowercase-only symbols or ones with unexpected suffixes). The check happens before any HTTP request.","commonSituations":"AlphaVantage placed too early in the fetcher priority list so non-US codes hit it first; user config mixing markets in one watchlist; a custom code format (e.g. 'AAPL.US') failing the US heuristic.","solutions":["Only route plain US tickers (e.g. 'AAPL', 'AMD') to AlphaVantageFetcher; move it after market-aware sources in the chain.","If your code format is valid US but rejected, check is_us_stock_code's rules and normalize the symbol (strip suffixes, uppercase) before fetching.","Catch this error as a routing signal and dispatch to Akshare/Baostock per market."],"exampleFix":"# before\ndf = av_fetcher.fetch('600519', start, end)  # raises\n\n# after\nfrom data_provider.utils import is_us_stock_code\nif is_us_stock_code(code):\n    df = av_fetcher.fetch(code, start, end)\nelse:\n    df = manager.fetch(code, start, end)  # market-aware routing","handlingStrategy":"validation","validationCode":"from data_provider.utils import is_us_stock_code\nif not is_us_stock_code(stock_code):\n    raise ValueError(f'{stock_code} must go to an A-share/HK source, not AlphaVantage')","typeGuard":"from data_provider.utils import is_us_stock_code\n\ndef requires_alpha_vantage(code: str) -> bool:\n    \"\"\"True only for plain US tickers AlphaVantage can serve.\"\"\"\n    return is_us_stock_code(code)","tryCatchPattern":"try:\n    df = av_fetcher.fetch(code, start, end)\nexcept DataFetchError as e:\n    if 'is not a US stock' in str(e):\n        df = manager.fetch(code, start, end)  # market-aware routing\n    else:\n        raise","preventionTips":["Route by market before choosing a fetcher; keep AlphaVantage out of the A-share/HK path.","Store watchlist codes with market markers ('hk00700', bare US 'AAPL') so detection is unambiguous.","Treat 'not a US stock' as a skip signal, never a retry."],"tags":["alphavantage","market-routing","validation","stock-code"],"backgroundTag":null,"analyzedSha":"5159bd72e8373d215492dff122acc9d389e219c9","analyzedAt":"2026-08-15T01:59:36.292Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}