Fix price fetch failing after market hours by adding 5-day daily fallback

period=1d interval=1m returns empty after NSE closes at 3:30 PM IST.
Fall back to period=5d interval=1d to get last available close price.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
Thigazhezhilan J 2026-05-28 18:50:48 +05:30
parent b06f7d4ffa
commit 622a74724b

View File

@ -78,6 +78,7 @@ def fetch_live_price(
):
if allow_cache is None:
allow_cache = ALLOW_PRICE_CACHE
# Try intraday (works during market hours)
try:
df = yf.download(
ticker,
@ -97,6 +98,26 @@ def fetch_live_price(
except Exception:
pass
# Fallback: last close from past 5 days (works after market hours)
try:
df = yf.download(
ticker,
period="5d",
interval="1d",
auto_adjust=True,
progress=False,
timeout=5,
)
if df is not None and not df.empty:
close_value = df["Close"].iloc[-1]
if hasattr(close_value, "iloc"):
close_value = close_value.iloc[-1]
price = float(close_value)
_set_last_price(ticker, price, "live", provider="yfinance")
return price
except Exception:
pass
if allow_cache:
last_live = _get_last_live_price(ticker, provider="yfinance")
if last_live is not None: