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:
parent
b06f7d4ffa
commit
622a74724b
@ -1,4 +1,4 @@
|
||||
# engine/data.py
|
||||
# engine/data.py
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
import os
|
||||
@ -6,11 +6,11 @@ import threading
|
||||
|
||||
import pandas as pd
|
||||
import yfinance as yf
|
||||
|
||||
ENGINE_ROOT = Path(__file__).resolve().parents[1]
|
||||
HISTORY_DIR = ENGINE_ROOT / "storage" / "history"
|
||||
ALLOW_PRICE_CACHE = os.getenv("ALLOW_PRICE_CACHE", "0").strip().lower() in {"1", "true", "yes"}
|
||||
|
||||
|
||||
ENGINE_ROOT = Path(__file__).resolve().parents[1]
|
||||
HISTORY_DIR = ENGINE_ROOT / "storage" / "history"
|
||||
ALLOW_PRICE_CACHE = os.getenv("ALLOW_PRICE_CACHE", "0").strip().lower() in {"1", "true", "yes"}
|
||||
|
||||
_LAST_PRICE: dict[str, dict[str, object]] = {}
|
||||
_LAST_PRICE_LOCK = threading.Lock()
|
||||
|
||||
@ -39,10 +39,10 @@ def _set_last_price(
|
||||
|
||||
|
||||
def get_price_snapshot(ticker: str) -> dict[str, object] | None:
|
||||
with _LAST_PRICE_LOCK:
|
||||
data = _LAST_PRICE.get(ticker)
|
||||
if not data:
|
||||
return None
|
||||
with _LAST_PRICE_LOCK:
|
||||
data = _LAST_PRICE.get(ticker)
|
||||
if not data:
|
||||
return None
|
||||
return dict(data)
|
||||
|
||||
|
||||
@ -78,14 +78,35 @@ 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,
|
||||
period="1d",
|
||||
interval="1m",
|
||||
auto_adjust=True,
|
||||
progress=False,
|
||||
timeout=5,
|
||||
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
|
||||
|
||||
# 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]
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user