{"record":{"id":"6e84416a3f615c1c","repo":"ZhuLinsen/daily_stock_analysis","slug":"alphavantage-api-key-not-configured","errorCode":null,"errorMessage":"[AlphaVantage] API key not configured","messagePattern":"\\[AlphaVantage\\] API key not configured","errorType":"exception","errorClass":"DataFetchError","httpStatus":null,"severity":"error","filePath":"data_provider/alphavantage_fetcher.py","lineNumber":43,"sourceCode":"\n\nclass 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","sourceCodeStart":25,"sourceCodeEnd":61,"githubUrl":"https://github.com/ZhuLinsen/daily_stock_analysis/blob/5159bd72e8373d215492dff122acc9d389e219c9/data_provider/alphavantage_fetcher.py#L25-L61","documentation":"A guard DataFetchError raised by AlphaVantageFetcher._fetch_raw_data when no API key is configured. The key is resolved once in __init__ from config.alphavantage_api_key or env ALPHAVANTAGE_API_KEY; if neither is set the fetcher logs 'API key not configured, fetcher disabled' at debug and every fetch attempt fails fast with this error instead of making a keyless HTTP call.","triggerScenarios":"Any fetch via AlphaVantageFetcher when both config attribute alphavantage_api_key and environment variable ALPHAVANTAGE_API_KEY are empty/None — e.g. fresh clone without .env, Docker image missing env passthrough, GitHub Actions secret not wired, or a typo'd env var name.","commonSituations":"New deployment where .env.example was copied but ALPHAVANTAGE_API_KEY left blank; secret present under a different name (ALPHA_VANTAGE_KEY); key set after process start so __init__ cached None.","solutions":["Set ALPHAVANTAGE_API_KEY in the environment (or .env) with a valid key from alphavantage.co and restart the process — __init__ reads it once.","Alternatively set alphavantage_api_key in the app config object the fetcher loads via get_config().","Verify with a debug log or by checking self._api_key after init that the key resolved.","If intentionally not using AlphaVantage, ensure it sits last/absent in the fetcher chain so this error only surfaces as a skipped source."],"exampleFix":"# before\n# .env has no key; every fetch raises\nfetcher = AlphaVantageFetcher()\n\n# .env\nALPHAVANTAGE_API_KEY=YOUR_KEY_HERE\n\n# after (restart required)\nfetcher = AlphaVantageFetcher()\nassert fetcher._api_key  # configured","handlingStrategy":"validation","validationCode":"import os\nkey = os.getenv('ALPHAVANTAGE_API_KEY')\nassert key, 'ALPHAVANTAGE_API_KEY not set — AlphaVantage fetcher will reject every call'","typeGuard":null,"tryCatchPattern":"try:\n    df = av_fetcher.fetch(sym, start, end)\nexcept DataFetchError as e:\n    if 'API key not configured' in str(e):\n        logger.info('skipping AlphaVantage (no key configured)')\n        df = yfinance_fetcher.fetch(sym, start, end)\n    else:\n        raise","preventionTips":["Add ALPHAVANTAGE_API_KEY to .env / deployment env from day one; the fetcher reads it only in __init__, so restart after setting.","Fail fast at startup with a config check if AlphaVantage is a required source, rather than per-fetch errors.","Keep a startup assertion on fetcher._api_key in smoke tests."],"tags":["alphavantage","api-key","configuration","env-vars"],"backgroundTag":null,"analyzedSha":"5159bd72e8373d215492dff122acc9d389e219c9","analyzedAt":"2026-08-15T01:59:36.292Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}