|
| 1 | +# -*- coding: utf-8 -*- |
| 2 | +""" |
| 3 | +AlphaVantageFetcher — US market data source (Priority 3) |
| 4 | +
|
| 5 | +Data source: AlphaVantage REST API |
| 6 | +Rate limit: 25 calls/day, 5 calls/min (free tier) |
| 7 | +Markets: US only |
| 8 | +""" |
| 9 | + |
| 10 | +import logging |
| 11 | +import os |
| 12 | +from datetime import datetime |
| 13 | +from typing import Optional |
| 14 | + |
| 15 | +import pandas as pd |
| 16 | +import requests |
| 17 | + |
| 18 | +from .base import BaseFetcher, DataFetchError, STANDARD_COLUMNS |
| 19 | +from .realtime_types import UnifiedRealtimeQuote, RealtimeSource |
| 20 | +from .us_index_mapping import is_us_stock_code |
| 21 | + |
| 22 | +logger = logging.getLogger(__name__) |
| 23 | + |
| 24 | +_AV_BASE_URL = "https://www.alphavantage.co/query" |
| 25 | + |
| 26 | + |
| 27 | +class AlphaVantageFetcher(BaseFetcher): |
| 28 | + name = "AlphaVantageFetcher" |
| 29 | + priority = 3 |
| 30 | + |
| 31 | + def __init__(self): |
| 32 | + from src.config import get_config |
| 33 | + config = get_config() |
| 34 | + self._api_key = getattr(config, 'alphavantage_api_key', None) or os.getenv('ALPHAVANTAGE_API_KEY') |
| 35 | + if not self._api_key: |
| 36 | + logger.debug("[AlphaVantage] API key not configured, fetcher disabled") |
| 37 | + |
| 38 | + def _is_us_stock(self, stock_code: str) -> bool: |
| 39 | + return is_us_stock_code(stock_code) |
| 40 | + |
| 41 | + def _fetch_raw_data(self, stock_code: str, start_date: str, end_date: str) -> pd.DataFrame: |
| 42 | + if not self._api_key: |
| 43 | + raise DataFetchError("[AlphaVantage] API key not configured") |
| 44 | + if not self._is_us_stock(stock_code): |
| 45 | + raise DataFetchError(f"[AlphaVantage] {stock_code} is not a US stock") |
| 46 | + |
| 47 | + symbol = stock_code.strip().upper() |
| 48 | + params = { |
| 49 | + 'function': 'TIME_SERIES_DAILY', |
| 50 | + 'symbol': symbol, |
| 51 | + 'outputsize': 'compact', |
| 52 | + 'apikey': self._api_key, |
| 53 | + } |
| 54 | + |
| 55 | + try: |
| 56 | + self.random_sleep(0.5, 1.5) |
| 57 | + resp = requests.get(_AV_BASE_URL, params=params, timeout=30) |
| 58 | + resp.raise_for_status() |
| 59 | + data = resp.json() |
| 60 | + except Exception as e: |
| 61 | + raise DataFetchError(f"[AlphaVantage] HTTP request failed for {symbol}: {e}") from e |
| 62 | + |
| 63 | + if 'Note' in data: |
| 64 | + raise DataFetchError(f"[AlphaVantage] Rate limited: {data['Note']}") |
| 65 | + if 'Error Message' in data: |
| 66 | + raise DataFetchError(f"[AlphaVantage] API error for {symbol}: {data['Error Message']}") |
| 67 | + |
| 68 | + ts_key = 'Time Series (Daily)' |
| 69 | + if ts_key not in data or not data[ts_key]: |
| 70 | + raise DataFetchError(f"[AlphaVantage] No time series data for {symbol}") |
| 71 | + |
| 72 | + rows = [] |
| 73 | + start = datetime.strptime(start_date, '%Y-%m-%d').date() |
| 74 | + end = datetime.strptime(end_date, '%Y-%m-%d').date() |
| 75 | + for date_str, values in data[ts_key].items(): |
| 76 | + row_date = datetime.strptime(date_str, '%Y-%m-%d').date() |
| 77 | + if start <= row_date <= end: |
| 78 | + rows.append({ |
| 79 | + 'date': date_str, |
| 80 | + '1. open': float(values.get('1. open', 0)), |
| 81 | + '2. high': float(values.get('2. high', 0)), |
| 82 | + '3. low': float(values.get('3. low', 0)), |
| 83 | + '4. close': float(values.get('4. close', 0)), |
| 84 | + '5. volume': float(values.get('5. volume', 0)), |
| 85 | + }) |
| 86 | + |
| 87 | + if not rows: |
| 88 | + raise DataFetchError(f"[AlphaVantage] No data in date range for {symbol}") |
| 89 | + |
| 90 | + df = pd.DataFrame(rows) |
| 91 | + df.index = pd.to_datetime(df['date']) |
| 92 | + return df.drop(columns=['date']) |
| 93 | + |
| 94 | + def _normalize_data(self, df: pd.DataFrame, stock_code: str) -> pd.DataFrame: |
| 95 | + if df.empty: |
| 96 | + return df |
| 97 | + |
| 98 | + df = df.copy() |
| 99 | + df['date'] = pd.to_datetime(df.index).date |
| 100 | + df = df.rename(columns={ |
| 101 | + '1. open': 'open', '2. high': 'high', '3. low': 'low', |
| 102 | + '4. close': 'close', '5. volume': 'volume', |
| 103 | + }) |
| 104 | + # AlphaVantage returns newest-first; sort ascending before computing pct_chg |
| 105 | + df = df.sort_values('date', ascending=True).reset_index(drop=True) |
| 106 | + df['pct_chg'] = df['close'].pct_change() * 100 |
| 107 | + df['pct_chg'] = df['pct_chg'].fillna(0).round(2) |
| 108 | + df['amount'] = df['volume'] * df['close'] |
| 109 | + df['code'] = stock_code |
| 110 | + |
| 111 | + keep = ['code'] + STANDARD_COLUMNS |
| 112 | + df = df[[col for col in keep if col in df.columns]] |
| 113 | + return df |
| 114 | + |
| 115 | + def get_realtime_quote(self, stock_code: str) -> Optional[UnifiedRealtimeQuote]: |
| 116 | + if not self._api_key or not self._is_us_stock(stock_code): |
| 117 | + return None |
| 118 | + |
| 119 | + symbol = stock_code.strip().upper() |
| 120 | + try: |
| 121 | + self.random_sleep(0.5, 1.5) |
| 122 | + resp = requests.get(_AV_BASE_URL, params={ |
| 123 | + 'function': 'GLOBAL_QUOTE', |
| 124 | + 'symbol': symbol, |
| 125 | + 'apikey': self._api_key, |
| 126 | + }, timeout=15) |
| 127 | + resp.raise_for_status() |
| 128 | + data = resp.json() |
| 129 | + except Exception as e: |
| 130 | + logger.warning(f"[AlphaVantage] Realtime quote failed for {symbol}: {e}") |
| 131 | + return None |
| 132 | + |
| 133 | + gq = data.get('Global Quote', {}) |
| 134 | + price_str = gq.get('05. price') |
| 135 | + if not price_str: |
| 136 | + return None |
| 137 | + |
| 138 | + price = float(price_str) |
| 139 | + prev_close = float(gq.get('08. previous close', 0)) |
| 140 | + change_pct_str = gq.get('10. change percent', '0%').replace('%', '') |
| 141 | + change_pct = float(change_pct_str) if change_pct_str else None |
| 142 | + |
| 143 | + return UnifiedRealtimeQuote( |
| 144 | + code=symbol, |
| 145 | + source=RealtimeSource.FALLBACK, |
| 146 | + price=price, |
| 147 | + change_pct=round(change_pct, 2) if change_pct is not None else None, |
| 148 | + change_amount=round(float(gq.get('09. change', 0)), 4), |
| 149 | + volume=int(float(gq.get('06. volume', 0))), |
| 150 | + amount=None, |
| 151 | + volume_ratio=None, |
| 152 | + turnover_rate=None, |
| 153 | + amplitude=None, |
| 154 | + open_price=float(gq.get('02. open', 0)), |
| 155 | + high=float(gq.get('03. high', 0)), |
| 156 | + low=float(gq.get('04. low', 0)), |
| 157 | + pre_close=prev_close, |
| 158 | + ) |
| 159 | + |
| 160 | + def get_stock_name(self, stock_code: str) -> Optional[str]: |
| 161 | + if not self._api_key or not self._is_us_stock(stock_code): |
| 162 | + return None |
| 163 | + |
| 164 | + symbol = stock_code.strip().upper() |
| 165 | + try: |
| 166 | + resp = requests.get(_AV_BASE_URL, params={ |
| 167 | + 'function': 'SYMBOL_SEARCH', |
| 168 | + 'keywords': symbol, |
| 169 | + 'apikey': self._api_key, |
| 170 | + }, timeout=10) |
| 171 | + resp.raise_for_status() |
| 172 | + data = resp.json() |
| 173 | + except Exception as e: |
| 174 | + logger.debug(f"[AlphaVantage] Symbol search failed for {symbol}: {e}") |
| 175 | + return None |
| 176 | + |
| 177 | + for match in data.get('bestMatches', []): |
| 178 | + if match.get('1. symbol') == symbol and match.get('2. name'): |
| 179 | + return match['2. name'] |
| 180 | + return None |
0 commit comments