refactor: Improve get_current_prices function with robust price fetching logic
This commit is contained in:
parent
4321c3ff66
commit
4ca31ebb06
@ -556,59 +556,6 @@ def get_open_trades():
|
|||||||
print(f"Error in get_open_trades: {str(e)}") # Debug
|
print(f"Error in get_open_trades: {str(e)}") # Debug
|
||||||
raise
|
raise
|
||||||
|
|
||||||
def get_current_prices(tickers: list) -> dict:
|
|
||||||
"""Get current prices for multiple tickers using yfinance"""
|
|
||||||
if not tickers:
|
|
||||||
return {}
|
|
||||||
|
|
||||||
prices = {}
|
|
||||||
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:
|
def delete_trade(trade_id: int) -> bool:
|
||||||
"""
|
"""
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user