ZhuLinsen/daily_stock_analysis · error · DataFetchError

[AlphaVantage] HTTP request failed for {symbol}: {e}

Error message

[AlphaVantage] HTTP request failed for {symbol}: {e}

What it means

A DataFetchError raised by AlphaVantageFetcher._fetch_raw_data wrapping any exception from the HTTP round-trip: requests.get (timeout=30s, after a 0.5-1.5s random sleep), raise_for_status, or resp.json() parsing. The original exception is chained via __cause__, and the symbol is included in the message for correlation.

Source

Thrown at data_provider/alphavantage_fetcher.py:61

            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

        if 'Note' in data:
            raise DataFetchError(f"[AlphaVantage] Rate limited: {data['Note']}")
        if 'Error Message' in data:
            raise DataFetchError(f"[AlphaVantage] API error for {symbol}: {data['Error Message']}")

        ts_key = 'Time Series (Daily)'
        if ts_key not in data or not data[ts_key]:
            raise DataFetchError(f"[AlphaVantage] No time series data for {symbol}")

        rows = []
        start = datetime.strptime(start_date, '%Y-%m-%d').date()
        end = datetime.strptime(end_date, '%Y-%m-%d').date()
        for date_str, values in data[ts_key].items():
            row_date = datetime.strptime(date_str, '%Y-%m-%d').date()
            if start <= row_date <= end:
                rows.append({
                    'date': date_str,

View on GitHub (pinned to 5159bd72e8)

Solutions

  1. Read e.__cause__: requests.exceptions.Timeout/ConnectionError → network; HTTPError → check status code; JSONDecodeError → gateway HTML error page.
  2. Test connectivity: curl 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=IBM&apikey=demo'.
  3. Fix or unset proxy env vars if they intercept the request.
  4. Retry transient timeouts once, then let the fetcher chain fall back to Yfinance/Akshare for US symbols.

Example fix

# before
resp = requests.get(_AV_BASE_URL, params=params, timeout=30)

# after (caller side)
try:
    df = av_fetcher.fetch(sym, start, end)
except DataFetchError as e:
    if isinstance(e.__cause__, requests.exceptions.Timeout):
        df = av_fetcher.fetch(sym, start, end)  # one retry
    else:
        raise
Defensive patterns

Strategy: retry

Validate before calling

import socket, requests
requests.get('https://www.alphavantage.co/query',
            params={'function': 'TIME_SERIES_DAILY', 'symbol': 'IBM', 'apikey': 'demo'},
            timeout=10)  # connectivity pre-flight

Try / catch

import requests
from data_provider.base import DataFetchError
try:
    df = av_fetcher.fetch(sym, start, end)
except DataFetchError as e:
    if isinstance(e.__cause__, (requests.exceptions.Timeout, requests.exceptions.ConnectionError)):
        time.sleep(5)
        df = av_fetcher.fetch(sym, start, end)  # single retry
    else:
        raise

Prevention

When it happens

Trigger: Network unreachable/DNS failure, TLS interception by corporate proxy, HTTP 4xx/5xx from alphavantage.net (raise_for_status), or a non-JSON response body causing JSONDecodeError — all within the single try block around the request.

Common situations: Firewalled environments blocking alphavantage.net; expired/wrong key causing HTTP 403-class responses; proxy env vars (HTTP_PROXY/HTTPS_PROXY) pointing at a dead proxy; occasional AV gateway 502/504s.

Related errors


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