Dmitry Beresnev commited on
Commit ·
42b622f
1
Parent(s): a4fc70c
fix data downloader
Browse files39 unmodified lines4041424344454647484950515253545556575859606162636465663 unmodified lines7071727374757677782 unmodified lines8182838485868788899091929394959697989910010110210310410510610710810911011111211311411539 unmodified linesretry=retry_if_exception_type((ConnectionError, TimeoutError)), # Only retry on network errorsreraise=True)def _fetch_with_retry(ticker_obj, method: str, period: str = "1y"):"""Internal function with retry logic for fetching data.Args:ticker_obj: yfinance Ticker objectmethod: Which method to use ('period', 'short', 'dates')period: Time periodReturns:Historical data or None"""if method == 'period':return ticker_obj.history(period=period)elif method == 'short':return ticker_obj.history(period="6mo")else: # datesimport datetimeend_date = datetime.datetime.now()start_date = end_date - datetime.timedelta(days=365)return ticker_obj.history(start=start_date, end=end_date)def fetch_single_ticker(ticker: str, period: str = "1y") -> Tuple[str, Optional[pd.Series], Optional[str]]:3 unmodified linesThis function runs in a separate process for parallel execution.Uses tenacity for exponential backoff and ratelimit for request throttling.Args:ticker: Ticker symbolperiod: Time period for historical dataReturns:Tuple of (ticker, price_series, error_message)2 unmodified lines# Create fresh Ticker object in this processticker_obj = yf.Ticker(ticker)# Try Method 1: Standard period with retry logictry:hist = _fetch_with_retry(ticker_obj, 'period', period)if not hist.empty:logger.info(f"✅ {ticker}: Fetched {len(hist)} days (method: period)")return ticker, hist['Close'], Noneexcept Exception as e:logger.warning(f"⚠️ {ticker}: Method 1 failed - {str(e)}")# Try Method 2: Shorter periodtry:hist = _fetch_with_retry(ticker_obj, 'short', period)if not hist.empty:logger.info(f"✅ {ticker}: Fetched {len(hist)} days (method: short)")return ticker, hist['Close'], Noneexcept Exception as e:logger.warning(f"⚠️ {ticker}: Method 2 failed - {str(e)}")# Try Method 3: Explicit dates (most reliable)try:hist = _fetch_with_retry(ticker_obj, 'dates', period)if not hist.empty:logger.info(f"✅ {ticker}: Fetched {len(hist)} days (method: dates)")return ticker, hist['Close'], Noneexcept Exception as e:logger.warning(f"⚠️ {ticker}: Method 3 failed - {str(e)}")# All methods failedlogger.error(f"❌ {ticker}: All methods exhausted")return ticker, None, "No data available after all retry attempts"except Exception as e:39 unmodified lines4041424344454647484950515253545556575859603 unmodified lines6465666768697071727374752 unmodified lines7879808182838485868788899091929394959697989910010110210339 unmodified linesretry=retry_if_exception_type((ConnectionError, TimeoutError)), # Only retry on network errorsreraise=True)def _fetch_with_retry(ticker_obj, period: str):"""Internal function with retry logic for fetching data.IMPORTANT: Only uses 'period' parameter (not start/end dates) to avoidyfinance timezone request that incorrectly handles 429 errors.Args:ticker_obj: yfinance Ticker objectperiod: Time period (e.g., '1y', '6mo', '3mo', '1mo')Returns:Historical data or None"""return ticker_obj.history(period=period)def fetch_single_ticker(ticker: str, period: str = "1y") -> Tuple[str, Optional[pd.Series], Optional[str]]:3 unmodified linesThis function runs in a separate process for parallel execution.Uses tenacity for exponential backoff and ratelimit for request throttling.IMPORTANT: Only uses 'period' parameter (not start/end dates) to avoidyfinance timezone request that incorrectly handles 429 errors.Args:ticker: Ticker symbolperiod: Time period for historical data (default: '1y')Returns:Tuple of (ticker, price_series, error_message)2 unmodified lines# Create fresh Ticker object in this processticker_obj = yf.Ticker(ticker)# Fallback periods to try (from longest to shortest)# Avoid 'max' as it may trigger timezone requestperiods_to_try = [period, '6mo', '3mo', '1mo']for idx, try_period in enumerate(periods_to_try, 1):try:hist = _fetch_with_retry(ticker_obj, try_period)if not hist.empty and len(hist) > 0:logger.info(f"✅ {ticker}: Fetched {len(hist)} days (period: {try_period})")return ticker, hist['Close'], Noneexcept Exception as e:logger.warning(f"⚠️ {ticker}: Period '{try_period}' failed - {str(e)}")if idx == len(periods_to_try):# Last attempt failedlogger.error(f"❌ {ticker}: All periods exhausted")return ticker, None, f"All periods failed. Last error: {str(e)}"# Continue to next period# All periods failedlogger.error(f"❌ {ticker}: No data available after trying all periods")return ticker, None, "No data available after all retry attempts"except Exception as e:
portfolio_calculator.py+30-42