refactor: Improve get_current_prices with robust price fetching and error handling
This commit is contained in:
parent
5910dcad1f
commit
4321c3ff66
@ -558,13 +558,56 @@ def get_open_trades():
|
||||
|
||||
def get_current_prices(tickers: list) -> dict:
|
||||
"""Get current prices for multiple tickers using yfinance"""
|
||||
if not tickers:
|
||||
return {}
|
||||
|
||||
prices = {}
|
||||
for ticker in tickers:
|
||||
try:
|
||||
stock = yf.Ticker(ticker)
|
||||
prices[ticker] = stock.fast_info["last_price"]
|
||||
except Exception as e:
|
||||
print(f"Error getting price for {ticker}: {e}")
|
||||
try:
|
||||
# Create a space-separated string of tickers
|
||||
ticker_str = " ".join(tickers)
|
||||
# Get data for all tickers at once with more reliable settings
|
||||
data = yf.download(
|
||||
ticker_str,
|
||||
period="1d", # Just today's data
|
||||
interval="1d", # Daily interval instead of minute
|
||||
group_by='ticker',
|
||||
progress=False, # Disable progress bar
|
||||
ignore_tz=True # Ignore timezone issues
|
||||
)
|
||||
|
||||
if len(tickers) == 1:
|
||||
# Handle single ticker case
|
||||
if isinstance(data, pd.DataFrame) and 'Close' in data.columns:
|
||||
prices[tickers[0]] = float(data['Close'].iloc[-1])
|
||||
else:
|
||||
# Handle multiple tickers
|
||||
for ticker in tickers:
|
||||
try:
|
||||
if isinstance(data, pd.DataFrame) and (ticker, 'Close') in data.columns:
|
||||
prices[ticker] = float(data[ticker]['Close'].iloc[-1])
|
||||
except Exception as e:
|
||||
print(f"Error processing price for {ticker}: {e}")
|
||||
# Try alternative method for this ticker
|
||||
try:
|
||||
stock = yf.Ticker(ticker)
|
||||
price = stock.history(period='1d')['Close'].iloc[-1]
|
||||
prices[ticker] = float(price)
|
||||
except Exception as e2:
|
||||
print(f"Backup method failed for {ticker}: {e2}")
|
||||
prices[ticker] = 0.0 # Set to 0 if both methods fail
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error in batch price fetch: {e}")
|
||||
# Fall back to individual ticker fetching
|
||||
for ticker in tickers:
|
||||
try:
|
||||
stock = yf.Ticker(ticker)
|
||||
price = stock.history(period='1d')['Close'].iloc[-1]
|
||||
prices[ticker] = float(price)
|
||||
except Exception as e:
|
||||
print(f"Error getting price for {ticker}: {e}")
|
||||
prices[ticker] = 0.0 # Set to 0 if fetch fails
|
||||
|
||||
return prices
|
||||
|
||||
def delete_trade(trade_id: int) -> bool:
|
||||
|
||||
Loading…
Reference in New Issue
Block a user