Dmitry Beresnev commited on
Commit ·
8e87652
1
Parent(s): 3610f46
fix portfolio calculator
Browse files14 unmodified lines15161718192053 unmodified lines747576777879808182838485868788899091929394959697989910010110210310410514 unmodified linesimport pandas as pdimport yfinance as yfimport streamlit as st# Constants53 unmodified lines# Log the error but continue to fallback strategyprint(f"Batch download failed: {str(e)}, trying individual downloads...")# Strategy 2: Download one ticker at a timest.info("Fetching data individually for each ticker...")individual_prices = {}failed_tickers = []for ticker in ticker_list:try:# Use Ticker object for more reliable downloadsticker_obj = yf.Ticker(ticker)hist = ticker_obj.history(period=period)if hist.empty:failed_tickers.append(ticker)continue# Extract close pricesindividual_prices[ticker] = hist['Close']except Exception as e:failed_tickers.append(ticker)print(f"Failed to fetch {ticker}: {str(e)}")continue# Check if we got any dataif not individual_prices:return None, f"Could not fetch data for any tickers. Failed: {', '.join(failed_tickers)}"# Combine all individual price seriesprices_df = pd.DataFrame(individual_prices)14 unmodified lines1516171819202153 unmodified lines7576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513614 unmodified linesimport pandas as pdimport yfinance as yfimport streamlit as stimport time# Constants53 unmodified lines# 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:return None, f"Could not fetch data for any tickers. Failed: {', '.join(failed_tickers)}\n\nTip: Try using the JSON editor to enter a smaller portfolio first, or try again in a few minutes."# Combine all individual price seriesprices_df = pd.DataFrame(individual_prices)
portfolio_calculator.py+51-20