prakashkota commited on
Commit
42d4336
·
1 Parent(s): 4f6e268

changed gradio interface to block

Browse files
Files changed (1) hide show
  1. app.py +44 -12
app.py CHANGED
@@ -50,6 +50,10 @@ from pytz import timezone
50
  from pandas.tseries.offsets import BDay
51
  import hashlib
52
 
 
 
 
 
53
  import threading
54
  lock = threading.Lock()
55
  # This forces all inference requests to run one at a time, which avoids file
@@ -69,12 +73,34 @@ scaler_X = joblib.load(os.path.join(model_dir, "scaler_X.pkl"))
69
  scaler_y = joblib.load(os.path.join(model_dir, "scaler_y.pkl"))
70
 
71
  os.environ["YFINANCE_NO_CACHE"] = "1" # <-- 🔥 disables SQLite caching
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
 
73
  # --- Inference Function --- #
74
  def predict_stock():
 
75
  # lightweight log print near the top of predict_stock() to verify it's hitting the cache config:
76
  print("YFINANCE_NO_CACHE =", os.getenv("YFINANCE_NO_CACHE"))
77
-
 
 
 
 
 
78
  # --- Clear yfinance cache to get latest volume and price data --- #
79
  cache_path = os.path.expanduser("~/.cache/py-yfinance")
80
  if os.path.exists(cache_path):
@@ -84,22 +110,28 @@ def predict_stock():
84
  Stock = "NVDA"
85
  start_date = "2020-01-01"
86
  train_end_date = "2024-12-31"
87
- today = datetime.today().strftime('%Y-%m-%d')
 
 
88
 
89
  # Download the full dataset (might contain stale final row)
 
90
  try:
91
- full_data = yf.download(
92
- tickers=Stock,
93
- start=start_date,
94
- end=today,
95
- interval="1d",
96
- auto_adjust=False,
97
- actions=False,
98
- progress=False,
99
- threads=True #<-- for parallel downloads, use True
100
  )
 
101
  if full_data.empty:
102
- raise RuntimeError("Download failed or returned no data.")
 
 
103
  except Exception as e:
104
  print("yfinance error:", e)
105
  return "Error: Could not fetch stock data. Please try again later.", pd.DataFrame()
 
50
  from pandas.tseries.offsets import BDay
51
  import hashlib
52
 
53
+
54
+ import time
55
+ import gc
56
+
57
  import threading
58
  lock = threading.Lock()
59
  # This forces all inference requests to run one at a time, which avoids file
 
73
  scaler_y = joblib.load(os.path.join(model_dir, "scaler_y.pkl"))
74
 
75
  os.environ["YFINANCE_NO_CACHE"] = "1" # <-- 🔥 disables SQLite caching
76
+ os.environ["XDG_CACHE_HOME"] = "/tmp/xfake_cache"
77
+ if not os.path.exists("/tmp/xfake_cache"):
78
+ os.makedirs("/tmp/xfake_cache", exist_ok=True)
79
+
80
+ def safe_download(*args, retries=3, delay=1, **kwargs):
81
+ for i in range(retries):
82
+ try:
83
+ df = yf.download(*args, **kwargs)
84
+ if not df.empty:
85
+ return df
86
+ except Exception as e:
87
+ print(f"[Attempt {i+1}] yfinance error: {e}")
88
+ time.sleep(delay)
89
+ raise RuntimeError("yfinance download failed after retries.")
90
+
91
+ lock = threading.Lock()
92
 
93
  # --- Inference Function --- #
94
  def predict_stock():
95
+
96
  # lightweight log print near the top of predict_stock() to verify it's hitting the cache config:
97
  print("YFINANCE_NO_CACHE =", os.getenv("YFINANCE_NO_CACHE"))
98
+
99
+ # Check for time zone
100
+ now_est = datetime.now(timezone("US/Eastern"))
101
+ print("Current Eastern Time:", now_est)
102
+ print("Trying to fetch data up to:", now_est.strftime('%Y-%m-%d'))
103
+
104
  # --- Clear yfinance cache to get latest volume and price data --- #
105
  cache_path = os.path.expanduser("~/.cache/py-yfinance")
106
  if os.path.exists(cache_path):
 
110
  Stock = "NVDA"
111
  start_date = "2020-01-01"
112
  train_end_date = "2024-12-31"
113
+ #today = datetime.today().strftime('%Y-%m-%d')
114
+ # Use EST for consistently for today
115
+ today = now_est.strftime('%Y-%m-%d')
116
 
117
  # Download the full dataset (might contain stale final row)
118
+ # solves any error with empty dataframes
119
  try:
120
+ full_data = safe_download(
121
+ tickers=Stock,
122
+ start=start_date,
123
+ end=today,
124
+ interval="1d",
125
+ auto_adjust=False,
126
+ actions=False,
127
+ progress=False,
128
+ threads=True #<-- for parallel downloads, use True
129
  )
130
+
131
  if full_data.empty:
132
+ print("yfinance returned empty data for:", today)
133
+ return "Error: Stock data not available at this time. Please try again shortly.", pd.DataFrame()
134
+
135
  except Exception as e:
136
  print("yfinance error:", e)
137
  return "Error: Could not fetch stock data. Please try again later.", pd.DataFrame()