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:
|
def get_current_prices(tickers: list) -> dict:
|
||||||
"""Get current prices for multiple tickers using yfinance"""
|
"""Get current prices for multiple tickers using yfinance"""
|
||||||
|
if not tickers:
|
||||||
|
return {}
|
||||||
|
|
||||||
prices = {}
|
prices = {}
|
||||||
for ticker in tickers:
|
try:
|
||||||
try:
|
# Create a space-separated string of tickers
|
||||||
stock = yf.Ticker(ticker)
|
ticker_str = " ".join(tickers)
|
||||||
prices[ticker] = stock.fast_info["last_price"]
|
# Get data for all tickers at once with more reliable settings
|
||||||
except Exception as e:
|
data = yf.download(
|
||||||
print(f"Error getting price for {ticker}: {e}")
|
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
|
return prices
|
||||||
|
|
||||||
def delete_trade(trade_id: int) -> bool:
|
def delete_trade(trade_id: int) -> bool:
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user