ZhuLinsen/daily_stock_analysis · error · DataFetchError

[AlphaVantage] API key not configured

Error message

[AlphaVantage] API key not configured

What it means

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.

Source

Thrown at data_provider/alphavantage_fetcher.py:43


class AlphaVantageFetcher(BaseFetcher):
    name = "AlphaVantageFetcher"
    priority = 3

    def __init__(self):
        from src.config import get_config
        config = get_config()
        self._api_key = getattr(config, 'alphavantage_api_key', None) or os.getenv('ALPHAVANTAGE_API_KEY')
        if not self._api_key:
            logger.debug("[AlphaVantage] API key not configured, fetcher disabled")

    def _is_us_stock(self, stock_code: str) -> bool:
        return is_us_stock_code(stock_code)

    def _fetch_raw_data(self, stock_code: str, start_date: str, end_date: str) -> pd.DataFrame:
        if not self._api_key:
            raise DataFetchError("[AlphaVantage] API key not configured")
        if not self._is_us_stock(stock_code):
            raise DataFetchError(f"[AlphaVantage] {stock_code} is not a US stock")

        symbol = stock_code.strip().upper()
        params = {
            'function': 'TIME_SERIES_DAILY',
            'symbol': symbol,
            'outputsize': 'compact',
            'apikey': self._api_key,
        }

        try:
            self.random_sleep(0.5, 1.5)
            resp = requests.get(_AV_BASE_URL, params=params, timeout=30)
            resp.raise_for_status()
            data = resp.json()
        except Exception as e:
            raise DataFetchError(f"[AlphaVantage] HTTP request failed for {symbol}: {e}") from e

View on GitHub (pinned to 5159bd72e8)

Solutions

  1. Set ALPHAVANTAGE_API_KEY in the environment (or .env) with a valid key from alphavantage.co and restart the process — __init__ reads it once.
  2. Alternatively set alphavantage_api_key in the app config object the fetcher loads via get_config().
  3. Verify with a debug log or by checking self._api_key after init that the key resolved.
  4. If intentionally not using AlphaVantage, ensure it sits last/absent in the fetcher chain so this error only surfaces as a skipped source.

Example fix

# before
# .env has no key; every fetch raises
fetcher = AlphaVantageFetcher()

# .env
ALPHAVANTAGE_API_KEY=YOUR_KEY_HERE

# after (restart required)
fetcher = AlphaVantageFetcher()
assert fetcher._api_key  # configured
Defensive patterns

Strategy: validation

Validate before calling

import os
key = os.getenv('ALPHAVANTAGE_API_KEY')
assert key, 'ALPHAVANTAGE_API_KEY not set — AlphaVantage fetcher will reject every call'

Try / catch

try:
    df = av_fetcher.fetch(sym, start, end)
except DataFetchError as e:
    if 'API key not configured' in str(e):
        logger.info('skipping AlphaVantage (no key configured)')
        df = yfinance_fetcher.fetch(sym, start, end)
    else:
        raise

Prevention

When it happens

Trigger: 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.

Common situations: 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.

Related errors


AI-assisted analysis of ZhuLinsen/daily_stock_analysis@5159bd72e8 (2026-08-15). Data as JSON: /api/errors/6e84416a3f615c1c. Report an issue: GitHub.