Dmitry Beresnev commited on
Commit Β·
a4fc70c
1
Parent(s): 8e87652
fix data downloader
Browse filesFiles changed (2)
14 unmodified lines151617181920212 unmodified lines24252627282943 unmodified lines73747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113214 unmodified linesimport pandas as pdimport yfinance as yfimport streamlit as stimport time# Constants2 unmodified linesMAX_TICKERS = 20@st.cache_data(ttl=3600) # Cache for 1 hourdef fetch_historical_data(tickers: Tuple[str, ...], # Tuple for hashability (caching requirement)43 unmodified linesexcept Exception as e:# Log the error but continue to fallback strategyprint(f"Batch download failed: {str(e)}, trying individual downloads...")# Strategy 2: Download one ticker at a time with retriesst.info("Fetching data individually for each ticker (this may take a moment)...")individual_prices = {}failed_tickers = []for idx, ticker in enumerate(ticker_list):max_retries = 3retry_delay = 2 # secondsfor attempt in range(max_retries):try:# Add delay between requests to avoid rate limiting (except first ticker)if idx > 0 or attempt > 0:time.sleep(retry_delay)# Use Ticker object for more reliable downloadsticker_obj = yf.Ticker(ticker)# Try different methodsif attempt == 0:# Method 1: history with periodhist = ticker_obj.history(period=period)elif attempt == 1:# Method 2: Try shorter periodhist = ticker_obj.history(period="6mo")else:# Method 3: Try start/end datesimport datetimeend_date = datetime.datetime.now()start_date = end_date - datetime.timedelta(days=365)hist = ticker_obj.history(start=start_date, end=end_date)if not hist.empty:# Extract close pricesindividual_prices[ticker] = hist['Close']st.success(f"β {ticker}: {len(hist)} days of data")break # Success, exit retry loopelse:if attempt < max_retries - 1:st.warning(f"β οΈ {ticker}: No data, retrying... (attempt {attempt + 1}/{max_retries})")else:st.error(f"β {ticker}: No data after {max_retries} attempts")failed_tickers.append(ticker)except Exception as e:if attempt < max_retries - 1:st.warning(f"β οΈ {ticker}: Error, retrying... (attempt {attempt + 1}/{max_retries})")retry_delay *= 2 # Exponential backoffelse:failed_tickers.append(ticker)st.error(f"β {ticker}: Failed after {max_retries} attempts")print(f"Failed to fetch {ticker}: {str(e)}")# Check if we got any dataif not individual_prices:14 unmodified lines15161718192021222324252627282 unmodified lines31323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112243 unmodified lines16616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421514 unmodified linesimport pandas as pdimport yfinance as yfimport streamlit as stfrom concurrent.futures import ProcessPoolExecutor, as_completedimport loggingfrom tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_typefrom ratelimit import limits, sleep_and_retry# Configure logginglogging.basicConfig(level=logging.INFO)logger = logging.getLogger(__name__)# Constants2 unmodified linesMAX_TICKERS = 20# Rate limiter: Max 5 calls per 10 seconds per ticker (conservative for Yahoo Finance)@sleep_and_retry@limits(calls=5, period=10)@retry(stop=stop_after_attempt(3), # Max 3 retrieswait=wait_exponential(multiplier=1, min=2, max=60), # Exponential backoff: 2s, 4s, 8s, ... max 60sretry=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]]:"""Fetch historical data for a single ticker with rate limiting and exponential backoff.This 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)"""try:# 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:logger.error(f"β {ticker}: Fatal error - {str(e)}")return ticker, None, str(e)@st.cache_data(ttl=3600) # Cache for 1 hourdef fetch_historical_data(tickers: Tuple[str, ...], # Tuple for hashability (caching requirement)43 unmodified linesexcept Exception as e:# Log the error but continue to fallback strategylogger.warning(f"Batch download failed: {str(e)}, trying individual downloads...")# Strategy 2: Parallel download using ProcessPoolExecutorst.info(f"π₯ Fetching data for {len(ticker_list)} tickers in parallel...")individual_prices = {}failed_tickers = []# Determine number of workers (max 4 to avoid overwhelming the API)max_workers = min(len(ticker_list), 4)try:# Use ProcessPoolExecutor for true parallel executionwith ProcessPoolExecutor(max_workers=max_workers) as executor:# Submit all ticker fetch jobsfuture_to_ticker = {executor.submit(fetch_single_ticker, ticker, period): tickerfor ticker in ticker_list}# Process results as they completecompleted = 0for future in as_completed(future_to_ticker):ticker = future_to_ticker[future]completed += 1try:ticker_symbol, price_series, error = future.result(timeout=30)if price_series is not None and not price_series.empty:individual_prices[ticker_symbol] = price_seriesst.success(f"β {ticker_symbol}: {len(price_series)} days ({completed}/{len(ticker_list)})")else:failed_tickers.append(ticker_symbol)st.error(f"β {ticker_symbol}: {error or 'No data'} ({completed}/{len(ticker_list)})")except Exception as e:failed_tickers.append(ticker)st.error(f"β {ticker}: {str(e)} ({completed}/{len(ticker_list)})")except Exception as e:st.error(f"Parallel processing error: {str(e)}")# Fall back to empty resultpass# Check if we got any dataif not individual_prices:
5 unmodified lines6785 unmodified linesnumpy==1.26.3sympy==1.12matplotlib==3.8.25 unmodified lines6789105 unmodified linesnumpy==1.26.3sympy==1.12matplotlib==3.8.2tenacity==8.2.3ratelimit==2.2.1
portfolio_calculator.py+132-49
requirements.txt+2